scene.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::Sender;
  19. use async_lock::Mutex;
  20. use darkfi_serial::{
  21. async_trait, deserialize, Decodable, Encodable, FutAsyncWriteExt, ReadExt, SerialDecodable,
  22. SerialEncodable, VarInt,
  23. };
  24. use futures::{stream::FuturesUnordered, StreamExt};
  25. use std::{fmt, str::FromStr, sync::Arc};
  26. use crate::{
  27. error::{Error, Result},
  28. prop::{Property, PropertyPtr, PropertyType, Role},
  29. ui,
  30. };
  31. pub type SceneNodeId = u32;
  32. #[derive(Debug, Copy, Clone, PartialEq, SerialEncodable, SerialDecodable)]
  33. #[repr(u8)]
  34. pub enum SceneNodeType {
  35. Null = 0,
  36. Root = 1,
  37. Window = 2,
  38. WindowInput = 6,
  39. Keyboard = 7,
  40. Mouse = 8,
  41. RenderLayer = 3,
  42. RenderObject = 4,
  43. RenderMesh = 5,
  44. RenderText = 9,
  45. RenderTexture = 13,
  46. Fonts = 10,
  47. Font = 11,
  48. Plugins = 14,
  49. Plugin = 15,
  50. ChatView = 16,
  51. EditBox = 17,
  52. Image = 18,
  53. Button = 19,
  54. }
  55. pub struct ScenePath(Vec<String>);
  56. impl<S: Into<String>> From<S> for ScenePath {
  57. fn from(path: S) -> Self {
  58. let path: String = path.into();
  59. (&path).parse().expect("invalid ScenePath &str")
  60. }
  61. }
  62. impl fmt::Display for ScenePath {
  63. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  64. write!(f, "/")?;
  65. for token in &self.0 {
  66. write!(f, "{}/", token)?;
  67. }
  68. Ok(())
  69. }
  70. }
  71. impl FromStr for ScenePath {
  72. type Err = Error;
  73. fn from_str(s: &str) -> Result<Self> {
  74. if s.is_empty() || s.chars().nth(0).unwrap() != '/' {
  75. return Err(Error::InvalidScenePath);
  76. }
  77. if s == "/" {
  78. return Ok(ScenePath(vec![]));
  79. }
  80. let mut tokens = s.split('/');
  81. // Should start with a /
  82. let initial = tokens.next().expect("should not be empty");
  83. if !initial.is_empty() {
  84. return Err(Error::InvalidScenePath);
  85. }
  86. let mut path = vec![];
  87. for token in tokens {
  88. // There should not be any double slashes //
  89. if token.is_empty() {
  90. return Err(Error::InvalidScenePath);
  91. }
  92. path.push(token.to_string());
  93. }
  94. Ok(ScenePath(path))
  95. }
  96. }
  97. pub type SceneGraphPtr = Arc<std::sync::Mutex<SceneGraph>>;
  98. pub type SceneGraphPtr2 = Arc<Mutex<SceneGraph>>;
  99. pub struct SceneGraph {
  100. // Node 0 is always the root
  101. nodes: Vec<SceneNode>,
  102. freed: Vec<SceneNodeId>,
  103. }
  104. impl SceneGraph {
  105. pub const ROOT_ID: SceneNodeId = 0;
  106. pub fn new() -> Self {
  107. let root = SceneNode {
  108. name: "/".to_string(),
  109. id: 0,
  110. typ: SceneNodeType::Root,
  111. parents: vec![],
  112. children: vec![],
  113. props: vec![],
  114. sigs: vec![],
  115. methods: vec![],
  116. pimpl: Pimpl::Null,
  117. };
  118. Self { nodes: vec![root], freed: vec![] }
  119. }
  120. pub fn add_node<S: Into<String>>(&mut self, name: S, typ: SceneNodeType) -> &mut SceneNode {
  121. let node = SceneNode {
  122. name: name.into(),
  123. // We set this at the end
  124. id: 0,
  125. typ,
  126. parents: vec![],
  127. children: vec![],
  128. props: vec![],
  129. sigs: vec![],
  130. methods: vec![],
  131. pimpl: Pimpl::Null,
  132. };
  133. let node_id = if self.freed.is_empty() {
  134. let node_id = self.nodes.len() as SceneNodeId;
  135. self.nodes.push(node);
  136. node_id
  137. } else {
  138. let node_id = self.freed.pop().unwrap();
  139. let _ = std::mem::replace(&mut self.nodes[node_id as usize], node);
  140. node_id
  141. };
  142. self.nodes[node_id as usize].id = node_id;
  143. &mut self.nodes[node_id as usize]
  144. }
  145. pub fn remove_node(&mut self, id: SceneNodeId) -> Result<()> {
  146. let node = self.get_node_mut(id).ok_or(Error::NodeNotFound)?;
  147. if !node.parents.is_empty() {
  148. return Err(Error::NodeHasParents);
  149. }
  150. if !node.children.is_empty() {
  151. return Err(Error::NodeHasChildren);
  152. }
  153. node.name.clear();
  154. node.typ = SceneNodeType::Null;
  155. node.props.clear();
  156. self.freed.push(id);
  157. Ok(())
  158. }
  159. fn root(&self) -> &SceneNode {
  160. &self.nodes[0]
  161. }
  162. fn root_mut(&mut self) -> &mut SceneNode {
  163. &mut self.nodes[0]
  164. }
  165. fn exists(&self, id: SceneNodeId) -> bool {
  166. id < self.nodes.len() as SceneNodeId && !self.freed.contains(&id)
  167. }
  168. pub fn get_node(&self, id: SceneNodeId) -> Option<&SceneNode> {
  169. if self.exists(id) {
  170. Some(&self.nodes[id as usize])
  171. } else {
  172. None
  173. }
  174. }
  175. pub fn get_node_mut(&mut self, id: SceneNodeId) -> Option<&mut SceneNode> {
  176. if self.exists(id) {
  177. Some(&mut self.nodes[id as usize])
  178. } else {
  179. None
  180. }
  181. }
  182. pub fn link(&mut self, child_id: SceneNodeId, parent_id: SceneNodeId) -> Result<()> {
  183. // Check both nodes are not already linked
  184. let is_linked = self.is_linked(child_id, parent_id)?;
  185. if is_linked {
  186. return Err(Error::NodesAreLinked);
  187. }
  188. let parent = self.get_node(parent_id).unwrap();
  189. let parent_inf =
  190. SceneNodeInfo { name: parent.name.clone(), id: parent_id, typ: parent.typ };
  191. let child_name = &self.get_node(child_id).unwrap().name;
  192. if parent.has_child(child_name) {
  193. return Err(Error::NodeChildNameConflict);
  194. }
  195. // Link parent into child
  196. let child = self.get_node_mut(child_id).unwrap();
  197. if child.has_parent(&parent_inf.name) {
  198. return Err(Error::NodeParentNameConflict);
  199. }
  200. let child_inf = SceneNodeInfo { name: child.name.clone(), id: child_id, typ: child.typ };
  201. assert!(!child.has_parent_id(parent_id));
  202. child.parents.push(parent_inf);
  203. // Link child into parent
  204. let parent = self.get_node_mut(parent_id).unwrap();
  205. assert!(!parent.has_child(&child_inf.name));
  206. parent.children.push(child_inf);
  207. Ok(())
  208. }
  209. pub fn unlink(&mut self, child_id: SceneNodeId, parent_id: SceneNodeId) -> Result<()> {
  210. // Check both nodes are actually linked
  211. let is_linked = self.is_linked(child_id, parent_id)?;
  212. if !is_linked {
  213. return Err(Error::NodesNotLinked);
  214. }
  215. // Unlink parent from child
  216. let child = self.get_node_mut(child_id).unwrap();
  217. child.remove_parent(parent_id);
  218. // Unlink child from parent
  219. let parent = self.get_node_mut(parent_id).unwrap();
  220. parent.remove_child(child_id);
  221. Ok(())
  222. }
  223. pub fn is_linked(&self, child_id: SceneNodeId, parent_id: SceneNodeId) -> Result<bool> {
  224. let parent = self.get_node(parent_id).ok_or(Error::ParentNodeNotFound)?;
  225. let child = self.get_node(child_id).ok_or(Error::ChildNodeNotFound)?;
  226. let parent_has_child = parent.has_child_id(child_id);
  227. let child_has_parent = child.has_parent_id(parent_id);
  228. // Internal consistency checks
  229. if parent_has_child {
  230. assert!(child_has_parent);
  231. } else {
  232. assert!(!child_has_parent);
  233. }
  234. Ok(parent_has_child)
  235. }
  236. pub fn lookup_node_id<P: Into<ScenePath>>(&self, path: P) -> Option<SceneNodeId> {
  237. let path: ScenePath = path.into();
  238. let mut current_id = Self::ROOT_ID;
  239. for node_name in path.0 {
  240. let parent_node = self.get_node(current_id).unwrap();
  241. match parent_node.get_child(&node_name) {
  242. Some(child_id) => {
  243. current_id = child_id;
  244. }
  245. None => return None,
  246. }
  247. }
  248. Some(current_id)
  249. }
  250. pub fn lookup_node<P: Into<ScenePath>>(&self, path: P) -> Option<&SceneNode> {
  251. let node_id = self.lookup_node_id(path)?;
  252. Some(self.get_node(node_id).unwrap())
  253. }
  254. pub fn lookup_node_mut<P: Into<ScenePath>>(&mut self, path: P) -> Option<&mut SceneNode> {
  255. let node_id = self.lookup_node_id(path)?;
  256. Some(self.get_node_mut(node_id).unwrap())
  257. }
  258. pub fn rename_node<S: Into<String>>(
  259. &mut self,
  260. node_id: SceneNodeId,
  261. node_name: S,
  262. ) -> Result<()> {
  263. let node_name = node_name.into();
  264. for sibling_inf in self.node_siblings(node_id)? {
  265. if sibling_inf.name == node_name {
  266. return Err(Error::NodeSiblingNameConflict)
  267. }
  268. }
  269. let node = self.get_node_mut(node_id).unwrap();
  270. node.name = node_name.clone();
  271. // Now update it for all children and parents too
  272. let parent_ids: Vec<_> = node.parents.iter().map(|parent_inf| parent_inf.id).collect();
  273. let child_ids: Vec<_> = node.children.iter().map(|child_inf| child_inf.id).collect();
  274. 'next_parent: for parent_id in parent_ids {
  275. let parent = self.get_node_mut(parent_id).unwrap();
  276. for child in &mut parent.children {
  277. if child.id == node_id {
  278. child.name = node_name.clone();
  279. continue 'next_parent
  280. }
  281. }
  282. panic!("child {} not found in parent {}!", node_id, parent.id)
  283. }
  284. 'next_child: for child_id in child_ids {
  285. let child = self.get_node_mut(child_id).unwrap();
  286. for parent in &mut child.parents {
  287. if parent.id == node_id {
  288. parent.name = node_name.clone();
  289. continue 'next_child
  290. }
  291. }
  292. panic!("parent {} not found in child {}!", node_id, child.id)
  293. }
  294. Ok(())
  295. }
  296. fn node_siblings(&self, node_id: SceneNodeId) -> Result<Vec<SceneNodeInfo>> {
  297. let mut siblings = vec![];
  298. let node = self.get_node(node_id).ok_or(Error::NodeNotFound)?;
  299. for parent_inf in &node.parents {
  300. let parent = self.get_node(parent_inf.id).ok_or(Error::ParentNodeNotFound)?;
  301. let mut sibling_infs = parent
  302. .children
  303. .iter()
  304. .cloned()
  305. .filter(|child_inf| child_inf.id != node_id)
  306. .collect();
  307. siblings.append(&mut sibling_infs);
  308. }
  309. Ok(siblings)
  310. }
  311. pub fn scan_dangling(&self) -> Vec<SceneNodeId> {
  312. let mut dangling = vec![];
  313. for node in &self.nodes {
  314. if node.id == Self::ROOT_ID {
  315. continue
  316. }
  317. if self.freed.contains(&node.id) {
  318. continue
  319. }
  320. if node.parents.is_empty() {
  321. dangling.push(node.id);
  322. }
  323. }
  324. dangling
  325. }
  326. }
  327. #[derive(Clone)]
  328. pub struct SceneNodeInfo {
  329. pub name: String,
  330. pub id: SceneNodeId,
  331. pub typ: SceneNodeType,
  332. }
  333. pub struct SceneNode {
  334. pub name: String,
  335. pub id: SceneNodeId,
  336. pub typ: SceneNodeType,
  337. pub parents: Vec<SceneNodeInfo>,
  338. pub children: Vec<SceneNodeInfo>,
  339. pub props: Vec<PropertyPtr>,
  340. pub sigs: Vec<Signal>,
  341. pub methods: Vec<Method>,
  342. pub pimpl: Pimpl,
  343. }
  344. impl SceneNode {
  345. fn has_parent_id(&self, parent_id: SceneNodeId) -> bool {
  346. self.parents.iter().any(|parent| parent.id == parent_id)
  347. }
  348. fn has_child_id(&self, child_id: SceneNodeId) -> bool {
  349. self.children.iter().any(|child| child.id == child_id)
  350. }
  351. fn has_parent(&self, parent_name: &str) -> bool {
  352. self.parents.iter().any(|parent| parent.name == parent_name)
  353. }
  354. fn has_child(&self, child_name: &str) -> bool {
  355. self.children.iter().any(|child| child.name == child_name)
  356. }
  357. fn get_child(&self, child_name: &str) -> Option<SceneNodeId> {
  358. for child in &self.children {
  359. if child.name == child_name {
  360. return Some(child.id);
  361. }
  362. }
  363. None
  364. }
  365. // Panics if parent is not linked
  366. fn remove_parent(&mut self, parent_id: SceneNodeId) {
  367. let parent_idx = self.parents.iter().position(|parent| parent.id == parent_id).unwrap();
  368. self.parents.swap_remove(parent_idx);
  369. }
  370. // Panics if child is not linked
  371. fn remove_child(&mut self, child_id: SceneNodeId) {
  372. let child_idx = self.children.iter().position(|child| child.id == child_id).unwrap();
  373. self.children.swap_remove(child_idx);
  374. }
  375. pub fn get_children(&self, allowed_types: &[SceneNodeType]) -> Vec<SceneNodeInfo> {
  376. self.children
  377. .iter()
  378. .cloned()
  379. .filter(move |child_inf| allowed_types.contains(&child_inf.typ))
  380. .collect()
  381. }
  382. pub fn get_children2(&self) -> Vec<SceneNodeInfo> {
  383. self.children.iter().cloned().collect()
  384. }
  385. pub fn add_property(&mut self, prop: Property) -> Result<()> {
  386. if self.has_property(&prop.name) {
  387. return Err(Error::PropertyAlreadyExists);
  388. }
  389. self.props.push(Arc::new(prop));
  390. Ok(())
  391. }
  392. fn has_property(&self, name: &str) -> bool {
  393. self.props.iter().any(|prop| prop.name == name)
  394. }
  395. pub fn get_property(&self, name: &str) -> Option<PropertyPtr> {
  396. self.props.iter().find(|prop| prop.name == name).map(|prop| prop.clone())
  397. }
  398. // Convenience methods
  399. pub fn get_property_bool(&self, name: &str) -> Result<bool> {
  400. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_bool(0)
  401. }
  402. pub fn get_property_u32(&self, name: &str) -> Result<u32> {
  403. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_u32(0)
  404. }
  405. pub fn get_property_f32(&self, name: &str) -> Result<f32> {
  406. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_f32(0)
  407. }
  408. pub fn get_property_str(&self, name: &str) -> Result<String> {
  409. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_str(0)
  410. }
  411. pub fn get_property_enum(&self, name: &str) -> Result<String> {
  412. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_enum(0)
  413. }
  414. pub fn get_property_node_id(&self, name: &str) -> Result<SceneNodeId> {
  415. self.get_property(name).ok_or(Error::PropertyNotFound)?.get_node_id(0)
  416. }
  417. // Setters
  418. pub fn set_property_bool(&self, role: Role, name: &str, val: bool) -> Result<()> {
  419. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_bool(role, 0, val)
  420. }
  421. pub fn set_property_u32(&self, role: Role, name: &str, val: u32) -> Result<()> {
  422. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_u32(role, 0, val)
  423. }
  424. pub fn set_property_f32(&self, role: Role, name: &str, val: f32) -> Result<()> {
  425. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_f32(role, 0, val)
  426. }
  427. pub fn set_property_str<S: Into<String>>(&self, role: Role, name: &str, val: S) -> Result<()> {
  428. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_str(role, 0, val)
  429. }
  430. pub fn set_property_node_id(&self, role: Role, name: &str, val: SceneNodeId) -> Result<()> {
  431. self.get_property(name).ok_or(Error::PropertyNotFound)?.set_node_id(role, 0, val)
  432. }
  433. pub fn add_signal<S: Into<String>>(
  434. &mut self,
  435. name: S,
  436. desc: S,
  437. fmt: Vec<(S, S, CallArgType)>,
  438. ) -> Result<()> {
  439. let name = name.into();
  440. if self.has_signal(&name) {
  441. return Err(Error::SignalAlreadyExists);
  442. }
  443. let fmt = fmt
  444. .into_iter()
  445. .map(|(n, d, t)| CallArg { name: n.into(), desc: d.into(), typ: t })
  446. .collect();
  447. self.sigs.push(Signal {
  448. name: name.into(),
  449. desc: desc.into(),
  450. fmt,
  451. slots: vec![],
  452. freed: vec![],
  453. });
  454. Ok(())
  455. }
  456. fn has_signal(&self, name: &str) -> bool {
  457. self.sigs.iter().any(|sig| sig.name == name)
  458. }
  459. pub fn get_signal(&self, name: &str) -> Option<&Signal> {
  460. self.sigs.iter().find(|sig| sig.name == name)
  461. }
  462. fn get_signal_mut(&mut self, name: &str) -> Option<&mut Signal> {
  463. self.sigs.iter_mut().find(|sig| sig.name == name)
  464. }
  465. pub fn register(&mut self, sig_name: &str, slot: Slot) -> Result<SlotId> {
  466. let sig = self.get_signal_mut(sig_name).ok_or(Error::SignalNotFound)?;
  467. let slot_id = if sig.freed.is_empty() {
  468. let slot_id = sig.slots.len() as SlotId;
  469. sig.slots.push(slot);
  470. slot_id
  471. } else {
  472. let slot_id = sig.freed.pop().unwrap();
  473. let _ = std::mem::replace(&mut sig.slots[slot_id as usize], slot);
  474. slot_id
  475. };
  476. Ok(slot_id)
  477. }
  478. pub fn unregister(&mut self, sig_name: &str, slot_id: SlotId) -> Result<()> {
  479. let sig = self.get_signal_mut(sig_name).ok_or(Error::SignalNotFound)?;
  480. if !sig.slot_exists(slot_id) {
  481. return Err(Error::SlotNotFound);
  482. }
  483. sig.freed.push(slot_id);
  484. Ok(())
  485. }
  486. pub async fn trigger(&self, sig_name: &str, data: Vec<u8>) -> Result<()> {
  487. let sig = self.get_signal(sig_name).ok_or(Error::SignalNotFound)?;
  488. let futures = FuturesUnordered::new();
  489. // TODO: autoremove slots which fail to send
  490. for (_, slot) in sig.get_slots() {
  491. debug!(target: "scene", "triggering {}", slot.name);
  492. // Trigger the slot
  493. futures.push(async { slot.notify.send(data.clone()).await.is_ok() });
  494. }
  495. let success: Vec<_> = futures.collect().await;
  496. debug!(target: "scene", "trigger success: {success:?}");
  497. Ok(())
  498. }
  499. pub fn add_method<S: Into<String>>(
  500. &mut self,
  501. name: S,
  502. args: Vec<(S, S, CallArgType)>,
  503. result: Vec<(S, S, CallArgType)>,
  504. method_fn: MethodRequestFn,
  505. ) -> Result<()> {
  506. let name = name.into();
  507. if self.has_signal(&name) {
  508. return Err(Error::MethodAlreadyExists);
  509. }
  510. let args = args
  511. .into_iter()
  512. .map(|(n, d, t)| CallArg { name: n.into(), desc: d.into(), typ: t })
  513. .collect();
  514. let result = result
  515. .into_iter()
  516. .map(|(n, d, t)| CallArg { name: n.into(), desc: d.into(), typ: t })
  517. .collect();
  518. self.methods.push(Method { name: name.into(), args, result, method_fn });
  519. Ok(())
  520. }
  521. pub fn get_method(&self, name: &str) -> Option<&Method> {
  522. self.methods.iter().find(|method| method.name == name)
  523. }
  524. fn get_method_mut(&mut self, name: &str) -> Option<&mut Method> {
  525. self.methods.iter_mut().find(|method| method.name == name)
  526. }
  527. pub fn call_method(
  528. &mut self,
  529. name: &str,
  530. arg_data: Vec<u8>,
  531. response_fn: MethodResponseFn,
  532. ) -> Result<()> {
  533. let method = self.get_method(name).ok_or(Error::MethodNotFound)?;
  534. (method.method_fn)(arg_data, response_fn);
  535. Ok(())
  536. }
  537. }
  538. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  539. pub enum CallArgType {
  540. Uint32,
  541. Uint64,
  542. Bool,
  543. Str,
  544. Hash,
  545. }
  546. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  547. pub struct CallArg {
  548. pub name: String,
  549. pub desc: String,
  550. pub typ: CallArgType,
  551. }
  552. type SlotFn = Box<dyn Fn(Vec<u8>) + Send>;
  553. pub type SlotId = u32;
  554. pub struct Slot {
  555. pub name: String,
  556. pub notify: Sender<Vec<u8>>,
  557. }
  558. pub struct Signal {
  559. pub name: String,
  560. pub desc: String,
  561. pub fmt: Vec<CallArg>,
  562. slots: Vec<Slot>,
  563. freed: Vec<SlotId>,
  564. }
  565. impl Signal {
  566. fn slot_exists(&self, slot_id: SlotId) -> bool {
  567. if slot_id >= self.slots.len() as SlotId {
  568. return false;
  569. }
  570. return !self.freed.contains(&slot_id);
  571. }
  572. pub fn get_slots<'a>(&'a self) -> impl Iterator<Item = (SlotId, &'a Slot)> {
  573. self.slots
  574. .iter()
  575. .enumerate()
  576. .filter(|(slot_id, _)| !self.freed.contains(&(*slot_id as SlotId)))
  577. .map(|(slot_id, slot)| (slot_id as SlotId, slot))
  578. }
  579. pub fn lookup_slot_id(&self, slot_name: &str) -> Option<SlotId> {
  580. for (slot_id, slot) in self.get_slots() {
  581. if slot.name == slot_name {
  582. return Some(slot_id);
  583. }
  584. }
  585. None
  586. }
  587. }
  588. type MethodRequestFn = Box<dyn Fn(Vec<u8>, MethodResponseFn) + Send + Sync>;
  589. pub type MethodResponseFn = Box<dyn Fn(Result<Vec<u8>>) + Send + Sync>;
  590. pub struct Method {
  591. pub name: String,
  592. pub args: Vec<CallArg>,
  593. pub result: Vec<CallArg>,
  594. method_fn: MethodRequestFn,
  595. }
  596. pub enum Pimpl {
  597. Null,
  598. Window(ui::WindowPtr),
  599. RenderLayer(ui::RenderLayerPtr),
  600. Mesh(ui::MeshPtr),
  601. Text(ui::TextPtr),
  602. EditBox(ui::EditBoxPtr),
  603. ChatView(ui::ChatViewPtr),
  604. Image(ui::ImagePtr),
  605. Button(ui::ButtonPtr),
  606. }
  607. impl std::fmt::Debug for SceneNode {
  608. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  609. write!(f, "'{}':{}", self.name, self.id)
  610. }
  611. }