mod.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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::system::CondVar;
  21. use darkfi_serial::{Decodable, Encodable};
  22. use futures::{stream::FuturesUnordered, StreamExt};
  23. use sled_overlay::sled;
  24. use smol::Task;
  25. use std::{
  26. io::Cursor,
  27. sync::{Arc, Mutex as SyncMutex},
  28. thread,
  29. };
  30. use crate::{
  31. error::Error,
  32. expr::Op,
  33. gfx::{GraphicsEventPublisherPtr, RenderApi, Vertex},
  34. plugin::{self, PluginObject},
  35. prop::{Property, PropertyBool, PropertyStr, PropertySubType, PropertyType, Role},
  36. scene::{Pimpl, SceneNode as SceneNode3, SceneNodePtr, SceneNodeType as SceneNodeType3, Slot},
  37. text::TextShaperPtr,
  38. ui::{chatview, Window},
  39. ExecutorPtr,
  40. };
  41. mod node;
  42. use node::create_darkirc;
  43. mod schema;
  44. //fn print_type_of<T>(_: &T) {
  45. // println!("{}", std::any::type_name::<T>())
  46. //}
  47. pub struct AsyncRuntime {
  48. signal: async_channel::Sender<()>,
  49. shutdown: async_channel::Receiver<()>,
  50. exec_threadpool: SyncMutex<Option<thread::JoinHandle<()>>>,
  51. ex: ExecutorPtr,
  52. tasks: SyncMutex<Vec<Task<()>>>,
  53. }
  54. impl AsyncRuntime {
  55. pub fn new(ex: ExecutorPtr) -> Self {
  56. let (signal, shutdown) = async_channel::unbounded::<()>();
  57. Self {
  58. signal,
  59. shutdown,
  60. exec_threadpool: SyncMutex::new(None),
  61. ex,
  62. tasks: SyncMutex::new(vec![]),
  63. }
  64. }
  65. pub fn start(&self) {
  66. let n_threads = thread::available_parallelism().unwrap().get();
  67. let shutdown = self.shutdown.clone();
  68. let ex = self.ex.clone();
  69. let exec_threadpool = thread::spawn(move || {
  70. easy_parallel::Parallel::new()
  71. // N executor threads
  72. .each(0..n_threads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  73. .run();
  74. });
  75. *self.exec_threadpool.lock().unwrap() = Some(exec_threadpool);
  76. info!(target: "async_runtime", "Started runtime [{n_threads} threads]");
  77. }
  78. pub fn push_task(&self, task: Task<()>) {
  79. self.tasks.lock().unwrap().push(task);
  80. }
  81. pub fn stop(&self) {
  82. // Go through event graph and call stop on everything
  83. // Depth first
  84. debug!(target: "app", "Stopping async runtime...");
  85. let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
  86. // Close all tasks
  87. smol::future::block_on(async {
  88. // Perform cleanup code
  89. // If not finished in certain amount of time, then just exit
  90. let futures = FuturesUnordered::new();
  91. for task in tasks {
  92. futures.push(task.cancel());
  93. }
  94. let _: Vec<_> = futures.collect().await;
  95. });
  96. if !self.signal.close() {
  97. error!(target: "app", "exec threadpool was already shutdown");
  98. }
  99. let exec_threadpool = std::mem::replace(&mut *self.exec_threadpool.lock().unwrap(), None);
  100. let exec_threadpool = exec_threadpool.expect("threadpool wasnt started");
  101. exec_threadpool.join().unwrap();
  102. debug!(target: "app", "Stopped app");
  103. }
  104. }
  105. pub type AppPtr = Arc<App>;
  106. pub struct App {
  107. pub sg_root: SceneNodePtr,
  108. pub render_api: RenderApi,
  109. pub event_pub: GraphicsEventPublisherPtr,
  110. pub text_shaper: TextShaperPtr,
  111. pub tasks: SyncMutex<Vec<Task<()>>>,
  112. pub ex: ExecutorPtr,
  113. }
  114. impl App {
  115. pub fn new(
  116. sg_root: SceneNodePtr,
  117. render_api: RenderApi,
  118. event_pub: GraphicsEventPublisherPtr,
  119. text_shaper: TextShaperPtr,
  120. ex: ExecutorPtr,
  121. ) -> Arc<Self> {
  122. Arc::new(Self {
  123. sg_root,
  124. ex,
  125. render_api,
  126. event_pub,
  127. text_shaper,
  128. tasks: SyncMutex::new(vec![]),
  129. })
  130. }
  131. /// Does not require miniquad to be init. Created the scene graph tree / schema and all
  132. /// the objects.
  133. pub async fn setup(&self) {
  134. debug!(target: "app", "App::setup()");
  135. let mut window = SceneNode3::new("window", SceneNodeType3::Window);
  136. let mut prop = Property::new("screen_size", PropertyType::Float32, PropertySubType::Pixel);
  137. prop.set_array_len(2);
  138. window.add_property(prop).unwrap();
  139. let mut prop = Property::new("scale", PropertyType::Float32, PropertySubType::Pixel);
  140. prop.set_defaults_f32(vec![1.]).unwrap();
  141. window.add_property(prop).unwrap();
  142. let window = window.setup(|me| Window::new(me, self.render_api.clone())).await;
  143. self.sg_root.clone().link(window.clone());
  144. schema::make(&self, window).await;
  145. debug!(target: "app", "Schema loaded");
  146. let plugin = Arc::new(SceneNode3::new("plugin", SceneNodeType3::PluginRoot));
  147. self.sg_root.clone().link(plugin.clone());
  148. let darkirc = create_darkirc("darkirc");
  149. let darkirc = darkirc
  150. .setup(|me| async {
  151. plugin::DarkIrc::new(me, self.ex.clone()).await.expect("DarkIrc pimpl setup")
  152. })
  153. .await;
  154. let (slot, recvr) = Slot::new("recvmsg");
  155. darkirc.register("recv", slot).unwrap();
  156. let sg_root2 = self.sg_root.clone();
  157. let listen_recv = self.ex.spawn(async move {
  158. while let Ok(data) = recvr.recv().await {
  159. let mut cur = Cursor::new(&data);
  160. let channel = String::decode(&mut cur).unwrap();
  161. let timestamp = chatview::Timestamp::decode(&mut cur).unwrap();
  162. let id = chatview::MessageId::decode(&mut cur).unwrap();
  163. let nick = String::decode(&mut cur).unwrap();
  164. let msg = String::decode(&mut cur).unwrap();
  165. let node_path = format!("/window/{channel}_chat_layer/content/chatty");
  166. debug!(target: "app", "Attempting to relay message to {node_path}");
  167. let Some(chatview) = sg_root2.clone().lookup_node(&node_path) else {
  168. warn!(target: "app", "Ignoring message since {node_path} doesn't exist");
  169. continue
  170. };
  171. // I prefer to just re-encode because the code is clearer.
  172. let mut data = vec![];
  173. timestamp.encode(&mut data).unwrap();
  174. id.encode(&mut data).unwrap();
  175. nick.encode(&mut data).unwrap();
  176. msg.encode(&mut data).unwrap();
  177. if let Err(err) = chatview.call_method("insert_line", data).await {
  178. error!(
  179. target: "app",
  180. "Call method {node_path}::insert_line({timestamp}, {id}, {nick}, '{msg}'): {err:?}"
  181. );
  182. }
  183. }
  184. });
  185. self.tasks.lock().unwrap().push(listen_recv);
  186. plugin.link(darkirc);
  187. debug!(target: "app", "Plugins loaded");
  188. }
  189. /// Begins the draw of the tree, and then starts the UI procs.
  190. pub async fn start(self: Arc<Self>) {
  191. debug!(target: "app", "App::start()");
  192. let window_node = self.sg_root.clone().lookup_node("/window").unwrap();
  193. let prop = window_node.get_property("screen_size").unwrap();
  194. // We can only do this once the window has been created in miniquad.
  195. let (screen_width, screen_height) = miniquad::window::screen_size();
  196. prop.set_f32(Role::App, 0, screen_width);
  197. prop.set_f32(Role::App, 1, screen_height);
  198. // Access drawable in window node and call draw()
  199. self.trigger_draw().await;
  200. self.start_procs().await;
  201. debug!(target: "app", "App started");
  202. }
  203. pub fn stop(&self) {
  204. smol::future::block_on(async {
  205. self.async_stop().await;
  206. });
  207. }
  208. async fn trigger_draw(&self) {
  209. let window_node = self.sg_root.clone().lookup_node("/window").expect("no window attached!");
  210. match &window_node.pimpl {
  211. Pimpl::Window(win) => win.draw().await,
  212. _ => panic!("wrong pimpl"),
  213. }
  214. }
  215. async fn start_procs(&self) {
  216. let window_node = self.sg_root.clone().lookup_node("/window").unwrap();
  217. match &window_node.pimpl {
  218. Pimpl::Window(win) => win.clone().start(self.event_pub.clone(), self.ex.clone()).await,
  219. _ => panic!("wrong pimpl"),
  220. }
  221. let plugins = self.sg_root.clone().lookup_node("/plugin").unwrap();
  222. for plugin in plugins.get_children() {
  223. match &plugin.pimpl {
  224. Pimpl::DarkIrc(darkirc) => darkirc.clone().start(self.ex.clone()).await,
  225. _ => panic!("wrong pimpl"),
  226. }
  227. }
  228. }
  229. /// Shutdown code here
  230. async fn async_stop(&self) {
  231. //self.darkirc_backend.stop().await;
  232. }
  233. }
  234. impl Drop for App {
  235. fn drop(&mut self) {
  236. debug!(target: "app", "Dropping app");
  237. // This hangs
  238. //self.stop();
  239. }
  240. }
  241. // Just for testing
  242. fn populate_tree(tree: &sled::Tree) {
  243. let chat_txt = include_str!("../../chat.txt");
  244. for line in chat_txt.lines() {
  245. let parts: Vec<&str> = line.splitn(3, ' ').collect();
  246. assert_eq!(parts.len(), 3);
  247. let time_parts: Vec<&str> = parts[0].splitn(2, ':').collect();
  248. let (hour, min) = (time_parts[0], time_parts[1]);
  249. let hour = hour.parse::<u32>().unwrap();
  250. let min = min.parse::<u32>().unwrap();
  251. let dt: NaiveDateTime =
  252. NaiveDate::from_ymd_opt(2024, 8, 6).unwrap().and_hms_opt(hour, min, 0).unwrap();
  253. let timest = dt.and_utc().timestamp_millis() as u64;
  254. let nick = parts[1].to_string();
  255. let text = parts[2].to_string();
  256. // serial order is important here
  257. let timest = timest.to_be_bytes();
  258. assert_eq!(timest.len(), 8);
  259. let mut key = [0u8; 8 + 32];
  260. key[..8].clone_from_slice(&timest);
  261. let msg = chatview::ChatMsg { nick, text };
  262. let mut val = vec![];
  263. msg.encode(&mut val).unwrap();
  264. tree.insert(&key, val).unwrap();
  265. }
  266. // O(n)
  267. debug!(target: "app", "populated db with {} lines", tree.len());
  268. }