main.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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. // string.chars().advance_back_by(n), not strictly needed but makes life easier
  35. #![feature(iter_advance_by)]
  36. // Use these to incrementally fix warnings with cargo fix
  37. //#![allow(warnings, unused)]
  38. //#![deny(unused_imports)]
  39. use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock};
  40. use darkfi::system::CondVar;
  41. use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate};
  42. use std::sync::{mpsc, Arc};
  43. #[macro_use]
  44. extern crate log;
  45. #[allow(unused_imports)]
  46. use log::LevelFilter;
  47. #[cfg(target_os = "android")]
  48. mod android;
  49. mod app;
  50. mod build_info;
  51. mod error;
  52. mod expr;
  53. mod gfx;
  54. mod logger;
  55. mod mesh;
  56. mod net;
  57. mod plugin;
  58. mod prop;
  59. mod pubsub;
  60. //mod py;
  61. mod ringbuf;
  62. mod scene;
  63. mod shape;
  64. use scene::SceneNode as SceneNode3;
  65. mod text;
  66. mod ui;
  67. mod util;
  68. use crate::{net::ZeroMQAdapter, text::TextShaper};
  69. // Hides the cmd.exe terminal on Windows.
  70. // Enable this when making release builds.
  71. //#![windows_subsystem = "windows"]
  72. pub type ExecutorPtr = Arc<smol::Executor<'static>>;
  73. fn panic_hook(panic_info: &std::panic::PanicHookInfo) {
  74. error!("panic occurred: {panic_info}");
  75. error!("{}", std::backtrace::Backtrace::force_capture().to_string());
  76. std::process::abort()
  77. }
  78. fn main() {
  79. // Abort the application on panic right away
  80. std::panic::set_hook(Box::new(panic_hook));
  81. logger::setup_logging();
  82. #[cfg(target_os = "android")]
  83. {
  84. use crate::android::{get_appdata_path, get_external_storage_path};
  85. info!("App internal data path: {:?}", get_appdata_path());
  86. info!("App external storage path: {:?}", get_external_storage_path());
  87. // Workaround for this bug
  88. // https://gitlab.torproject.org/tpo/core/arti/-/issues/999
  89. unsafe {
  90. std::env::set_var("HOME", get_appdata_path().as_os_str());
  91. }
  92. //let paths = std::fs::read_dir("/data/data/darkfi.darkfi/").unwrap();
  93. //for path in paths {
  94. // debug!("{}", path.unwrap().path().display())
  95. //}
  96. }
  97. let exe_path = std::env::current_exe().unwrap();
  98. let basename = exe_path.parent().unwrap();
  99. std::env::set_current_dir(basename);
  100. info!("Target OS: {}", build_info::TARGET_OS);
  101. info!("Target arch: {}", build_info::TARGET_ARCH);
  102. let cwd = std::env::current_dir().unwrap();
  103. info!("Current dir: {}", cwd.display());
  104. let ex = Arc::new(smol::Executor::new());
  105. let sg_root = SceneNode3::root();
  106. let async_runtime = app::AsyncRuntime::new(ex.clone());
  107. async_runtime.start();
  108. #[cfg(feature = "enable-netdebug")]
  109. {
  110. let sg_root2 = sg_root.clone();
  111. let ex2 = ex.clone();
  112. let zmq_task = ex.spawn(async {
  113. let zmq_rpc = ZeroMQAdapter::new(sg_root2, ex2).await;
  114. zmq_rpc.run().await;
  115. });
  116. async_runtime.push_task(zmq_task);
  117. }
  118. let (method_req, method_rep) = mpsc::channel();
  119. // The UI actually needs to be running for this to reply back.
  120. // Otherwise calls will just hang.
  121. let render_api = gfx::RenderApi::new(method_req);
  122. let event_pub = gfx::GraphicsEventPublisher::new();
  123. let text_shaper = TextShaper::new();
  124. let cv_gfxwin_started = Arc::new(CondVar::new());
  125. let cv_gfxwin_started2 = cv_gfxwin_started.clone();
  126. let cv_app_started = Arc::new(CondVar::new());
  127. let cv_app_started2 = cv_app_started.clone();
  128. let app = app::App::new(sg_root, render_api, event_pub.clone(), text_shaper, ex.clone());
  129. let app2 = app.clone();
  130. let app_task = ex.spawn(async move {
  131. app2.setup().await;
  132. // Needed because accessing screen_size() is not allowed until window init
  133. cv_gfxwin_started2.wait().await;
  134. app2.start().await;
  135. cv_app_started2.notify();
  136. });
  137. async_runtime.push_task(app_task);
  138. /*
  139. // Nice to see which events exist
  140. let ev_sub = event_pub.subscribe_key_down();
  141. let ev_relay_task = ex.spawn(async move {
  142. debug!(target: "main", "event relayer started");
  143. loop {
  144. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  145. debug!(target: "main", "Event relayer closed");
  146. break
  147. };
  148. // Ignore keys which get stuck repeating when switching windows
  149. match key {
  150. miniquad::KeyCode::LeftShift | miniquad::KeyCode::LeftSuper => continue,
  151. _ => {}
  152. }
  153. if !repeat {
  154. debug!(target: "main", "key_down event: {:?} {:?} {}", key, mods, repeat);
  155. }
  156. }
  157. });
  158. async_runtime.push_task(ev_relay_task);
  159. let ev_sub = event_pub.subscribe_key_up();
  160. let ev_relay_task = ex.spawn(async move {
  161. debug!(target: "main", "event relayer started");
  162. loop {
  163. let Ok((key, mods)) = ev_sub.receive().await else {
  164. debug!(target: "main", "Event relayer closed");
  165. break
  166. };
  167. // Ignore keys which get stuck repeating when switching windows
  168. match key {
  169. miniquad::KeyCode::LeftShift | miniquad::KeyCode::LeftSuper => continue,
  170. _ => {}
  171. }
  172. debug!(target: "main", "key_up event: {:?} {:?}", key, mods);
  173. }
  174. });
  175. async_runtime.push_task(ev_relay_task);
  176. let ev_sub = event_pub.subscribe_char();
  177. let ev_relay_task = ex.spawn(async move {
  178. debug!(target: "main", "event relayer started");
  179. loop {
  180. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  181. debug!(target: "main", "Event relayer closed");
  182. break
  183. };
  184. debug!(target: "main", "char event: {:?} {:?} {}", key, mods, repeat);
  185. }
  186. });
  187. async_runtime.push_task(ev_relay_task);
  188. */
  189. //let stage = gfx::Stage::new(method_rep, event_pub);
  190. gfx::run_gui(app, async_runtime, method_rep, event_pub, cv_gfxwin_started);
  191. debug!(target: "main", "Started GFX backend");
  192. }
  193. /*
  194. use rustpython_vm::{self as pyvm, convert::ToPyObject};
  195. fn main() {
  196. let module = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  197. let source = r#"
  198. def foo():
  199. open("hihi", "w")
  200. return 110
  201. #max(1 + lw/3, 4*10) + foo(2, True)
  202. "#;
  203. //let code_obj = vm
  204. // .compile(source, pyvm::compiler::Mode::Exec, "<embedded>".to_owned())
  205. // .map_err(|err| vm.new_syntax_error(&err, Some(source))).unwrap();
  206. //code_obj
  207. pyvm::import::import_source(vm, "lain", source).unwrap()
  208. });
  209. fn foo(x: u32, y: bool) -> u32 {
  210. if y {
  211. 2 * x
  212. } else {
  213. x
  214. }
  215. }
  216. let res = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  217. let globals = vm.ctx.new_dict();
  218. globals.set_item("lw", vm.ctx.new_int(110).to_pyobject(vm), vm).unwrap();
  219. globals.set_item("lh", vm.ctx.new_int(4).to_pyobject(vm), vm).unwrap();
  220. globals.set_item("foo", vm.new_function("foo", foo).into(), vm).unwrap();
  221. let scope = pyvm::scope::Scope::new(None, globals);
  222. let foo_fn = module.get_attr("foo", vm).unwrap();
  223. foo_fn.call((), vm).unwrap()
  224. //vm.run_code_obj(code_obj, scope).unwrap()
  225. });
  226. println!("{:?}", res);
  227. }
  228. */