scene.rs 16 KB

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