main.rs 8.7 KB

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