mod.rs 12 KB

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