mod.rs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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_recursion::async_recursion;
  19. use chrono::{Local, NaiveDate, NaiveDateTime, TimeZone};
  20. use darkfi_serial::Encodable;
  21. use futures::{stream::FuturesUnordered, StreamExt};
  22. use sled_overlay::sled;
  23. use smol::Task;
  24. use std::{
  25. sync::{Arc, Mutex as SyncMutex},
  26. thread,
  27. };
  28. use crate::{
  29. darkirc::{DarkIrcBackendPtr, Privmsg},
  30. error::Error,
  31. expr::Op,
  32. gfx::{GraphicsEventPublisherPtr, RenderApiPtr, Vertex},
  33. prop::{Property, PropertyBool, PropertyStr, PropertySubType, PropertyType, Role},
  34. scene::{
  35. CallArgType, MethodResponseFn, Pimpl, SceneGraph, SceneGraphPtr2, SceneNodeId,
  36. SceneNodeType, Slot,
  37. },
  38. text::TextShaperPtr,
  39. ui::{
  40. chatview, Button, ChatView, EditBox, Image, RenderLayer, Stoppable, Text, VectorArt, Window,
  41. },
  42. ExecutorPtr,
  43. };
  44. mod node;
  45. mod schema;
  46. //fn print_type_of<T>(_: &T) {
  47. // println!("{}", std::any::type_name::<T>())
  48. //}
  49. pub struct AsyncRuntime {
  50. signal: async_channel::Sender<()>,
  51. shutdown: async_channel::Receiver<()>,
  52. exec_threadpool: SyncMutex<Option<thread::JoinHandle<()>>>,
  53. ex: ExecutorPtr,
  54. tasks: SyncMutex<Vec<Task<()>>>,
  55. }
  56. impl AsyncRuntime {
  57. pub fn new(ex: ExecutorPtr) -> Self {
  58. let (signal, shutdown) = async_channel::unbounded::<()>();
  59. Self {
  60. signal,
  61. shutdown,
  62. exec_threadpool: SyncMutex::new(None),
  63. ex,
  64. tasks: SyncMutex::new(vec![]),
  65. }
  66. }
  67. pub fn start(&self) {
  68. let n_threads = thread::available_parallelism().unwrap().get();
  69. let shutdown = self.shutdown.clone();
  70. let ex = self.ex.clone();
  71. let exec_threadpool = thread::spawn(move || {
  72. easy_parallel::Parallel::new()
  73. // N executor threads
  74. .each(0..n_threads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  75. .run();
  76. });
  77. *self.exec_threadpool.lock().unwrap() = Some(exec_threadpool);
  78. debug!(target: "async_runtime", "Started runtime");
  79. }
  80. pub fn push_task(&self, task: Task<()>) {
  81. self.tasks.lock().unwrap().push(task);
  82. }
  83. pub fn stop(&self) {
  84. // Go through event graph and call stop on everything
  85. // Depth first
  86. debug!(target: "app", "Stopping async runtime...");
  87. let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
  88. // Close all tasks
  89. smol::future::block_on(async {
  90. // Perform cleanup code
  91. // If not finished in certain amount of time, then just exit
  92. let futures = FuturesUnordered::new();
  93. for task in tasks {
  94. futures.push(task.cancel());
  95. }
  96. let _: Vec<_> = futures.collect().await;
  97. });
  98. if !self.signal.close() {
  99. error!(target: "app", "exec threadpool was already shutdown");
  100. }
  101. let exec_threadpool = std::mem::replace(&mut *self.exec_threadpool.lock().unwrap(), None);
  102. let exec_threadpool = exec_threadpool.expect("threadpool wasnt started");
  103. exec_threadpool.join().unwrap();
  104. debug!(target: "app", "Stopped app");
  105. }
  106. }
  107. pub type AppPtr = Arc<App>;
  108. pub struct App {
  109. pub(self) sg: SceneGraphPtr2,
  110. pub(self) ex: ExecutorPtr,
  111. pub(self) render_api: RenderApiPtr,
  112. pub(self) event_pub: GraphicsEventPublisherPtr,
  113. pub(self) text_shaper: TextShaperPtr,
  114. pub(self) darkirc_backend: DarkIrcBackendPtr,
  115. pub(self) tasks: SyncMutex<Vec<Task<()>>>,
  116. }
  117. impl App {
  118. pub fn new(
  119. sg: SceneGraphPtr2,
  120. ex: ExecutorPtr,
  121. render_api: RenderApiPtr,
  122. event_pub: GraphicsEventPublisherPtr,
  123. text_shaper: TextShaperPtr,
  124. darkirc_backend: DarkIrcBackendPtr,
  125. ) -> Arc<Self> {
  126. Arc::new(Self {
  127. sg,
  128. ex,
  129. render_api,
  130. event_pub,
  131. text_shaper,
  132. darkirc_backend,
  133. tasks: SyncMutex::new(vec![]),
  134. })
  135. }
  136. pub async fn start(self: Arc<Self>) {
  137. debug!(target: "app", "App::start()");
  138. // Setup UI
  139. let mut sg = self.sg.lock().await;
  140. let window = sg.add_node("window", SceneNodeType::Window);
  141. let mut prop = Property::new("screen_size", PropertyType::Float32, PropertySubType::Pixel);
  142. prop.set_array_len(2);
  143. // Window not yet initialized so we can't set these.
  144. //prop.set_f32(Role::App, 0, screen_width);
  145. //prop.set_f32(Role::App, 1, screen_height);
  146. window.add_property(prop).unwrap();
  147. let mut prop = Property::new("scale", PropertyType::Float32, PropertySubType::Pixel);
  148. prop.set_defaults_f32(vec![1.]).unwrap();
  149. window.add_property(prop).unwrap();
  150. let window_id = window.id;
  151. // Create Window
  152. // Window::new(window, weak sg)
  153. drop(sg);
  154. let pimpl = Window::new(
  155. self.ex.clone(),
  156. self.sg.clone(),
  157. window_id,
  158. self.render_api.clone(),
  159. self.event_pub.clone(),
  160. )
  161. .await;
  162. // -> reads any props it needs
  163. // -> starts procs
  164. let mut sg = self.sg.lock().await;
  165. let node = sg.get_node_mut(window_id).unwrap();
  166. node.pimpl = pimpl;
  167. sg.link(window_id, SceneGraph::ROOT_ID).unwrap();
  168. // Testing
  169. let node = sg.get_node(window_id).unwrap();
  170. node.set_property_f32(Role::App, "scale", 2.).unwrap();
  171. drop(sg);
  172. schema::make(&self).await;
  173. debug!(target: "app", "Schema loaded");
  174. // Access drawable in window node and call draw()
  175. self.trigger_redraw().await;
  176. // Start the backend
  177. //if let Err(err) = self.darkirc_backend.start(self.sg.clone(), self.ex.clone()).await {
  178. // error!(target: "app", "backend error: {err}");
  179. //}
  180. debug!(target: "app", "App started");
  181. }
  182. pub fn stop(&self) {
  183. smol::future::block_on(async {
  184. self.async_stop().await;
  185. });
  186. }
  187. async fn async_stop(&self) {
  188. self.darkirc_backend.stop().await;
  189. let sg = self.sg.lock().await;
  190. let window_id = sg.lookup_node("/window").unwrap().id;
  191. self.stop_node(&sg, window_id).await;
  192. drop(sg);
  193. }
  194. #[async_recursion]
  195. async fn stop_node(&self, sg: &SceneGraph, node_id: SceneNodeId) {
  196. let node = sg.get_node(node_id).unwrap();
  197. for child_inf in node.get_children2() {
  198. self.stop_node(sg, child_inf.id).await;
  199. }
  200. match &node.pimpl {
  201. Pimpl::Window(win) => win.stop().await,
  202. Pimpl::RenderLayer(layer) => layer.stop().await,
  203. Pimpl::VectorArt(svg) => svg.stop().await,
  204. Pimpl::Text(txt) => txt.stop().await,
  205. Pimpl::EditBox(ebox) => ebox.stop().await,
  206. Pimpl::ChatView(_) | Pimpl::Image(_) | Pimpl::Button(_) => {}
  207. _ => panic!("unhandled pimpl type"),
  208. };
  209. }
  210. async fn trigger_redraw(&self) {
  211. let sg = self.sg.lock().await;
  212. let window_node = sg.lookup_node("/window").expect("no window attached!");
  213. match &window_node.pimpl {
  214. Pimpl::Window(win) => win.draw(&sg).await,
  215. _ => panic!("wrong pimpl"),
  216. }
  217. }
  218. }
  219. impl Drop for App {
  220. fn drop(&mut self) {
  221. debug!(target: "app", "Dropping app");
  222. // This hangs
  223. //self.stop();
  224. }
  225. }
  226. // Just for testing
  227. fn populate_tree(tree: &sled::Tree) {
  228. let chat_txt = include_str!("../../chat.txt");
  229. for line in chat_txt.lines() {
  230. let parts: Vec<&str> = line.splitn(3, ' ').collect();
  231. assert_eq!(parts.len(), 3);
  232. let time_parts: Vec<&str> = parts[0].splitn(2, ':').collect();
  233. let (hour, min) = (time_parts[0], time_parts[1]);
  234. let hour = hour.parse::<u32>().unwrap();
  235. let min = min.parse::<u32>().unwrap();
  236. let dt: NaiveDateTime =
  237. NaiveDate::from_ymd_opt(2024, 8, 6).unwrap().and_hms_opt(hour, min, 0).unwrap();
  238. let timest = dt.and_utc().timestamp_millis() as u64;
  239. let nick = parts[1].to_string();
  240. let text = parts[2].to_string();
  241. // serial order is important here
  242. let timest = timest.to_be_bytes();
  243. assert_eq!(timest.len(), 8);
  244. let mut key = [0u8; 8 + 32];
  245. key[..8].clone_from_slice(&timest);
  246. let msg = chatview::ChatMsg { nick, text };
  247. let mut val = vec![];
  248. msg.encode(&mut val).unwrap();
  249. tree.insert(&key, val).unwrap();
  250. }
  251. // O(n)
  252. debug!(target: "app", "populated db with {} lines", tree.len());
  253. }