net.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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_lock::Mutex;
  19. use darkfi_serial::{async_trait, deserialize, Decodable, Encodable, SerialDecodable, VarInt};
  20. use std::{io::Cursor, sync::Arc};
  21. use zeromq::{Socket, SocketRecv, SocketSend};
  22. use crate::{
  23. app::node::{create_layer, create_vector_art},
  24. error::{Error, Result},
  25. expr::{decompile, Compiler, MachineGlobals, SExprCode, SExprMachine, SExprVal},
  26. gfx::{gfxtag, Renderer},
  27. prop::{PropertyPermission, PropertyType, Role},
  28. scene::{Pimpl, SceneNodeId, SceneNodePtr, SceneNodeType, ScenePath, Slot},
  29. ui::{
  30. get_ui_object3, get_ui_object_ptr, Layer, RedrawTrigger, ShapeVertex, VectorArt,
  31. VectorShape,
  32. },
  33. ExecutorPtr,
  34. };
  35. /// Stop the UI tasks and clear the buffers of a subtree about to be
  36. /// removed at runtime, mirroring Window::stop(). Only pimpl types with a
  37. /// UIObject mapping are touched; others (Window, Setting, plugins, Null)
  38. /// keep their tasks until process exit.
  39. fn stop_ui_subtree(node: &SceneNodePtr) {
  40. if matches!(
  41. node.pimpl(),
  42. Pimpl::Layer(_) |
  43. Pimpl::ScrollLayer(_) |
  44. Pimpl::VectorArt(_) |
  45. Pimpl::Text(_) |
  46. Pimpl::TextScramble(_) |
  47. Pimpl::Edit(_) |
  48. Pimpl::Image(_) |
  49. Pimpl::Video(_) |
  50. Pimpl::Button(_) |
  51. Pimpl::EmojiPicker(_) |
  52. Pimpl::Shortcut(_) |
  53. Pimpl::Menu(_) |
  54. Pimpl::TokenTable(_) |
  55. Pimpl::Slider(_) |
  56. Pimpl::Dropdown(_)
  57. ) {
  58. get_ui_object3(node).stop();
  59. }
  60. for child in node.get_children() {
  61. stop_ui_subtree(&child);
  62. }
  63. }
  64. /// Run a freshly compiled expr on a throwaway machine so unknown
  65. /// variables (typos) reject the set request instead of failing silently
  66. /// on every eval afterwards. The dummy values are irrelevant; only name
  67. /// resolution matters and the globals are discarded. `global_names` are
  68. /// the variable names the property's real eval can provide.
  69. fn check_expr(code: &SExprCode, global_names: &[String]) -> Result<()> {
  70. let mut globals: MachineGlobals = vec![];
  71. for name in global_names {
  72. globals.push((name.clone(), SExprVal::Float32(1.)));
  73. }
  74. let mut machine = SExprMachine { globals, stmts: code };
  75. machine.call()?;
  76. Ok(())
  77. }
  78. const USE_IPV6: bool = true;
  79. #[derive(Debug, SerialDecodable)]
  80. #[repr(u8)]
  81. enum Command {
  82. Hello = 0,
  83. AddNode = 1,
  84. RemoveNode = 9,
  85. RenameNode = 23,
  86. ScanDangling = 24,
  87. LookupNodeId = 12,
  88. AddProperty = 11,
  89. LinkNode = 2,
  90. UnlinkNode = 8,
  91. GetInfo = 19,
  92. GetChildren = 4,
  93. GetParents = 5,
  94. GetProperties = 3,
  95. GetPropertyValue = 6,
  96. SetPropertyValue = 7,
  97. GetSignals = 14,
  98. RegisterSlot = 15,
  99. UnregisterSlot = 16,
  100. LookupSlotId = 17,
  101. GetSlots = 18,
  102. GetMethods = 20,
  103. GetMethod = 21,
  104. CallMethod = 22,
  105. }
  106. // Missing calls todo:
  107. // GetPropLen
  108. // UnsetProperty
  109. // SetPropertyNull
  110. // PropertyPushNull
  111. // PropertyPush
  112. // PropertyIsUnset
  113. pub struct ZeroMQAdapter {
  114. /*
  115. // req-reply commands
  116. req_socket: zmq::Socket,
  117. // We cannot share zmq sockets across threads, and we cannot quickly spawn
  118. // pub sockets due to address reuse errors.
  119. slot_sender: mpsc::SyncSender<(Vec<u8>, Vec<u8>)>,
  120. slot_recvr: Option<mpsc::Receiver<(Vec<u8>, Vec<u8>)>>,
  121. */
  122. sg_root: SceneNodePtr,
  123. renderer: Renderer,
  124. redraw: RedrawTrigger,
  125. ex: ExecutorPtr,
  126. zmq_rep: Mutex<zeromq::RepSocket>,
  127. zmq_pub: Mutex<zeromq::PubSocket>,
  128. }
  129. impl ZeroMQAdapter {
  130. pub async fn new(
  131. sg_root: SceneNodePtr,
  132. renderer: Renderer,
  133. redraw: RedrawTrigger,
  134. ex: ExecutorPtr,
  135. ) -> Arc<Self> {
  136. let mut zmq_rep = zeromq::RepSocket::new();
  137. if USE_IPV6 {
  138. zmq_rep.bind("tcp://[::]:9484").await.unwrap();
  139. } else {
  140. zmq_rep.bind("tcp://0.0.0.0:9484").await.unwrap();
  141. }
  142. let mut zmq_pub = zeromq::PubSocket::new();
  143. if USE_IPV6 {
  144. zmq_pub.bind("tcp://[::]:9485").await.unwrap();
  145. } else {
  146. zmq_pub.bind("tcp://0.0.0.0:9485").await.unwrap();
  147. }
  148. Arc::new(Self {
  149. sg_root,
  150. renderer,
  151. redraw,
  152. ex,
  153. zmq_rep: Mutex::new(zmq_rep),
  154. zmq_pub: Mutex::new(zmq_pub),
  155. })
  156. }
  157. pub async fn run(self: Arc<Self>) {
  158. loop {
  159. let req = self.zmq_rep.lock().await.recv().await.unwrap();
  160. assert_eq!(req.len(), 2);
  161. let cmd = req.get(0).unwrap().to_vec();
  162. assert_eq!(cmd.len(), 1);
  163. let payload = req.get(1).unwrap().to_vec();
  164. let cmd = deserialize(&cmd).unwrap();
  165. debug!(target: "req", "zmq: {:?} {:?}", cmd, payload);
  166. let self2 = self.clone();
  167. match self2.process_request(cmd, payload).await {
  168. Ok(reply) => {
  169. let mut m = zeromq::ZmqMessage::from(vec![0u8]);
  170. m.push_back(reply.into());
  171. // [errc:1] [reply]
  172. self.zmq_rep.lock().await.send(m).await.unwrap();
  173. }
  174. Err(err) => {
  175. let errc = err as u8;
  176. warn!(target: "req", "errc {}: {}", errc, err);
  177. let mut m = zeromq::ZmqMessage::from(vec![errc]);
  178. m.push_back(vec![].into());
  179. // [errc:1] [reply]
  180. self.zmq_rep.lock().await.send(m).await.unwrap();
  181. }
  182. }
  183. }
  184. }
  185. async fn process_request(self: Arc<Self>, cmd: Command, payload: Vec<u8>) -> Result<Vec<u8>> {
  186. let mut cur = Cursor::new(&payload);
  187. let mut reply = vec![];
  188. match cmd {
  189. Command::Hello => {
  190. debug!(target: "req", "hello()");
  191. assert_eq!(payload.len(), 0);
  192. "hello".encode(&mut reply).unwrap();
  193. }
  194. Command::GetInfo => {
  195. /*
  196. let node_id = SceneNodeId::decode(&mut cur).unwrap();
  197. debug!(target: "req", "{:?}({})", cmd, node_id);
  198. let node = scene_graph.get_node(node_id).ok_or(Error::NodeNotFound)?;
  199. node.name.encode(&mut reply).unwrap();
  200. node.typ.encode(&mut reply).unwrap();
  201. */
  202. }
  203. Command::GetChildren => {
  204. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  205. debug!(target: "req", "{cmd:?}({node_path})");
  206. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  207. let children: Vec<_> = node
  208. .get_children()
  209. .iter()
  210. .map(|node| (node.name.clone(), node.id, node.typ))
  211. .collect();
  212. children.encode(&mut reply).unwrap();
  213. }
  214. Command::GetParents => {
  215. /*
  216. let node_id = SceneNodeId::decode(&mut cur).unwrap();
  217. debug!(target: "req", "{:?}({})", cmd, node_id);
  218. let node = scene_graph.get_node(node_id).ok_or(Error::NodeNotFound)?;
  219. let parents: Vec<_> = node
  220. .parents
  221. .iter()
  222. .map(|node_inf| (node_inf.name.clone(), node_inf.id, node_inf.typ))
  223. .collect();
  224. parents.encode(&mut reply).unwrap();
  225. */
  226. }
  227. Command::GetProperties => {
  228. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  229. debug!(target: "req", "{cmd:?}({node_path})");
  230. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  231. VarInt(node.props.len() as u64).encode(&mut reply).unwrap();
  232. for prop in &node.props {
  233. prop.name.encode(&mut reply).unwrap();
  234. prop.typ.encode(&mut reply).unwrap();
  235. prop.subtype.encode(&mut reply).unwrap();
  236. //prop.defaults.encode(&mut reply).unwrap();
  237. prop.ui_name.encode(&mut reply).unwrap();
  238. prop.desc.encode(&mut reply).unwrap();
  239. prop.is_null_allowed.encode(&mut reply).unwrap();
  240. prop.is_expr_allowed.encode(&mut reply).unwrap();
  241. (prop.array_len as u32).encode(&mut reply).unwrap();
  242. prop.min_val.encode(&mut reply).unwrap();
  243. prop.max_val.encode(&mut reply).unwrap();
  244. prop.enum_items.encode(&mut reply).unwrap();
  245. let depends: Vec<_> = prop
  246. .get_depends()
  247. .into_iter()
  248. .map(|d| (d.i as u32, d.local_name))
  249. .collect();
  250. depends.encode(&mut reply).unwrap();
  251. }
  252. }
  253. Command::GetPropertyValue => {
  254. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  255. let prop_name = String::decode(&mut cur).unwrap();
  256. debug!(target: "req", "{cmd:?}({node_path}, {prop_name})");
  257. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  258. let prop = node.get_property(&prop_name).ok_or(Error::PropertyNotFound)?;
  259. prop.typ.encode(&mut reply).unwrap();
  260. VarInt(prop.get_len() as u64).encode(&mut reply).unwrap();
  261. for i in 0..prop.get_len() {
  262. // Check the raw stored value, since get_value() resolves
  263. // exprs to their cached/default value and would never
  264. // report the EXPR status.
  265. let val = prop.get_raw_value(i)?;
  266. if val.is_expr() {
  267. 3u8.encode(&mut reply).unwrap();
  268. let expr = prop.get_expr(i)?;
  269. decompile(&expr).encode(&mut reply).unwrap();
  270. } else if val.is_unset() {
  271. // A null default encodes zero payload bytes, so it
  272. // is reported as the NULL status instead of UNSET.
  273. // This mirrors the old get_value() semantics, where
  274. // an unset index with a null default resolved to
  275. // null.
  276. let default = prop.defaults.lock().unwrap()[i].clone();
  277. if default.is_null() {
  278. 2u8.encode(&mut reply).unwrap();
  279. } else if default.is_expr() {
  280. // An unset index resolving through a default
  281. // expr reports the decompiled expr source under
  282. // the EXPR status. Encoding the SExprCode bytes
  283. // as the payload would desync the client, which
  284. // expects a payload matching the property type
  285. // on the UNSET path.
  286. 3u8.encode(&mut reply).unwrap();
  287. let expr = default.as_sexpr().unwrap();
  288. decompile(&expr).encode(&mut reply).unwrap();
  289. } else {
  290. 1u8.encode(&mut reply).unwrap();
  291. // Shapes are not serialized on the get path;
  292. // the python client shows a "<...>" placeholder.
  293. if prop.typ != PropertyType::VectorShape {
  294. default.encode(&mut reply).unwrap();
  295. }
  296. }
  297. } else if val.is_null() {
  298. 2u8.encode(&mut reply).unwrap();
  299. } else {
  300. 0u8.encode(&mut reply).unwrap();
  301. if prop.typ != PropertyType::VectorShape {
  302. val.encode(&mut reply).unwrap();
  303. }
  304. }
  305. }
  306. }
  307. Command::SetPropertyValue => {
  308. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  309. let prop_name = String::decode(&mut cur).unwrap();
  310. let prop_i = u32::decode(&mut cur).unwrap() as usize;
  311. let prop_type = PropertyType::decode(&mut cur).unwrap();
  312. debug!(target: "req", "{cmd:?}({node_path}, {prop_name}, {prop_i}, {prop_type:?})");
  313. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  314. let prop = node.get_property(&prop_name).ok_or(Error::PropertyNotFound)?;
  315. let atom = &mut self.redraw.make_guard(gfxtag!("ZeroMQAdapter::SetPropertyValue"));
  316. match prop_type {
  317. PropertyType::Null => {
  318. prop.set_null(atom, Role::Root, prop_i)?;
  319. }
  320. PropertyType::Bool => {
  321. let val = bool::decode(&mut cur).unwrap();
  322. prop.set_bool(atom, Role::Root, prop_i, val)?;
  323. }
  324. PropertyType::Uint32 => {
  325. let val = u32::decode(&mut cur).unwrap();
  326. prop.set_u32(atom, Role::Root, prop_i, val)?;
  327. }
  328. PropertyType::Float32 => {
  329. let val = f32::decode(&mut cur).unwrap();
  330. prop.set_f32(atom, Role::Root, prop_i, val)?;
  331. }
  332. PropertyType::Str => {
  333. let val = String::decode(&mut cur).unwrap();
  334. prop.set_str(atom, Role::Root, prop_i, val)?;
  335. }
  336. PropertyType::Enum => {
  337. let val = String::decode(&mut cur).unwrap();
  338. prop.set_enum(atom, Role::Root, prop_i, val)?;
  339. }
  340. PropertyType::SceneNodeId => {
  341. let val = SceneNodeId::decode(&mut cur).unwrap();
  342. prop.set_node_id(atom, Role::Root, prop_i, val)?;
  343. }
  344. PropertyType::SExpr => {
  345. // Exprs are sent as source strings and compiled here.
  346. // The netdebug compiler is const-free: only machine
  347. // globals (w, h, ...) are available as variables.
  348. let expr_str = String::decode(&mut cur).unwrap();
  349. debug!(target: "req", " compiling expr \"{expr_str}\"");
  350. let code = Compiler::new().compile(&expr_str)?;
  351. // The property's eval site provides its depends
  352. // names plus one of the machine global sets in
  353. // use (w, h for most rects, parent_*/rect_* for
  354. // edit behaves), so accept the union and treat
  355. // anything else as a typo.
  356. let mut names: Vec<String> =
  357. prop.get_depends().into_iter().map(|d| d.local_name).collect();
  358. names.extend(
  359. ["w", "h", "parent_w", "parent_h", "rect_w", "rect_h"]
  360. .iter()
  361. .map(|s| s.to_string()),
  362. );
  363. check_expr(&code, &names)?;
  364. prop.set_expr(atom, Role::Root, prop_i, code)?;
  365. }
  366. PropertyType::VectorShape => {
  367. // Vertices carry coordinate exprs as source strings,
  368. // compiled with the same const-free compiler. The
  369. // payload is: vert count varint; per vert: x expr
  370. // string, y expr string, 4x f32 color; index count
  371. // varint; u16 indices.
  372. let cc = Compiler::new();
  373. // Shape verts eval with only the w/h globals.
  374. let shape_globals: Vec<String> =
  375. ["w", "h"].iter().map(|s| s.to_string()).collect();
  376. let vert_count = VarInt::decode(&mut cur)?.0 as usize;
  377. let mut verts = vec![];
  378. for _ in 0..vert_count {
  379. let x_src = String::decode(&mut cur)?;
  380. let y_src = String::decode(&mut cur)?;
  381. let color = [
  382. f32::decode(&mut cur)?,
  383. f32::decode(&mut cur)?,
  384. f32::decode(&mut cur)?,
  385. f32::decode(&mut cur)?,
  386. ];
  387. let x = cc.compile(&x_src)?;
  388. let y = cc.compile(&y_src)?;
  389. check_expr(&x, &shape_globals)?;
  390. check_expr(&y, &shape_globals)?;
  391. verts.push(ShapeVertex::new(x, y, color));
  392. }
  393. let index_count = VarInt::decode(&mut cur)?.0 as usize;
  394. let mut indices = vec![];
  395. for _ in 0..index_count {
  396. let index = u16::decode(&mut cur)?;
  397. if index as usize >= verts.len() {
  398. return Err(Error::PropertyWrongIndex)
  399. }
  400. indices.push(index);
  401. }
  402. let shape = VectorShape { verts, indices };
  403. prop.set_shape(atom, Role::Root, prop_i, shape)?;
  404. }
  405. }
  406. }
  407. Command::AddNode => {
  408. let parent_path: ScenePath = String::decode(&mut cur)?.parse()?;
  409. let node_name = String::decode(&mut cur)?;
  410. let node_type = SceneNodeType::decode(&mut cur)?;
  411. debug!(target: "req", "{cmd:?}({parent_path}, {node_name}, {node_type:?})");
  412. let parent = self.sg_root.lookup_node(parent_path).ok_or(Error::NodeNotFound)?;
  413. if parent.get_children().iter().any(|c| c.name == node_name) {
  414. return Err(Error::NodeSiblingNameConflict)
  415. }
  416. let renderer = self.renderer.clone();
  417. let redraw = self.redraw.clone();
  418. let node = match node_type {
  419. SceneNodeType::Layer => {
  420. create_layer(&node_name)
  421. .setup(|me| Layer::new(me, renderer.clone(), redraw.clone()))
  422. .await
  423. }
  424. SceneNodeType::VectorArt => {
  425. create_vector_art(&node_name)
  426. .setup(|me| VectorArt::new(me, renderer.clone(), redraw.clone()))
  427. .await
  428. }
  429. _ => return Err(Error::UnsupportedNodeType),
  430. };
  431. // Hold the guard over the link so the triggered pass sees
  432. // the attached node.
  433. let _atom = self.redraw.make_guard(gfxtag!("ZeroMQAdapter::AddNode"));
  434. parent.link(node.clone());
  435. node.id.encode(&mut reply).unwrap();
  436. // Arm the pimpl's OnModify handlers (redraw on property
  437. // change) exactly like window-owned nodes. The task keeps a
  438. // strong ref so an immediate RemoveNode cannot drop the node
  439. // out from under start().
  440. let node2 = node.clone();
  441. let ex2 = self.ex.clone();
  442. self.ex
  443. .spawn(async move {
  444. let obj = get_ui_object_ptr(&node2);
  445. obj.start(ex2).await
  446. })
  447. .detach();
  448. }
  449. Command::RemoveNode => {
  450. let node_path: ScenePath = String::decode(&mut cur)?.parse()?;
  451. debug!(target: "req", "{cmd:?}({node_path})");
  452. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  453. // The scene root has no parent, removal is meaningless.
  454. if Arc::ptr_eq(&node, &self.sg_root) {
  455. return Err(Error::NodeNotRemovable)
  456. }
  457. // Tear down the subtree's UI tasks and buffers before
  458. // unlinking, mirroring Window::stop(). Pimpl types without
  459. // a UIObject mapping (Window, Setting, plugins, ...) keep
  460. // their tasks until process exit.
  461. stop_ui_subtree(&node);
  462. node.unlink();
  463. self.redraw.trigger();
  464. }
  465. Command::RenameNode => {
  466. /*
  467. let node_id = SceneNodeId::decode(&mut cur).unwrap();
  468. let node_name = String::decode(&mut cur).unwrap();
  469. debug!(target: "req", "{:?}({}, {})", cmd, node_id, node_name);
  470. scene_graph.rename_node(node_id, node_name)?;
  471. */
  472. }
  473. Command::ScanDangling => {
  474. /*
  475. let dangling = scene_graph.scan_dangling();
  476. dangling.encode(&mut reply).unwrap();
  477. */
  478. }
  479. Command::LookupNodeId => {
  480. /*
  481. let node_path: String = deserialize(&payload).unwrap();
  482. debug!(target: "req", "{:?}({})", cmd, node_path);
  483. let node_id = scene_graph.lookup_node_id(&node_path).ok_or(Error::NodeNotFound)?;
  484. node_id.encode(&mut reply).unwrap();
  485. */
  486. }
  487. Command::AddProperty => {
  488. /*
  489. let node_id = SceneNodeId::decode(&mut cur).unwrap();
  490. let prop_name = String::decode(&mut cur).unwrap();
  491. let prop_type = PropertyType::decode(&mut cur).unwrap();
  492. let prop_subtype = PropertySubType::decode(&mut cur).unwrap();
  493. debug!(target: "req", "{:?}({}, {}, {:?}, {:?}, ...)", cmd, node_id, prop_name, prop_type, prop_subtype);
  494. let mut prop = Property::new(prop_name, prop_type, prop_subtype, PropertyPermission::default());
  495. let prop_array_len = u32::decode(&mut cur).unwrap();
  496. prop.set_array_len(prop_array_len as usize);
  497. let prop_defaults_is_some = bool::decode(&mut cur).unwrap();
  498. if prop_defaults_is_some {
  499. let prop_defaults_len = VarInt::decode(&mut cur).unwrap();
  500. match prop_type {
  501. PropertyType::Uint32 => {
  502. let mut prop_defaults = vec![];
  503. for _ in 0..prop_defaults_len.0 {
  504. prop_defaults.push(u32::decode(&mut cur).unwrap());
  505. }
  506. prop.set_defaults_u32(prop_defaults)?;
  507. }
  508. PropertyType::Float32 => {
  509. let mut prop_defaults = vec![];
  510. for _ in 0..prop_defaults_len.0 {
  511. prop_defaults.push(f32::decode(&mut cur).unwrap());
  512. }
  513. prop.set_defaults_f32(prop_defaults)?;
  514. }
  515. PropertyType::Str => {
  516. let mut prop_defaults = vec![];
  517. for _ in 0..prop_defaults_len.0 {
  518. prop_defaults.push(String::decode(&mut cur).unwrap());
  519. }
  520. prop.set_defaults_str(prop_defaults)?;
  521. }
  522. _ => return Err(Error::PropertyWrongType),
  523. }
  524. }
  525. let prop_ui_name = String::decode(&mut cur).unwrap();
  526. let prop_desc = String::decode(&mut cur).unwrap();
  527. let prop_is_null_allowed = bool::decode(&mut cur).unwrap();
  528. let prop_is_expr_allowed = bool::decode(&mut cur).unwrap();
  529. match prop_type {
  530. PropertyType::Uint32 => {
  531. let min_is_some = bool::decode(&mut cur).unwrap();
  532. let min = if min_is_some {
  533. let min = u32::decode(&mut cur).unwrap();
  534. Some(PropertyValue::Uint32(min))
  535. } else {
  536. None
  537. };
  538. let max_is_some = bool::decode(&mut cur).unwrap();
  539. let max = if max_is_some {
  540. let max = u32::decode(&mut cur).unwrap();
  541. Some(PropertyValue::Uint32(max))
  542. } else {
  543. None
  544. };
  545. prop.min_val = min;
  546. prop.max_val = max;
  547. }
  548. PropertyType::Float32 => {
  549. let min_is_some = bool::decode(&mut cur).unwrap();
  550. let min = if min_is_some {
  551. let min = f32::decode(&mut cur).unwrap();
  552. Some(PropertyValue::Float32(min))
  553. } else {
  554. None
  555. };
  556. let max_is_some = bool::decode(&mut cur).unwrap();
  557. let max = if max_is_some {
  558. let max = f32::decode(&mut cur).unwrap();
  559. Some(PropertyValue::Float32(max))
  560. } else {
  561. None
  562. };
  563. prop.min_val = min;
  564. prop.max_val = max;
  565. }
  566. _ => {
  567. let min_is_some = bool::decode(&mut cur).unwrap();
  568. if min_is_some {
  569. return Err(Error::PropertyWrongType)
  570. }
  571. let max_is_some = bool::decode(&mut cur).unwrap();
  572. if max_is_some {
  573. return Err(Error::PropertyWrongType)
  574. }
  575. }
  576. }
  577. let prop_enum_items = Vec::<String>::decode(&mut cur).unwrap();
  578. let node = scene_graph.get_node_mut(node_id).ok_or(Error::NodeNotFound)?;
  579. prop.set_ui_text(prop_ui_name, prop_desc);
  580. prop.is_null_allowed = prop_is_null_allowed;
  581. prop.is_expr_allowed = prop_is_expr_allowed;
  582. if !prop_enum_items.is_empty() {
  583. prop.set_enum_items(prop_enum_items)?;
  584. }
  585. node.add_property(prop)?;
  586. */
  587. }
  588. Command::LinkNode => {
  589. /*
  590. let child_id = SceneNodeId::decode(&mut cur).unwrap();
  591. let parent_id = SceneNodeId::decode(&mut cur).unwrap();
  592. debug!(target: "req", "{:?}({}, {})", cmd, child_id, parent_id);
  593. scene_graph.link(child_id, parent_id)?;
  594. */
  595. }
  596. Command::UnlinkNode => {
  597. /*
  598. let child_id = SceneNodeId::decode(&mut cur).unwrap();
  599. let parent_id = SceneNodeId::decode(&mut cur).unwrap();
  600. debug!(target: "req", "{:?}({}, {})", cmd, child_id, parent_id);
  601. scene_graph.unlink(child_id, parent_id)?;
  602. */
  603. }
  604. Command::GetSignals => {
  605. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  606. debug!(target: "req", "{cmd:?}({node_path})");
  607. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  608. let sigs = node.sigs.read().unwrap();
  609. let sig_names: Vec<_> = sigs.iter().map(|sig| sig.name.clone()).collect();
  610. sig_names.encode(&mut reply).unwrap();
  611. }
  612. Command::RegisterSlot => {
  613. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  614. let sig_name = String::decode(&mut cur).unwrap();
  615. let slot_name = String::decode(&mut cur).unwrap();
  616. let user_data = Vec::<u8>::decode(&mut cur).unwrap();
  617. debug!(target: "req", "{cmd:?}({node_path}, {sig_name}, {slot_name}, {user_data:?})");
  618. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  619. let (sendr, recvr) = async_channel::unbounded();
  620. let slot = Slot { name: slot_name, notify: sendr };
  621. // This task will auto-die when the slot is unregistered
  622. let self2 = self.clone();
  623. self.ex
  624. .spawn(async move {
  625. loop {
  626. let Ok(signal_data) = recvr.recv().await else {
  627. // Die
  628. break
  629. };
  630. let mut m = zeromq::ZmqMessage::from(signal_data);
  631. m.push_back(user_data.clone().into());
  632. self2.zmq_pub.lock().await.send(m).await.unwrap();
  633. }
  634. })
  635. .detach();
  636. let slot_id = node.register(&sig_name, slot)?;
  637. slot_id.encode(&mut reply).unwrap();
  638. }
  639. Command::UnregisterSlot => {
  640. /*
  641. let node_id = SceneNodeId::decode(&mut cur).unwrap();
  642. let sig_name = String::decode(&mut cur).unwrap();
  643. let slot_id = SlotId::decode(&mut cur).unwrap();
  644. debug!(target: "req", "{:?}({}, {}, {})", cmd, node_id, sig_name, slot_id);
  645. let node = scene_graph.get_node_mut(node_id).ok_or(Error::NodeNotFound)?;
  646. node.unregister(&sig_name, slot_id)?;
  647. */
  648. }
  649. Command::LookupSlotId => {
  650. /*
  651. let node_id = SceneNodeId::decode(&mut cur).unwrap();
  652. let sig_name = String::decode(&mut cur).unwrap();
  653. let slot_name = String::decode(&mut cur).unwrap();
  654. debug!(target: "req", "{:?}({}, {}, {})", cmd, node_id, sig_name, slot_name);
  655. let node = scene_graph.get_node(node_id).ok_or(Error::NodeNotFound)?;
  656. let signal = node.get_signal(&sig_name).ok_or(Error::SignalNotFound)?;
  657. let slot_id = signal.lookup_slot_id(&slot_name).ok_or(Error::SlotNotFound)?;
  658. slot_id.encode(&mut reply).unwrap();
  659. */
  660. }
  661. Command::GetSlots => {
  662. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  663. let sig_name = String::decode(&mut cur).unwrap();
  664. debug!(target: "req", "{cmd:?}({node_path}, {sig_name})");
  665. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  666. let signal = node.get_signal(&sig_name).ok_or(Error::SignalNotFound)?;
  667. let slots = signal.get_slots();
  668. let slot_names: Vec<_> =
  669. slots.iter().map(|(slot_id, slot)| (slot.name.clone(), *slot_id)).collect();
  670. slot_names.encode(&mut reply).unwrap();
  671. }
  672. Command::GetMethods => {
  673. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  674. debug!(target: "req", "{cmd:?}({node_path})");
  675. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  676. let method_names: Vec<_> = node.methods.iter().map(|m| m.name.clone()).collect();
  677. method_names.encode(&mut reply).unwrap();
  678. }
  679. Command::GetMethod => {
  680. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  681. let method_name = String::decode(&mut cur).unwrap();
  682. debug!(target: "req", "{:?}({}, {})", cmd, node_path, method_name);
  683. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  684. let method = node.get_method(&method_name).ok_or(Error::MethodNotFound)?;
  685. method.args.encode(&mut reply).unwrap();
  686. method.result.encode(&mut reply).unwrap();
  687. }
  688. Command::CallMethod => {
  689. let node_path: ScenePath = String::decode(&mut cur).unwrap().parse()?;
  690. let method_name = String::decode(&mut cur).unwrap();
  691. let arg_data = Vec::<u8>::decode(&mut cur).unwrap();
  692. debug!(target: "req", "{cmd:?}({node_path}, {method_name}, ...)");
  693. let node = self.sg_root.lookup_node(node_path).ok_or(Error::NodeNotFound)?;
  694. let result = node.call_method(&method_name, arg_data).await?;
  695. result.encode(&mut reply).unwrap();
  696. }
  697. }
  698. Ok(reply)
  699. }
  700. }