Modularized and updtaed

This commit is contained in:
Nicola Guerrera
2023-05-14 21:42:04 +02:00
parent ac3961e713
commit 3341fd6316
8 changed files with 656 additions and 1157 deletions

994
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,6 @@ version = "0.4.0"
edition = "2021"
[dependencies]
cached = "0.42.0"
cached = "0.43.0"
clap = { version = "4.1.3", features = ["derive"] }
color-eyre = "0.6.2"
@@ -24,11 +23,6 @@ rustc-hash = "1.1.0"
serde = "1.0.155"
serde_json = "1.0.94"
serde_with = "2.3.1"
stardust-xr-fusion = "0.40.0"
stardust-xr-molecules = "0.24.3"
serde = "1.0.155"
serde_json = "1.0.94"
serde_with = "2.3.1"
stardust-xr-fusion = "0.40.2"
stardust-xr-molecules = "0.24.3"
tokio = { version = "1.24.1", features = ["full"] }
@@ -36,3 +30,6 @@ tracing-subscriber = { version = "0.3.16", features = ["env-filter"] }
tween = "2.0.0"
ustr = "0.9.0"
walkdir = "2.3.2"
[dev-dependencies]
tempdir = "0.3.7"

View File

@@ -2,239 +2,6 @@ use color_eyre::eyre::Result;
use glam::Quat;
use manifest_dir_macros::directory_relative_path;
use mint::Vector3;
use protostar::{
protostar::ProtoStar,
xdg::{get_desktop_files, parse_desktop_file, DesktopFile},
};
use stardust_xr_fusion::{
client::{Client, FrameInfo, RootHandler},
core::values::Transform,
drawable::{MaterialParameter, Model, ResourceID},
fields::BoxField,
node::NodeError,
spatial::Spatial,
};
use stardust_xr_molecules::{touch_plane::TouchPlane, GrabData, Grabbable};
use std::f32::consts::PI;
use tween::TweenTime;
const APP_SIZE: f32 = 0.06;
const PADDING: f32 = 0.005;
#[derive(Clone)]
struct Hex {
q: isize,
r: isize,
s: isize,
}
const HEX_CENTER: Hex = Hex { q: 0, r: 0, s: 0 };
const HEX_DIRECTION_VECTORS: [Hex; 6] = [
Hex { q: 1, r: 0, s: -1 },
Hex { q: 1, r: -1, s: 0 },
Hex { q: 0, r: -1, s: 1 },
Hex { q: -1, r: 0, s: 1 },
Hex { q: -1, r: 1, s: 0 },
Hex { q: 0, r: 1, s: -1 },
];
impl Hex {
fn new(q: isize, r: isize, s: isize) -> Self {
Hex { q, r, s }
}
fn get_coords(&self) -> [f32; 3] {
let x = 3.0 / 2.0 * (APP_SIZE + PADDING) / 2.0 * (-self.q - self.s).to_f32();
let y = 3.0_f32.sqrt() * (APP_SIZE + PADDING) / 2.0
* ((-self.q - self.s).to_f32() / 2.0 + self.s.to_f32());
[x, y, 0.0]
}
fn add(self, vec: &Hex) -> Self {
Hex::new(self.q + vec.q, self.r + vec.r, self.s + vec.s)
}
fn neighbor(self, direction: usize) -> Self {
self.add(&HEX_DIRECTION_VECTORS[direction])
}
fn scale(self, factor: isize) -> Self {
Hex::new(self.q * factor, self.r * factor, self.s * factor)
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
color_eyre::install().unwrap();
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.pretty()
.init();
let (client, event_loop) = Client::connect_with_async_loop().await?;
client.set_base_prefixes(&[directory_relative_path!("res")]);
let _root = client.wrap_root(AppHexGrid::new(&client))?;
tokio::select! {
_ = tokio::signal::ctrl_c() => (),
e = event_loop => e??,
};
Ok(())
}
struct AppHexGrid {
apps: Vec<App>,
button: Button,
}
impl AppHexGrid {
fn new(client: &Client) -> Self {
let button = Button::new(client).unwrap();
let mut desktop_files: Vec<DesktopFile> = get_desktop_files()
.into_iter()
.filter_map(|d| parse_desktop_file(d).ok())
.filter(|d| !d.no_display)
.collect();
desktop_files.sort_by_key(|d| d.clone().name.unwrap_or_default());
let mut apps = Vec::new();
let mut radius = 1;
while !desktop_files.is_empty() {
let mut hex = HEX_CENTER.add(&HEX_DIRECTION_VECTORS[4].clone().scale(radius));
for i in 0..6 {
if desktop_files.is_empty() {
break;
};
for _ in 0..radius {
if desktop_files.is_empty() {
break;
};
apps.push(
App::new(
button.grabbable.content_parent(),
hex.get_coords(),
desktop_files.pop().unwrap(),
)
.unwrap(),
);
hex = hex.neighbor(i);
}
}
radius += 1;
}
AppHexGrid { apps, button }
}
}
impl RootHandler for AppHexGrid {
fn frame(&mut self, info: FrameInfo) {
self.button.frame(info);
if self.button.touch_plane.touch_started() {
let color = [0.0, 1.0, 0.0, 1.0];
self.button
.model
.model_part("?????")
.unwrap()
.set_material_parameter("color", MaterialParameter::Color(color))
.unwrap();
for app in &mut self.apps {
app.protostar.toggle();
}
} else if self.button.touch_plane.touch_stopped() {
let color = [0.0, 0.0, 1.0, 1.0];
self.button
.model
.model_part("?????")
.unwrap()
.set_material_parameter("color", MaterialParameter::Color(color))
.unwrap();
}
for app in &mut self.apps {
app.frame(info);
}
}
}
struct App {
_desktop_file: DesktopFile,
protostar: ProtoStar,
}
impl App {
fn new(
parent: &Spatial,
position: impl Into<Vector3<f32>>,
desktop_file: DesktopFile,
) -> Option<Self> {
let position = position.into();
let protostar =
ProtoStar::create_from_desktop_file(parent, position, desktop_file.clone()).ok()?;
Some(App {
_desktop_file: desktop_file,
protostar,
})
}
}
impl RootHandler for App {
fn frame(&mut self, info: FrameInfo) {
self.protostar.frame(info);
}
}
struct Button {
touch_plane: TouchPlane,
grabbable: Grabbable,
model: Model,
}
impl Button {
fn new(client: &Client) -> Result<Self, NodeError> {
let field = BoxField::create(client.get_root(), Transform::default(), [APP_SIZE; 3])?;
let grabbable = Grabbable::create(
client.get_root(),
Transform::default(),
&field,
GrabData {
max_distance: 0.01,
..Default::default()
},
)?;
field.set_spatial_parent(grabbable.content_parent())?;
let touch_plane = TouchPlane::create(
grabbable.content_parent(),
Transform::default(),
[(APP_SIZE + PADDING) / 2.0; 2],
(APP_SIZE + PADDING) / 2.0,
1.0..0.0,
1.0..0.0,
)?;
let model = Model::create(
grabbable.content_parent(),
Transform::from_rotation_scale(
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
[0.03, 0.03, 0.03],
),
&ResourceID::new_namespaced("protostar", "hexagon/hexagon"),
)?;
model
.model_part("?????")
.unwrap()
.set_material_parameter("color", MaterialParameter::Color([0.0, 0.0, 1.0, 1.0]))?;
Ok(Button {
touch_plane,
grabbable,
model,
})
}
}
impl RootHandler for Button {
fn frame(&mut self, info: FrameInfo) {
self.touch_plane.update();
self.grabbable.update(&info).unwrap();
}
}
use color_eyre::eyre::Result;
use glam::Quat;
use manifest_dir_macros::directory_relative_path;
use mint::Vector3;
use protostar::{
application::Application,
xdg::{get_desktop_files, parse_desktop_file, DesktopFile, Icon, IconType},
@@ -448,6 +215,8 @@ impl RootHandler for Button {
}
}
// Model handling
fn model_from_icon(parent: &Spatial, icon: &Icon) -> Result<Model> {
return match &icon.icon_type {
IconType::Png => {

View File

@@ -1,27 +1,54 @@
#![allow(dead_code)]
use clap::{self, Parser};
use color_eyre::eyre::Result;
use glam::Vec3;
use glam::{Quat, Vec3};
use manifest_dir_macros::directory_relative_path;
use protostar::protostar::ProtoStar;
use mint::Vector3;
use protostar::{
application::Application,
xdg::{parse_desktop_file, DesktopFile, Icon, IconType},
};
use stardust_xr_fusion::{
client::{Client, FrameInfo, RootHandler},
core::values::Transform,
drawable::{MaterialParameter, Model, ResourceID},
drawable::{Alignment, Bounds, MaterialParameter, Model, ResourceID, Text, TextFit, TextStyle},
fields::BoxField,
input::{InputData, InputDataType},
node::NodeError,
node::NodeType,
spatial::Spatial,
};
use stardust_xr_molecules::{touch_plane::TouchPlane, GrabData, Grabbable};
use std::{f32::consts::PI, path::PathBuf};
use tween::{QuartInOut, Tweener};
use walkdir::WalkDir;
const APP_SIZE: f32 = 0.06;
const ACTIVATION_DISTANCE: f32 = 0.5;
#[derive(Debug, Parser)]
#[clap(author, version, about, long_about = None)]
struct Args {
/// Directory to scan for desktop files
apps_directory: PathBuf,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
color_eyre::install()?;
let args = Args::parse();
if !args.apps_directory.is_dir() {
panic!(
"{} is not a direcotry",
args.apps_directory.to_string_lossy()
)
}
let (client, event_loop) = Client::connect_with_async_loop().await?;
client.set_base_prefixes(&[directory_relative_path!("res")]);
let _wrapped_root = client.wrap_root(Sirius::new(&client)?)?;
let _wrapped_root = client.wrap_root(Sirius::new(&client, args)?)?;
tokio::select! {
_ = tokio::signal::ctrl_c() => (),
@@ -30,49 +57,21 @@ async fn main() -> Result<()> {
Ok(())
}
struct Star {
cli: ProtoStar,
}
impl Star {
fn new(parent: &Spatial, _name: Option<&str>, path: String) -> Option<Self> {
let cli = ProtoStar::new_raw(parent, [0.0; 3], None, None, path).unwrap();
Some(Star { cli })
}
}
impl RootHandler for Star {
fn frame(&mut self, info: FrameInfo) {
self.cli.frame(info);
}
}
const LOCATION_OF_TELESCOPE: &str = "/home/bc/repos/stardust/";
const EXECUTABLES: [&str; 3] = ["magnetar", "atmosphere", "manifold"];
struct Sirius {
touch_plane: TouchPlane,
model: Model,
root: Spatial,
clients: Vec<Star>,
clients: Vec<App>,
visibility: bool,
grabbable: Grabbable,
}
impl Sirius {
fn new(client: &Client) -> Result<Self, NodeError> {
fn new(client: &Client, args: Args) -> Result<Self, NodeError> {
let mut client_list: Vec<(Option<&str>, String)> = Vec::new();
for executable in EXECUTABLES {
client_list.push((
Some(executable),
format!(
"{}telescope/repos/{}/target/release/{}",
LOCATION_OF_TELESCOPE, executable, executable
),
));
}
let root = Spatial::create(client.get_root(), Transform::default(), false).unwrap();
let field = BoxField::create(&root, Transform::default(), Vec3::from([0.1; 3])).unwrap();
let field = BoxField::create(&root, Transform::default(), [0.1; 3]).unwrap();
let grabbable =
Grabbable::create(&root, Transform::default(), &field, GrabData::default())?;
let touch_plane = TouchPlane::create(
@@ -83,10 +82,28 @@ impl Sirius {
1.0..0.0,
1.0..0.0,
)?;
let mut clients = Vec::new();
for clientkv in client_list {
clients.push(Star::new(grabbable.content_parent(), clientkv.0, clientkv.1).unwrap());
}
let walkdir = WalkDir::new(args.apps_directory.canonicalize().unwrap());
let mut clients: Vec<App> = walkdir
.into_iter()
.filter_map(|path| path.ok())
.map(|entry| entry.into_path())
.filter(|path| {
path.is_file()
&& path.extension().is_some()
&& path.extension().unwrap() == "desktop"
})
.filter_map(|path| {
App::create_from_desktop_file(
grabbable.content_parent(),
[0.0; 3],
parse_desktop_file(path).ok()?,
)
.ok()
})
.collect();
let model = Model::create(
grabbable.content_parent(),
Transform::default(),
@@ -125,31 +142,25 @@ impl RootHandler for Sirius {
self.visibility = !self.visibility;
match self.visibility {
true => {
for star in self.clients.iter().enumerate() {
let mut starpos = (star.0 as f32 + 1.0) / 10.0;
for (pos, star) in self.clients.iter().enumerate() {
let mut starpos = (pos as f32 + 1.0) / 10.0;
match starpos % 0.2 == 0.0 {
true => starpos = -starpos / 2.0,
false => starpos = (starpos - 0.1) / 2.0,
}
println!("{}", starpos);
star.1
.cli
.content_parent()
star.content_parent()
.set_position(
Some(&self.grabbable.content_parent()),
Vec3::from([starpos, 0.1, 0.0]),
[starpos, 0.1, 0.0],
)
.ok();
}
}
false => {
for star in &self.clients {
star.cli
.content_parent()
.set_position(
Some(&self.grabbable.content_parent()),
Vec3::from([0.0, 0.0, 0.0]),
)
star.content_parent()
.set_position(Some(&self.grabbable.content_parent()), [0.0, 0.0, 0.0])
.ok();
}
}
@@ -197,3 +208,230 @@ fn position(data: &InputData) -> Vec3 {
InputDataType::Tip(t) => t.origin.into(),
}
}
fn model_from_icon(parent: &Spatial, icon: &Icon) -> Result<Model> {
return match &icon.icon_type {
IconType::Png => {
let t = Transform::from_rotation_scale(
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
[APP_SIZE * 0.5; 3],
);
let model = Model::create(
parent,
t,
&ResourceID::new_namespaced("protostar", "hexagon/hexagon"),
)?;
model
.model_part("Hex")?
.set_material_parameter("color", MaterialParameter::Color([0.0, 1.0, 1.0, 1.0]))?;
model.model_part("Icon")?.set_material_parameter(
"diffuse",
MaterialParameter::Texture(ResourceID::Direct(icon.path.clone())),
)?;
Ok(model)
}
IconType::Gltf => Ok(Model::create(
parent,
Transform::from_scale([0.05; 3]),
&ResourceID::new_direct(icon.path.clone())?,
)?),
_ => panic!("Invalid Icon Type"),
};
}
pub struct App {
application: Application,
parent: Spatial,
position: Vector3<f32>,
grabbable: Grabbable,
_field: BoxField,
icon: Model,
label: Option<Text>,
grabbable_shrink: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_grow: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_move: Option<Tweener<f32, f64, QuartInOut>>,
currently_shown: bool,
}
impl App {
pub fn create_from_desktop_file(
parent: &Spatial,
position: impl Into<Vector3<f32>>,
desktop_file: DesktopFile,
) -> Result<Self> {
let position = position.into();
let field = BoxField::create(parent, Transform::default(), [APP_SIZE; 3])?;
let application = Application::create(&parent.client()?, desktop_file)?;
let icon = application.icon(128, false);
let grabbable = Grabbable::create(
parent,
Transform::from_position(position),
&field,
GrabData {
max_distance: 0.01,
frame_cancel_threshold: 50,
..Default::default()
},
)?;
grabbable.content_parent().set_spatial_parent(parent)?;
field.set_spatial_parent(grabbable.content_parent())?;
let icon = icon
.map(|i| model_from_icon(grabbable.content_parent(), &i))
.unwrap_or_else(|| {
Ok(Model::create(
grabbable.content_parent(),
Transform::from_rotation_scale(
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
[APP_SIZE * 0.5; 3],
),
&ResourceID::new_namespaced("protostar", "hexagon/hexagon"),
)?)
})?;
let label_style = TextStyle {
character_height: APP_SIZE * 2.0,
bounds: Some(Bounds {
bounds: [1.0; 2].into(),
fit: TextFit::Wrap,
bounds_align: Alignment::XCenter | Alignment::YCenter,
}),
text_align: Alignment::Center.into(),
..Default::default()
};
let label = application.name().and_then(|name| {
Text::create(
&icon,
Transform::from_position_rotation(
[0.0, 0.1, -(APP_SIZE * 4.0)],
Quat::from_rotation_x(PI * 0.5),
),
name,
label_style,
)
.ok()
});
Ok(App {
parent: parent.alias(),
position,
grabbable,
_field: field,
label,
application,
icon,
grabbable_shrink: None,
grabbable_grow: None,
grabbable_move: None,
currently_shown: true,
})
}
pub fn content_parent(&self) -> &Spatial {
self.grabbable.content_parent()
}
pub fn toggle(&mut self) {
self.grabbable.set_enabled(!self.currently_shown).unwrap();
if self.currently_shown {
self.grabbable_move = Some(Tweener::quart_in_out(1.0, 0.0001, 0.25)); //TODO make the scale a parameter
} else {
self.icon.set_enabled(true).unwrap();
self.label.as_ref().map(|l| l.set_enabled(true).unwrap());
self.grabbable_move = Some(Tweener::quart_in_out(0.0001, 1.0, 0.25));
}
self.currently_shown = !self.currently_shown;
}
}
impl RootHandler for App {
fn frame(&mut self, info: FrameInfo) {
let _ = self.grabbable.update(&info);
if let Some(grabbable_move) = &mut self.grabbable_move {
if !grabbable_move.is_finished() {
let scale = grabbable_move.move_by(info.delta);
self.grabbable
.content_parent()
.set_position(
Some(&self.parent),
[
self.position.x * scale,
self.position.y * scale,
self.position.z * scale,
],
)
.unwrap();
} else {
if grabbable_move.final_value() == 0.0001 {
self.icon.set_enabled(false).unwrap();
self.label.as_ref().map(|l| l.set_enabled(false).unwrap());
}
self.grabbable_move = None;
}
}
if let Some(grabbable_shrink) = &mut self.grabbable_shrink {
if !grabbable_shrink.is_finished() {
let scale = grabbable_shrink.move_by(info.delta);
self.grabbable
.content_parent()
.set_scale(Some(&self.parent), Vector3::from([scale; 3]))
.unwrap();
} else {
self.grabbable
.content_parent()
.set_spatial_parent(&self.parent)
.unwrap();
if self.currently_shown {
self.grabbable_grow = Some(Tweener::quart_in_out(0.0001, 1.0, 0.25));
self.grabbable.cancel_angular_velocity();
self.grabbable.cancel_linear_velocity();
}
self.grabbable_shrink = None;
self.grabbable
.content_parent()
.set_position(Some(&self.parent), self.position)
.unwrap();
self.grabbable
.content_parent()
.set_rotation(Some(&self.parent), Quat::default())
.unwrap();
self.icon
.set_rotation(
None,
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
)
.unwrap();
}
} else if let Some(grabbable_grow) = &mut self.grabbable_grow {
if !grabbable_grow.is_finished() {
let scale = grabbable_grow.move_by(info.delta);
self.grabbable
.content_parent()
.set_scale(Some(&self.parent), Vector3::from([scale; 3]))
.unwrap();
} else {
self.grabbable
.content_parent()
.set_spatial_parent(&self.parent)
.unwrap();
self.grabbable_grow = None;
}
} else if self.grabbable.valid() && self.grabbable.grab_action().actor_stopped() {
self.grabbable_shrink = Some(Tweener::quart_in_out(APP_SIZE * 0.5, 0.0001, 0.25));
let Ok(distance_future) = self.grabbable
.content_parent()
.get_position_rotation_scale(&self.parent)
else {return};
let application = self.application.clone();
let space = self.content_parent().alias();
//TODO: split the executable string for the args
tokio::task::spawn(async move {
let distance_vector = distance_future.await.ok().unwrap().0;
let distance = ((distance_vector.x.powi(2) + distance_vector.y.powi(2)).sqrt()
+ distance_vector.z.powi(2))
.sqrt();
if dbg!(distance) > ACTIVATION_DISTANCE {
let _ = application.launch(&space);
}
});
}
}
}

View File

@@ -71,7 +71,7 @@ impl Application {
tokio::task::spawn(async move {
let Ok(startup_token) = future_startup_token.await else {return};
let Ok(connection_env) = future_connection_env.await else {return};
dbg!(&connection_env);
for (k, v) in connection_env.into_iter() {
std::env::set_var(k, v);
}

View File

@@ -19,17 +19,11 @@ async fn main() -> Result<()> {
let (client, event_loop) = Client::connect_with_async_loop().await?;
client.set_base_prefixes(&[directory_relative_path!("res")]);
let protostar = if let Some(desktop_file) = args.desktop_file {
ProtoStar::create_from_desktop_file(
let protostar = ProtoStar::create_from_desktop_file(
client.get_root(),
[0.0, 0.0, 0.0],
parse_desktop_file(desktop_file).map_err(|e| Report::msg(e))?,
)?
} else if let Some(command) = args.command {
ProtoStar::new_raw(client.get_root(), [0.0, 0.0, 0.0], None, None, command)?
} else {
bail!("No command or desktop file, nothing to launch.");
};
parse_desktop_file(args.desktop_file).map_err(|e| Report::msg(e))?,
)?;
let _root = client.wrap_root(protostar);

View File

@@ -1,5 +1,3 @@
use crate::xdg::{DesktopFile, Icon, IconType};
use color_eyre::eyre::{eyre, Result};
use crate::{
application::Application,
xdg::{DesktopFile, Icon, IconType},
@@ -7,8 +5,6 @@ use crate::{
use color_eyre::eyre::Result;
use glam::Quat;
use mint::Vector3;
use nix::unistd::setsid;
use regex::Regex;
use stardust_xr_fusion::{
client::{FrameInfo, RootHandler},
core::values::Transform,
@@ -19,14 +15,8 @@ use stardust_xr_fusion::{
};
use stardust_xr_molecules::{GrabData, Grabbable};
use std::f32::consts::PI;
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use std::f32::consts::PI;
use tween::{QuartInOut, Tweener};
const MODEL_SCALE: f32 = 0.03;
const ACTIVATION_DISTANCE: f32 = 1.0;
const MODEL_SCALE: f32 = 0.03;
const ACTIVATION_DISTANCE: f32 = 0.5;
@@ -43,7 +33,6 @@ fn model_from_icon(parent: &Spatial, icon: &Icon) -> Result<Model> {
t,
&ResourceID::new_namespaced("protostar", "hexagon/hexagon"),
)?;
let model_part = model.model_part("hexagon/hexagon").unwrap();
model
.model_part("Hex")?
.set_material_parameter("color", MaterialParameter::Color([0.0, 1.0, 1.0, 1.0]))?;
@@ -63,8 +52,6 @@ fn model_from_icon(parent: &Spatial, icon: &Icon) -> Result<Model> {
}
pub struct ProtoStar {
parent: Spatial,
position: Vector3<f32>,
application: Application,
parent: Spatial,
position: Vector3<f32>,
@@ -75,42 +62,9 @@ pub struct ProtoStar {
grabbable_shrink: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_grow: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_move: Option<Tweener<f32, f64, QuartInOut>>,
execute_command: String,
currently_shown: bool,
label: Option<Text>,
grabbable_shrink: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_grow: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_move: Option<Tweener<f32, f64, QuartInOut>>,
currently_shown: bool,
}
impl ProtoStar {
pub fn create_from_desktop_file(
parent: &Spatial,
position: impl Into<Vector3<f32>>,
desktop_file: DesktopFile,
) -> Result<Self> {
// dbg!(&desktop_file);
let raw_icons = desktop_file.get_raw_icons();
let mut icon = raw_icons
.clone()
.into_iter()
.find(|i| match i.icon_type {
IconType::Gltf => true,
_ => false,
})
.or(raw_icons.into_iter().max_by_key(|i| i.size));
match icon {
Some(i) => {
icon = match i.cached_process(128) {
Ok(i) => Some(i),
_ => None,
}
}
None => {}
}
pub fn create_from_desktop_file(
parent: &Spatial,
position: impl Into<Vector3<f32>>,
@@ -122,25 +76,6 @@ impl ProtoStar {
let icon = application.icon(128, false);
let grabbable = Grabbable::create(
parent,
position,
desktop_file.name.as_deref(),
icon,
desktop_file.command.ok_or_else(|| eyre!("No command"))?,
);
}
pub fn new_raw(
parent: &Spatial,
position: impl Into<Vector3<f32>>,
name: Option<&str>,
icon: Option<Icon>,
execute_command: String,
) -> Result<Self> {
let position = position.into();
let field = BoxField::create(parent, Transform::default(), [MODEL_SCALE * 2.0; 3])?;
let grabbable = Grabbable::create(
parent,
Transform::from_position(position),
Transform::from_position(position),
&field,
GrabData {
@@ -163,29 +98,6 @@ impl ProtoStar {
)?)
})?;
let label_style = TextStyle {
character_height: MODEL_SCALE * 4.0,
bounds: Some(Bounds {
bounds: [1.0; 2].into(),
fit: TextFit::Wrap,
bounds_align: Alignment::XCenter | Alignment::YCenter,
}),
text_align: Alignment::Center.into(),
..Default::default()
};
let label = name.and_then(|name| {
Text::create(
&icon,
Transform::from_position_rotation(
[0.0, 0.1, -(MODEL_SCALE * 8.0)],
Quat::from_rotation_x(PI * 0.5),
),
name,
label_style,
)
.ok()
});
let label_style = TextStyle {
character_height: MODEL_SCALE * 4.0,
bounds: Some(Bounds {
@@ -212,19 +124,12 @@ impl ProtoStar {
parent: parent.alias(),
position,
grabbable,
field,
label,
_field: field,
label,
application,
icon,
grabbable_shrink: None,
grabbable_grow: None,
execute_command,
currently_shown: true,
grabbable_move: None,
grabbable_shrink: None,
grabbable_grow: None,
grabbable_move: None,
currently_shown: true,
})
@@ -246,7 +151,6 @@ impl ProtoStar {
}
impl RootHandler for ProtoStar {
fn frame(&mut self, info: FrameInfo) {
self.grabbable.update(&info).unwrap();
let _ = self.grabbable.update(&info);
if let Some(grabbable_move) = &mut self.grabbable_move {
@@ -271,87 +175,6 @@ impl RootHandler for ProtoStar {
self.grabbable_move = None;
}
}
if let Some(grabbable_shrink) = &mut self.grabbable_shrink {
if !grabbable_shrink.is_finished() {
let scale = grabbable_shrink.move_by(info.delta);
self.grabbable
.content_parent()
.set_scale(Some(&self.parent), Vector3::from([scale; 3]))
.unwrap();
} else {
self.grabbable
.content_parent()
.set_spatial_parent(&self.parent)
.unwrap();
if self.currently_shown {
self.grabbable_grow = Some(Tweener::quart_in_out(0.0001, 1.0, 0.25));
self.grabbable.cancel_angular_velocity();
self.grabbable.cancel_linear_velocity();
}
self.grabbable_shrink = None;
self.grabbable
.content_parent()
.set_position(Some(&self.parent), self.position)
.unwrap();
self.grabbable
.content_parent()
.set_rotation(Some(&self.parent), Quat::default())
.unwrap();
self.icon
.set_rotation(
None,
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
)
.unwrap();
}
} else if let Some(grabbable_grow) = &mut self.grabbable_grow {
if !grabbable_grow.is_finished() {
let scale = grabbable_grow.move_by(info.delta);
self.grabbable
.content_parent()
.set_scale(Some(&self.parent), Vector3::from([scale; 3]))
if let Some(grabbable_move) = &mut self.grabbable_move {
if !grabbable_move.is_finished() {
let scale = grabbable_move.move_by(info.delta);
self.grabbable
.content_parent()
.set_position(
Some(&self.parent),
[
self.position.x * scale,
self.position.y * scale,
self.position.z * scale,
],
)
.unwrap();
} else {
self.grabbable
.content_parent()
.set_spatial_parent(&self.parent)
.unwrap();
self.grabbable_grow = None;
if grabbable_move.final_value() == 0.0001 {
self.icon.set_enabled(false).unwrap();
self.label.as_ref().map(|l| l.set_enabled(false).unwrap());
}
self.grabbable_move = None;
}
} else if self.grabbable.grab_action().actor_stopped() {
let startup_settings = StartupSettings::create(&self.field.client().unwrap()).unwrap();
startup_settings
.set_root(self.grabbable.content_parent())
.unwrap();
self.grabbable_shrink = Some(Tweener::quart_in_out(MODEL_SCALE, 0.0001, 0.25));
let distance_future = self
.grabbable
.content_parent()
.get_position_rotation_scale(&self.parent)
.unwrap();
let executable = self.execute_command.clone();
//TODO: split the executable string for the args
}
if let Some(grabbable_shrink) = &mut self.grabbable_shrink {
if !grabbable_shrink.is_finished() {
let scale = grabbable_shrink.move_by(info.delta);
@@ -415,30 +238,6 @@ impl RootHandler for ProtoStar {
let distance = ((distance_vector.x.powi(2) + distance_vector.y.powi(2)).sqrt()
+ distance_vector.z.powi(2))
.sqrt();
if dbg!(distance) > ACTIVATION_DISTANCE {
let future = startup_settings.generate_startup_token().unwrap();
std::env::set_var("STARDUST_STARTUP_TOKEN", future.await.unwrap());
let re = Regex::new(r"%[fFuUdDnNickvm]").unwrap();
let exec = re.replace_all(&executable, "");
unsafe {
Command::new("sh")
.arg("-c")
.arg(exec.to_string())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.pre_exec(|| {
_ = setsid();
Ok(())
})
.spawn()
.expect("Failed to start child process");
}
let distance_vector = distance_future.await.ok().unwrap().0;
let distance = ((distance_vector.x.powi(2) + distance_vector.y.powi(2)).sqrt()
+ distance_vector.z.powi(2))
.sqrt();
if dbg!(distance) > ACTIVATION_DISTANCE {
let _ = application.launch(&space);
}

View File

@@ -18,8 +18,8 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Mutex;
use std::{env, fs};
use walkdir::WalkDir;
use walkdir::WalkDir;
#[serde_as]
#[derive(Deserialize, Serialize)]
struct ImageCache {
@@ -233,19 +233,19 @@ pub struct DesktopFile {
pub no_display: bool,
}
impl DesktopFile {
pub fn get_raw_icons(&self) -> Vec<Icon> {
pub fn get_raw_icons(&self, preferred_px_size: u16) -> Vec<Icon> {
// Get the name of the icon from the DesktopFile struct
let Some(icon_name) = self.icon.as_ref() else { return Vec::new(); };
let test_icon_path = self.path.join(Path::new(icon_name));
if test_icon_path.exists() {
if let Some(icon) = Icon::from_path(test_icon_path, 128) {
if let Some(icon) = Icon::from_path(test_icon_path, preferred_px_size) {
return vec![icon];
}
}
if let Some(cache_icon_path) = IMAGE_CACHE.lock().unwrap().map.get(icon_name) {
if cache_icon_path.exists() {
if let Some(icon) = Icon::from_path(cache_icon_path.to_owned(), 128) {
if let Some(icon) = Icon::from_path(cache_icon_path.to_owned(), preferred_px_size) {
return vec![icon];
}
}
@@ -341,7 +341,7 @@ fn test_get_icon_path() {
};
// Call the get_icon_path() function with a size argument and store the result
let icon_paths = desktop_file.get_raw_icons();
let icon_paths = desktop_file.get_raw_icons(32);
dbg!(&icon_paths);
// Assert that the get_icon_path() function returns the expected result