mod.rs 15 KB

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