1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use super::HandlerWrapper;
use super::{scenegraph::Scenegraph, spatial::Spatial};
use anyhow::Result;
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use serde::Deserialize;
use stardust_xr::schemas::flex::{deserialize, serialize};
use stardust_xr::{client, messenger::Messenger};
use std::any::TypeId;
use std::path::Path;
use std::sync::{Arc, Weak};
use tokio::net::UnixStream;
use tokio::sync::Notify;
use tokio::task::JoinHandle;

#[derive(Deserialize)]
struct LogicStepInfoInternal {
	delta: f64,
}
#[derive(Debug, Default, Clone, Copy)]
pub struct LogicStepInfo {
	pub delta: f64,
	pub elapsed: f64,
}

pub trait LifeCycleHandler: Send + Sync + 'static {
	fn logic_step(&mut self, _info: LogicStepInfo);
}

struct LifeCycleHandlerDummy;
impl LifeCycleHandler for LifeCycleHandlerDummy {
	fn logic_step(&mut self, info: LogicStepInfo) {
		println!("Logic step delta is {}s", info.delta);
	}
}

pub struct Root {
	pub spatial: Spatial,
}

pub struct Client {
	pub messenger: Messenger,
	pub scenegraph: Scenegraph,

	stop_notifier: Notify,

	root: OnceCell<Arc<Spatial>>,
	hmd: OnceCell<Spatial>,
	pub(crate) registered_item_uis: Mutex<Vec<TypeId>>,

	elapsed_time: Mutex<f64>,
	life_cycle_handler: Mutex<Weak<Mutex<dyn LifeCycleHandler>>>,
}

impl Client {
	pub async fn connect() -> Result<Arc<Self>, std::io::Error> {
		let connection = client::connect().await?;
		Client::from_connection(connection).await
	}

	pub async fn from_connection(connection: UnixStream) -> Result<Arc<Self>, std::io::Error> {
		let client = Arc::new(Client {
			scenegraph: Scenegraph::new(),
			messenger: Messenger::new(tokio::runtime::Handle::current(), connection),

			stop_notifier: Default::default(),

			root: OnceCell::new(),
			hmd: OnceCell::new(),
			registered_item_uis: Mutex::new(Vec::new()),

			elapsed_time: Mutex::new(0.0),
			life_cycle_handler: Mutex::new(Weak::<Mutex<LifeCycleHandlerDummy>>::new()),
		});
		let weak_client = Arc::downgrade(&client);
		let _ = client.root.set(Arc::new(
			Spatial::from_path(weak_client.clone(), "/").unwrap(),
		));
		let _ = client
			.hmd
			.set(Spatial::from_path(weak_client, "/hmd").unwrap());

		if let Ok(desktop_startup_id) = std::env::var("DESKTOP_STARTUP_ID") {
			client
				.get_root()
				.node
				.send_remote_signal(
					"applyDesktopStartupID",
					&flexbuffers::singleton(desktop_startup_id.as_str()),
				)
				.unwrap();
		}

		client
			.get_root()
			.node
			.send_remote_signal("subscribeLogicStep", &[0, 0])
			.map_err(|_| std::io::Error::from(std::io::ErrorKind::NotConnected))?;

		client.get_root().node.local_signals.insert(
			"logicStep".to_owned(),
			Box::new({
				let client = client.clone();
				move |data| {
					if let Some(handler) = client.life_cycle_handler.lock().upgrade() {
						let info_internal: LogicStepInfoInternal = deserialize(data)?;
						let mut elapsed = client.elapsed_time.lock();
						(*elapsed) += info_internal.delta;
						let info = LogicStepInfo {
							delta: info_internal.delta,
							elapsed: *elapsed,
						};
						handler.lock().logic_step(info);
					}
					Ok(())
				}
			}),
		);

		Ok(client)
	}

	pub async fn connect_with_async_loop() -> Result<(Arc<Self>, JoinHandle<()>), std::io::Error> {
		let client = Client::connect().await?;

		let event_loop = tokio::task::spawn({
			let client = client.clone();
			async move {
				let dispatch_loop = async { while client.dispatch().await.is_ok() {} };
				let flush_loop = async { while client.flush().await.is_ok() {} };

				tokio::select! {
					_ = client.stop_notifier.notified() => (),
					_ = dispatch_loop => (),
					_ = flush_loop => (),
				}
				println!("Stopped the loop");
			}
		});

		Ok((client, event_loop))
	}

	pub async fn dispatch(&self) -> Result<(), std::io::Error> {
		self.messenger.dispatch(&self.scenegraph).await
	}

	pub async fn flush(&self) -> Result<(), std::io::Error> {
		self.messenger.flush().await
	}

	pub fn get_root(&self) -> &Spatial {
		self.root.get().as_ref().unwrap()
	}
	pub fn get_hmd(&self) -> &Spatial {
		self.hmd.get().as_ref().unwrap()
	}

	pub fn wrap_root<T: LifeCycleHandler>(&self, wrapped: T) -> HandlerWrapper<Spatial, T> {
		let wrapper = HandlerWrapper::new(
			Spatial {
				node: self.root.get().unwrap().node.clone(),
			},
			move |_, _, _| wrapped,
		);
		*self.life_cycle_handler.lock() = wrapper.weak_wrapped();
		wrapper
	}

	pub fn set_base_prefixes<T: AsRef<str>>(&self, prefixes: &[T]) {
		let prefixes: Vec<&Path> = prefixes
			.iter()
			.map(|p| Path::new(p.as_ref()))
			.filter(|p| p.is_absolute() && p.exists())
			.collect();

		self.messenger
			.send_remote_signal("/", "setBasePrefixes", &serialize(prefixes).unwrap());
	}

	pub fn stop_loop(&self) {
		self.stop_notifier.notify_one();
	}
}

impl Drop for Client {
	fn drop(&mut self) {
		self.stop_loop();
		let _ = self
			.messenger
			.send_remote_signal("/", "disconnect", &[0_u8; 0]);
	}
}

#[tokio::test]
async fn fusion_client_connect() -> anyhow::Result<()> {
	let (client, event_loop) = Client::connect_with_async_loop().await?;

	tokio::select! {
		biased;
		_ = tokio::time::sleep(core::time::Duration::from_secs(1)) => (),
		_ = event_loop => (),
	};
	drop(client);
	Ok(())
}

#[tokio::test]
async fn fusion_client_life_cycle() -> anyhow::Result<()> {
	let (client, event_loop) = Client::connect_with_async_loop().await?;

	let _wrapper = client.wrap_root(LifeCycleHandlerDummy);

	tokio::select! {
		_ = tokio::time::sleep(core::time::Duration::from_secs(60)) => Err(anyhow::anyhow!("Timed Out")),
		_ = event_loop => Ok(()),
	}
}