mod.rs 15 KB

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