main.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. // channel wait until deadline
  19. #![feature(deadline_api)]
  20. // Adds remainder() fn for String::split() result
  21. #![feature(str_split_whitespace_remainder)]
  22. // instant.elapsed().as_millis_f32()
  23. #![feature(duration_millis_float)]
  24. // Allow attributes on statements and code blocks
  25. #![feature(stmt_expr_attributes)]
  26. // if let Some(is_foo) = is_foo && is_foo { ... }
  27. #![feature(let_chains)]
  28. // consume a box
  29. #![feature(box_into_inner)]
  30. // we need Arc::get_mut_unchecked() to workaround the lack of Arc::new_cyclic() which
  31. // accepts async fns.
  32. // See https://github.com/rust-lang/rust/issues/112566
  33. #![feature(get_mut_unchecked)]
  34. // Use these to incrementally fix warnings with cargo fix
  35. //#![allow(warnings, unused)]
  36. //#![deny(unused_imports)]
  37. use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock};
  38. use darkfi::system::CondVar;
  39. use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate};
  40. use std::sync::{mpsc, Arc};
  41. #[macro_use]
  42. extern crate log;
  43. #[allow(unused_imports)]
  44. use log::LevelFilter;
  45. mod app;
  46. mod build_info;
  47. //mod darkirc;
  48. mod darkirc2;
  49. mod error;
  50. mod expr;
  51. mod gfx;
  52. mod logger;
  53. mod mesh;
  54. mod net;
  55. //mod plugin;
  56. mod prop;
  57. mod pubsub;
  58. //mod py;
  59. mod ringbuf;
  60. mod scene;
  61. use scene::SceneNode as SceneNode3;
  62. mod text;
  63. mod ui;
  64. mod util;
  65. use crate::{
  66. darkirc2::{LocalDarkIRC, LocalDarkIRCPtr},
  67. net::ZeroMQAdapter,
  68. text::TextShaper,
  69. };
  70. pub type ExecutorPtr = Arc<smol::Executor<'static>>;
  71. fn panic_hook(panic_info: &std::panic::PanicInfo) {
  72. error!("panic occurred: {panic_info}");
  73. //error!("panic: {}", std::backtrace::Backtrace::force_capture().to_string());
  74. std::process::exit(1);
  75. }
  76. fn main() {
  77. // Exit the application on panic right away
  78. std::panic::set_hook(Box::new(panic_hook));
  79. logger::setup_logging();
  80. #[cfg(target_os = "android")]
  81. {
  82. // Workaround for this bug
  83. // https://gitlab.torproject.org/tpo/core/arti/-/issues/999
  84. unsafe {
  85. std::env::set_var("HOME", "/data/data/darkfi.darkwallet/");
  86. }
  87. let paths = std::fs::read_dir("/data/data/darkfi.darkwallet/").unwrap();
  88. for path in paths {
  89. debug!("{}", path.unwrap().path().display())
  90. }
  91. }
  92. let exe_path = std::env::current_exe().unwrap();
  93. let basename = exe_path.parent().unwrap();
  94. std::env::set_current_dir(basename);
  95. info!("Target OS: {}", build_info::TARGET_OS);
  96. info!("Target arch: {}", build_info::TARGET_ARCH);
  97. let cwd = std::env::current_dir().unwrap();
  98. info!("Current dir: {}", cwd.display());
  99. let ex = Arc::new(smol::Executor::new());
  100. let sg_root = SceneNode3::root();
  101. let async_runtime = app::AsyncRuntime::new(ex.clone());
  102. async_runtime.start();
  103. let sg_root2 = sg_root.clone();
  104. let ex2 = ex.clone();
  105. let zmq_task = ex.spawn(async {
  106. let zmq_rpc = ZeroMQAdapter::new(sg_root2, ex2).await;
  107. zmq_rpc.run().await;
  108. });
  109. async_runtime.push_task(zmq_task);
  110. let (method_req, method_rep) = mpsc::channel();
  111. // The UI actually needs to be running for this to reply back.
  112. // Otherwise calls will just hang.
  113. let render_api = gfx::RenderApi::new(method_req);
  114. let event_pub = gfx::GraphicsEventPublisher::new();
  115. let text_shaper = TextShaper::new();
  116. let cv_started = Arc::new(CondVar::new());
  117. let cv_started2 = cv_started.clone();
  118. let app = app::App::new(sg_root, render_api, event_pub.clone(), text_shaper, ex.clone());
  119. let app2 = app.clone();
  120. let app_task = ex.spawn(async move {
  121. app2.start().await;
  122. cv_started2.notify();
  123. });
  124. async_runtime.push_task(app_task);
  125. let app2 = app.clone();
  126. let sg_root = app.sg_root.clone();
  127. let ex2 = ex.clone();
  128. let darkirc_task = ex.spawn(async move {
  129. cv_started.wait().await;
  130. let darkirc_evgr = LocalDarkIRC::new(sg_root.clone(), ex2.clone()).await.unwrap();
  131. *app2.darkirc_evgr.lock().unwrap() = Some(darkirc_evgr.clone());
  132. if let Err(e) = darkirc_evgr.start(ex2).await {
  133. error!("DarkIRC error: {e}")
  134. }
  135. });
  136. async_runtime.push_task(darkirc_task);
  137. /*
  138. // Nice to see which events exist
  139. let ev_sub = event_pub.subscribe_key_down();
  140. let ev_relay_task = ex.spawn(async move {
  141. debug!(target: "main", "event relayer started");
  142. loop {
  143. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  144. debug!(target: "main", "Event relayer closed");
  145. break
  146. };
  147. // Ignore keys which get stuck repeating when switching windows
  148. match key {
  149. miniquad::KeyCode::LeftShift | miniquad::KeyCode::LeftSuper => continue,
  150. _ => {}
  151. }
  152. if !repeat {
  153. debug!(target: "main", "key_down event: {:?} {:?} {}", key, mods, repeat);
  154. }
  155. }
  156. });
  157. async_runtime.push_task(ev_relay_task);
  158. let ev_sub = event_pub.subscribe_key_up();
  159. let ev_relay_task = ex.spawn(async move {
  160. debug!(target: "main", "event relayer started");
  161. loop {
  162. let Ok((key, mods)) = ev_sub.receive().await else {
  163. debug!(target: "main", "Event relayer closed");
  164. break
  165. };
  166. // Ignore keys which get stuck repeating when switching windows
  167. match key {
  168. miniquad::KeyCode::LeftShift | miniquad::KeyCode::LeftSuper => continue,
  169. _ => {}
  170. }
  171. debug!(target: "main", "key_up event: {:?} {:?}", key, mods);
  172. }
  173. });
  174. async_runtime.push_task(ev_relay_task);
  175. let ev_sub = event_pub.subscribe_char();
  176. let ev_relay_task = ex.spawn(async move {
  177. debug!(target: "main", "event relayer started");
  178. loop {
  179. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  180. debug!(target: "main", "Event relayer closed");
  181. break
  182. };
  183. debug!(target: "main", "char event: {:?} {:?} {}", key, mods, repeat);
  184. }
  185. });
  186. async_runtime.push_task(ev_relay_task);
  187. */
  188. //let stage = gfx::Stage::new(method_rep, event_pub);
  189. gfx::run_gui(app, async_runtime, method_rep, event_pub);
  190. debug!(target: "main", "Started GFX backend");
  191. }
  192. /*
  193. use rustpython_vm::{self as pyvm, convert::ToPyObject};
  194. fn main() {
  195. let module = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  196. let source = r#"
  197. def foo():
  198. open("hihi", "w")
  199. return 110
  200. #max(1 + lw/3, 4*10) + foo(2, True)
  201. "#;
  202. //let code_obj = vm
  203. // .compile(source, pyvm::compiler::Mode::Exec, "<embedded>".to_owned())
  204. // .map_err(|err| vm.new_syntax_error(&err, Some(source))).unwrap();
  205. //code_obj
  206. pyvm::import::import_source(vm, "lain", source).unwrap()
  207. });
  208. fn foo(x: u32, y: bool) -> u32 {
  209. if y {
  210. 2 * x
  211. } else {
  212. x
  213. }
  214. }
  215. let res = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  216. let globals = vm.ctx.new_dict();
  217. globals.set_item("lw", vm.ctx.new_int(110).to_pyobject(vm), vm).unwrap();
  218. globals.set_item("lh", vm.ctx.new_int(4).to_pyobject(vm), vm).unwrap();
  219. globals.set_item("foo", vm.new_function("foo", foo).into(), vm).unwrap();
  220. let scope = pyvm::scope::Scope::new(None, globals);
  221. let foo_fn = module.get_attr("foo", vm).unwrap();
  222. foo_fn.call((), vm).unwrap()
  223. //vm.run_code_obj(code_obj, scope).unwrap()
  224. });
  225. println!("{:?}", res);
  226. }
  227. */