scene.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_channel::{Receiver, Sender};
  19. use async_trait::async_trait;
  20. use darkfi_serial::{FutAsyncWriteExt, SerialDecodable, SerialEncodable};
  21. use futures::{stream::FuturesUnordered, StreamExt};
  22. use parking_lot::Mutex as SyncMutex;
  23. use std::{
  24. collections::{HashMap, VecDeque},
  25. fmt,
  26. future::Future,
  27. str::FromStr,
  28. sync::{Arc, OnceLock, RwLock as SyncRwLock, Weak},
  29. };
  30. use crate::plugin;
  31. use crate::{
  32. error::{Error, Result},
  33. prop::{Property, PropertyAtomicGuard, PropertyPtr, Role},
  34. pubsub::{Publisher, PublisherPtr, Subscription},
  35. ui,
  36. };
  37. macro_rules! t { ($($arg:tt)*) => { trace!(target: "scene", $($arg)*); } }
  38. pub struct ScenePath(VecDeque<String>);
  39. impl<S: Into<String>> From<S> for ScenePath {
  40. fn from(path: S) -> Self {
  41. let path: String = path.into();
  42. (&path).parse().expect("invalid ScenePath &str")
  43. }
  44. }
  45. impl fmt::Display for ScenePath {
  46. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  47. write!(f, "/")?;
  48. for token in &self.0 {
  49. write!(f, "{}/", token)?;
  50. }
  51. Ok(())
  52. }
  53. }
  54. impl FromStr for ScenePath {
  55. type Err = Error;
  56. fn from_str(s: &str) -> Result<Self> {
  57. if s.is_empty() || s.chars().nth(0).unwrap() != '/' {
  58. return Err(Error::InvalidScenePath)
  59. }
  60. if s == "/" {
  61. return Ok(ScenePath(VecDeque::new()))
  62. }
  63. let mut tokens = s.split('/');
  64. // Should start with a /
  65. let initial = tokens.next().expect("should not be empty");
  66. if !initial.is_empty() {
  67. return Err(Error::InvalidScenePath)
  68. }
  69. let mut path = VecDeque::new();
  70. for token in tokens {
  71. // There should not be any double slashes //
  72. if token.is_empty() {
  73. return Err(Error::InvalidScenePath)
  74. }
  75. path.push_back(token.to_string());
  76. }
  77. Ok(ScenePath(path))
  78. }
  79. }
  80. pub type SceneNodePtr = Arc<SceneNode>;
  81. pub type SceneNodeWeak = Weak<SceneNode>;
  82. pub type SceneNodeId = u32;
  83. #[derive(Debug, Copy, Clone, PartialEq, SerialEncodable, SerialDecodable)]
  84. #[repr(u8)]
  85. pub enum SceneNodeType {
  86. Null = 0,
  87. Root = 1,
  88. Window = 2,
  89. WindowInput = 3,
  90. Keyboard = 4,
  91. Mouse = 5,
  92. Layer = 6,
  93. Object = 7,
  94. VectorArt = 8,
  95. Text = 9,
  96. Texture = 10,
  97. Fonts = 11,
  98. Font = 12,
  99. ChatView = 13,
  100. Edit = 14,
  101. Image = 15,
  102. Button = 16,
  103. Shortcut = 17,
  104. Gesture = 18,
  105. EmojiPicker = 19,
  106. SettingRoot = 20,
  107. Setting = 21,
  108. Menu = 22,
  109. TokenTable = 23,
  110. PluginRoot = 100,
  111. Plugin = 101,
  112. }
  113. pub struct SceneNode {
  114. pub name: String,
  115. pub id: SceneNodeId,
  116. pub typ: SceneNodeType,
  117. parent: SyncRwLock<Option<Weak<Self>>>,
  118. children: SyncRwLock<Vec<SceneNodePtr>>,
  119. pub props: Vec<PropertyPtr>,
  120. pub sigs: SyncRwLock<Vec<SignalPtr>>,
  121. pub methods: Vec<Method>,
  122. pub pimpl: OnceLock<Pimpl>,
  123. tasks: SyncMutex<Vec<smol::Task<()>>>,
  124. }
  125. impl SceneNode {
  126. pub fn root() -> SceneNodePtr {
  127. Arc::new(Self::new("", SceneNodeType::Root))
  128. }
  129. pub fn new<S: Into<String>>(name: S, typ: SceneNodeType) -> Self {
  130. Self {
  131. name: name.into(),
  132. id: rand::random(),
  133. typ,
  134. parent: SyncRwLock::new(None),
  135. children: SyncRwLock::new(vec![]),
  136. props: vec![],
  137. sigs: SyncRwLock::new(vec![]),
  138. methods: vec![],
  139. pimpl: OnceLock::new(),
  140. tasks: SyncMutex::new(vec![]),
  141. }
  142. }
  143. pub async fn setup<F, Fut>(self, pimpl_fn: F) -> Arc<Self>
  144. where
  145. F: FnOnce(SceneNodeWeak) -> Fut,
  146. Fut: Future<Output = Pimpl>,
  147. {
  148. let self_ = Arc::new(self);
  149. let weak_self = Arc::downgrade(&self_);
  150. // Initial props
  151. for prop in &self_.props {
  152. prop.set_parent(weak_self.clone());
  153. }
  154. let pimpl = pimpl_fn(weak_self).await;
  155. assert_eq!(Arc::strong_count(&self_), 1);
  156. self_.pimpl.set(pimpl).unwrap();
  157. self_
  158. }
  159. pub fn setup_null(self) -> Arc<Self> {
  160. let self_ = Arc::new(self);
  161. let weak_self = Arc::downgrade(&self_);
  162. // Initial props
  163. for prop in &self_.props {
  164. prop.set_parent(weak_self.clone());
  165. }
  166. assert_eq!(Arc::strong_count(&self_), 1);
  167. self_.pimpl.set(Pimpl::Null).unwrap();
  168. self_
  169. }
  170. pub fn pimpl<'a>(&'a self) -> &'a Pimpl {
  171. self.pimpl.get().unwrap()
  172. }
  173. pub fn link(self: &Arc<Self>, child: SceneNodePtr) {
  174. let mut childs_parent = child.parent.write().unwrap();
  175. assert!(childs_parent.is_none());
  176. *childs_parent = Some(Arc::downgrade(&self));
  177. drop(childs_parent);
  178. let mut children = self.children.write().unwrap();
  179. children.push(child);
  180. }
  181. pub fn unlink(&self) {
  182. // Try to read the parent
  183. let Some(parent_weak) = self.parent.read().unwrap().clone() else { return };
  184. // Try to upgrade to an Arc
  185. let Some(parent) = parent_weak.upgrade() else { return };
  186. // Delete ourself from the parent
  187. let mut children = parent.children.write().unwrap();
  188. for i in 0..children.len() {
  189. if children[i].id == self.id {
  190. children.remove(i);
  191. return
  192. }
  193. }
  194. panic!("child not found");
  195. }
  196. pub fn get_children(&self) -> Vec<SceneNodePtr> {
  197. self.children.read().unwrap().clone()
  198. }
  199. pub fn lookup_node<P: Into<ScenePath>>(self: &Arc<Self>, path: P) -> Option<SceneNodePtr> {
  200. let path: ScenePath = path.into();
  201. let mut path = path.0;
  202. if path.is_empty() {
  203. return Some(self.clone())
  204. }
  205. let child_name = path.pop_front().unwrap();
  206. for child in self.get_children() {
  207. if child.name == child_name {
  208. let path = ScenePath(path);
  209. return child.lookup_node(path)
  210. }
  211. }
  212. None
  213. }
  214. fn has_property(&self, name: &str) -> bool {
  215. self.props.iter().any(|prop| prop.name == name)
  216. }
  217. pub fn add_property(&mut self, prop: Property) -> Result<()> {
  218. if self.has_property(&prop.name) {
  219. return Err(Error::PropertyAlreadyExists)
  220. }
  221. self.props.push(Arc::new(prop));
  222. Ok(())
  223. }
  224. pub fn get_property(&self, name: &str) -> Option<PropertyPtr> {
  225. self.props.iter().find(|prop| prop.name == name).map(|prop| prop.clone())
  226. }
  227. // Convenience methods
  228. pub fn get_property_bool(&self, name: &str) -> Result<bool> {
  229. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_bool(0)
  230. }
  231. pub fn get_property_u32(&self, name: &str) -> Result<u32> {
  232. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_u32(0)
  233. }
  234. pub fn get_property_f32(&self, name: &str) -> Result<f32> {
  235. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_f32(0)
  236. }
  237. pub fn get_property_str(&self, name: &str) -> Result<String> {
  238. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_str(0)
  239. }
  240. pub fn get_property_enum(&self, name: &str) -> Result<String> {
  241. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_enum(0)
  242. }
  243. pub fn get_property_node_id(&self, name: &str) -> Result<SceneNodeId> {
  244. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_node_id(0)
  245. }
  246. // Setters
  247. pub fn set_property_bool(
  248. &self,
  249. atom: &mut PropertyAtomicGuard,
  250. role: Role,
  251. name: &str,
  252. val: bool,
  253. ) -> Result<()> {
  254. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_bool(atom, role, 0, val)
  255. }
  256. pub fn set_property_u32(
  257. &self,
  258. atom: &mut PropertyAtomicGuard,
  259. role: Role,
  260. name: &str,
  261. val: u32,
  262. ) -> Result<()> {
  263. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_u32(atom, role, 0, val)
  264. }
  265. pub fn set_property_f32(
  266. &self,
  267. atom: &mut PropertyAtomicGuard,
  268. role: Role,
  269. name: &str,
  270. val: f32,
  271. ) -> Result<()> {
  272. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_f32(atom, role, 0, val)
  273. }
  274. pub fn set_property_str<S: Into<String>>(
  275. &self,
  276. atom: &mut PropertyAtomicGuard,
  277. role: Role,
  278. name: &str,
  279. val: S,
  280. ) -> Result<()> {
  281. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_str(atom, role, 0, val)
  282. }
  283. pub fn set_property_enum<S: Into<String>>(
  284. &self,
  285. atom: &mut PropertyAtomicGuard,
  286. role: Role,
  287. name: &str,
  288. val: S,
  289. ) -> Result<()> {
  290. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_enum(atom, role, 0, val)
  291. }
  292. pub fn set_property_node_id(
  293. &self,
  294. atom: &mut PropertyAtomicGuard,
  295. role: Role,
  296. name: &str,
  297. val: SceneNodeId,
  298. ) -> Result<()> {
  299. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_node_id(atom, role, 0, val)
  300. }
  301. pub fn set_property_f32_vec(
  302. &self,
  303. atom: &mut PropertyAtomicGuard,
  304. role: Role,
  305. name: &str,
  306. val: Vec<f32>,
  307. ) -> Result<()> {
  308. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_f32_vec(atom, role, val)
  309. }
  310. pub fn add_signal<S: Into<String>>(
  311. &mut self,
  312. name: S,
  313. desc: S,
  314. fmt: Vec<(S, S, CallArgType)>,
  315. ) -> Result<()> {
  316. let name = name.into();
  317. if self.has_signal(&name) {
  318. return Err(Error::SignalAlreadyExists)
  319. }
  320. let fmt = fmt
  321. .into_iter()
  322. .map(|(n, d, t)| CallArg { name: n.into(), desc: d.into(), typ: t })
  323. .collect();
  324. let mut sigs = self.sigs.write().unwrap();
  325. sigs.push(Arc::new(Signal {
  326. name: name.into(),
  327. desc: desc.into(),
  328. fmt,
  329. slots: SyncRwLock::new(HashMap::new()),
  330. }));
  331. Ok(())
  332. }
  333. fn has_signal(&self, name: &str) -> bool {
  334. let sigs = self.sigs.read().unwrap();
  335. sigs.iter().any(|sig| sig.name == name)
  336. }
  337. pub fn get_signal(&self, name: &str) -> Option<SignalPtr> {
  338. let sigs = self.sigs.read().unwrap();
  339. sigs.iter().find(|sig| sig.name == name).cloned()
  340. }
  341. pub fn register(&self, sig_name: &str, slot: Slot) -> Result<SlotId> {
  342. let slot_id = rand::random();
  343. let sig = self.get_signal(sig_name).ok_or(Error::SignalNotFound)?;
  344. let mut slots = sig.slots.write().unwrap();
  345. slots.insert(slot_id, slot);
  346. Ok(slot_id)
  347. }
  348. pub fn unregister(&self, sig_name: &str, slot_id: SlotId) -> Result<()> {
  349. let sig = self.get_signal(sig_name).ok_or(Error::SignalNotFound)?;
  350. let mut slots = sig.slots.write().unwrap();
  351. slots.remove(&slot_id).ok_or(Error::SlotNotFound)?;
  352. Ok(())
  353. }
  354. pub async fn trigger(&self, sig_name: &str, data: Vec<u8>) -> Result<()> {
  355. t!("trigger({sig_name}, {data:?}) [node={self:?}]");
  356. let sig = self.get_signal(sig_name).ok_or(Error::SignalNotFound)?;
  357. let futures = FuturesUnordered::new();
  358. let slots: Vec<_> = sig.slots.read().unwrap().values().cloned().collect();
  359. // TODO: autoremove failed slots
  360. for slot in slots {
  361. t!(" triggering {}", slot.name);
  362. // Trigger the slot
  363. let data = data.clone();
  364. futures.push(async move { slot.notify.send(data).await.is_ok() });
  365. }
  366. let success: Vec<_> = futures.collect().await;
  367. t!("trigger success: {success:?}");
  368. Ok(())
  369. }
  370. pub fn add_method<S: Into<String>>(
  371. &mut self,
  372. name: S,
  373. args: Vec<(S, S, CallArgType)>,
  374. result: Option<Vec<(S, S, CallArgType)>>,
  375. ) -> Result<()> {
  376. let name = name.into();
  377. if self.has_method(&name) {
  378. return Err(Error::MethodAlreadyExists)
  379. }
  380. let args = args
  381. .into_iter()
  382. .map(|(n, d, t)| CallArg { name: n.into(), desc: d.into(), typ: t })
  383. .collect();
  384. let result = match result {
  385. Some(result) => Some(
  386. result
  387. .into_iter()
  388. .map(|(n, d, t)| CallArg { name: n.into(), desc: d.into(), typ: t })
  389. .collect(),
  390. ),
  391. None => None,
  392. };
  393. self.methods.push(Method::new(name.into(), args, result));
  394. Ok(())
  395. }
  396. fn has_method(&self, name: &str) -> bool {
  397. self.methods.iter().any(|sig| sig.name == name)
  398. }
  399. pub fn get_method(&self, name: &str) -> Option<&Method> {
  400. self.methods.iter().find(|method| method.name == name)
  401. }
  402. pub async fn call_method(&self, name: &str, arg_data: CallData) -> Result<Option<CallData>> {
  403. let method = self.get_method(name).ok_or(Error::MethodNotFound)?;
  404. Ok(method.call(arg_data).await)
  405. }
  406. pub fn subscribe_method_call(&self, name: &str) -> Result<MethodCallSub> {
  407. let method = self.get_method(name).ok_or(Error::MethodNotFound)?;
  408. let method_sub = method.pubsub.clone().subscribe();
  409. Ok(method_sub)
  410. }
  411. pub fn get_full_path(&self) -> Option<String> {
  412. let subpath = "/".to_string() + &self.name;
  413. let Some(parent_weak) = self.parent.read().unwrap().clone() else { return Some(subpath) };
  414. let Some(parent) = parent_weak.upgrade() else { return None };
  415. // Handle root /
  416. if parent.typ == SceneNodeType::Root {
  417. return Some(subpath)
  418. }
  419. Some(parent.get_full_path()? + &subpath)
  420. }
  421. pub fn push_task(&self, task: smol::Task<()>) {
  422. self.tasks.lock().push(task);
  423. }
  424. pub fn clear_tasks(&self) {
  425. self.tasks.lock().clear();
  426. }
  427. }
  428. impl std::fmt::Debug for SceneNode {
  429. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  430. if let Some(path) = self.get_full_path() {
  431. write!(f, "{path}")
  432. } else {
  433. write!(f, "{}:{}", self.name, self.id)
  434. }
  435. }
  436. }
  437. impl Drop for SceneNode {
  438. fn drop(&mut self) {
  439. println!("Drop {}:{}", self.name, self.id);
  440. }
  441. }
  442. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  443. pub enum CallArgType {
  444. Uint32,
  445. Uint64,
  446. Float32,
  447. Bool,
  448. Str,
  449. Hash,
  450. }
  451. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  452. pub struct CallArg {
  453. pub name: String,
  454. pub desc: String,
  455. pub typ: CallArgType,
  456. }
  457. pub type CallData = Vec<u8>;
  458. pub type SlotId = u32;
  459. #[derive(Clone)]
  460. pub struct Slot {
  461. pub name: String,
  462. pub notify: Sender<CallData>,
  463. }
  464. impl Slot {
  465. pub fn new<S: Into<String>>(name: S) -> (Self, Receiver<CallData>) {
  466. let (notify, recvr) = async_channel::unbounded();
  467. let self_ = Self { name: name.into(), notify };
  468. (self_, recvr)
  469. }
  470. }
  471. type SignalPtr = Arc<Signal>;
  472. pub struct Signal {
  473. pub name: String,
  474. #[allow(dead_code)]
  475. pub desc: String,
  476. #[allow(dead_code)]
  477. pub fmt: Vec<CallArg>,
  478. slots: SyncRwLock<HashMap<SlotId, Slot>>,
  479. }
  480. #[derive(Clone, Debug)]
  481. pub struct MethodCall {
  482. pub data: CallData,
  483. pub send_res: Option<Sender<CallData>>,
  484. }
  485. impl MethodCall {
  486. fn new(data: CallData, send_res: Option<Sender<CallData>>) -> Self {
  487. Self { data, send_res }
  488. }
  489. }
  490. pub type MethodCallSub = Subscription<MethodCall>;
  491. pub struct Method {
  492. pub name: String,
  493. pub args: Vec<CallArg>,
  494. pub result: Option<Vec<CallArg>>,
  495. pub pubsub: PublisherPtr<MethodCall>,
  496. }
  497. impl Method {
  498. fn new(name: String, args: Vec<CallArg>, result: Option<Vec<CallArg>>) -> Self {
  499. Self { name, args, result, pubsub: Publisher::new() }
  500. }
  501. async fn call(&self, data: CallData) -> Option<CallData> {
  502. match &self.result {
  503. Some(_) => {
  504. let (send_res, recv_res) = async_channel::bounded(1);
  505. self.pubsub.notify(MethodCall::new(data, Some(send_res)));
  506. Some(recv_res.recv().await.unwrap())
  507. }
  508. None => {
  509. self.pubsub.notify(MethodCall::new(data, None));
  510. None
  511. }
  512. }
  513. }
  514. }
  515. pub enum Pimpl {
  516. Null,
  517. Window(ui::WindowPtr),
  518. Layer(ui::LayerPtr),
  519. ScrollLayer(ui::ScrollLayerPtr),
  520. VectorArt(ui::VectorArtPtr),
  521. Text(ui::TextPtr),
  522. Edit(ui::BaseEditPtr),
  523. ChatView(ui::ChatViewPtr),
  524. Image(ui::ImagePtr),
  525. Video(ui::VideoPtr),
  526. Button(ui::ButtonPtr),
  527. Shortcut(ui::ShortcutPtr),
  528. Gesture(ui::GesturePtr),
  529. EmojiPicker(ui::EmojiPickerPtr),
  530. Menu(ui::MenuPtr),
  531. TokenTable(ui::TokenTablePtr),
  532. #[cfg(feature = "enable-plugin-darkirc")]
  533. DarkIrc(plugin::DarkIrcPtr),
  534. #[cfg(feature = "enable-plugin-darkirc")]
  535. DarkIrc2(plugin::DarkIrc2Ptr),
  536. #[cfg(feature = "enable-plugin-fud")]
  537. Fud(plugin::FudPtr),
  538. #[cfg(feature = "enable-plugin-drk")]
  539. Drk(plugin::DrkPtr),
  540. }
  541. impl std::fmt::Debug for Pimpl {
  542. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  543. write!(f, "Pimpl")
  544. }
  545. }