main.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 std::sync::{mpsc, Arc};
  39. #[macro_use]
  40. extern crate log;
  41. #[allow(unused_imports)]
  42. use log::LevelFilter;
  43. mod app;
  44. //mod darkirc;
  45. mod error;
  46. mod expr;
  47. mod gfx;
  48. mod mesh;
  49. mod net;
  50. //mod plugin;
  51. mod prop;
  52. mod pubsub;
  53. //mod py;
  54. mod ringbuf;
  55. mod scene;
  56. use scene::SceneNode as SceneNode3;
  57. mod text;
  58. mod ui;
  59. mod util;
  60. use crate::{net::ZeroMQAdapter, text::TextShaper};
  61. pub type ExecutorPtr = Arc<smol::Executor<'static>>;
  62. fn panic_hook(panic_info: &std::panic::PanicInfo) {
  63. error!("panic occurred: {panic_info}");
  64. //error!("panic: {}", std::backtrace::Backtrace::force_capture().to_string());
  65. std::process::exit(1);
  66. }
  67. fn main() {
  68. // Exit the application on panic right away
  69. std::panic::set_hook(Box::new(panic_hook));
  70. #[cfg(target_os = "android")]
  71. {
  72. android_logger::init_once(
  73. android_logger::Config::default().with_max_level(LevelFilter::Debug).with_tag("darkfi"),
  74. );
  75. let paths = std::fs::read_dir("/data/data/darkfi.darkwallet/").unwrap();
  76. for path in paths {
  77. debug!("{}", path.unwrap().path().display())
  78. }
  79. }
  80. #[cfg(target_os = "linux")]
  81. {
  82. // For ANSI colors in the terminal
  83. colored::control::set_override(true);
  84. let term_logger = simplelog::TermLogger::new(
  85. simplelog::LevelFilter::Debug,
  86. simplelog::Config::default(),
  87. simplelog::TerminalMode::Mixed,
  88. simplelog::ColorChoice::Auto,
  89. );
  90. simplelog::CombinedLogger::init(vec![term_logger]).expect("logger");
  91. }
  92. let ex = Arc::new(smol::Executor::new());
  93. let sg_root = SceneNode3::root();
  94. let async_runtime = app::AsyncRuntime::new(ex.clone());
  95. async_runtime.start();
  96. let sg_root2 = sg_root.clone();
  97. let ex2 = ex.clone();
  98. let zmq_task = ex.spawn(async {
  99. let zmq_rpc = ZeroMQAdapter::new(sg_root2, ex2).await;
  100. zmq_rpc.run().await;
  101. });
  102. async_runtime.push_task(zmq_task);
  103. let (method_req, method_rep) = mpsc::channel();
  104. // The UI actually needs to be running for this to reply back.
  105. // Otherwise calls will just hang.
  106. let render_api = gfx::RenderApi::new(method_req);
  107. let event_pub = gfx::GraphicsEventPublisher::new();
  108. let text_shaper = TextShaper::new();
  109. //let darkirc_backend = DarkIrcBackend::new();
  110. let app = app::App::new(
  111. sg_root.clone(),
  112. render_api.clone(),
  113. event_pub.clone(),
  114. text_shaper,
  115. //darkirc_backend,
  116. ex.clone(),
  117. );
  118. let app_task = ex.spawn(app.clone().start());
  119. async_runtime.push_task(app_task);
  120. // Nice to see which events exist
  121. let ev_sub = event_pub.subscribe_key_down();
  122. let ev_relay_task = ex.spawn(async move {
  123. debug!(target: "main", "event relayer started");
  124. loop {
  125. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  126. debug!(target: "main", "Event relayer closed");
  127. break
  128. };
  129. // Ignore keys which get stuck repeating when switching windows
  130. match key {
  131. miniquad::KeyCode::LeftShift | miniquad::KeyCode::LeftSuper => continue,
  132. _ => {}
  133. }
  134. if !repeat {
  135. debug!(target: "main", "key_down event: {:?} {:?} {}", key, mods, repeat);
  136. }
  137. }
  138. });
  139. async_runtime.push_task(ev_relay_task);
  140. let ev_sub = event_pub.subscribe_key_up();
  141. let ev_relay_task = ex.spawn(async move {
  142. debug!(target: "main", "event relayer started");
  143. loop {
  144. let Ok((key, mods)) = 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. debug!(target: "main", "key_up event: {:?} {:?}", key, mods);
  154. }
  155. });
  156. async_runtime.push_task(ev_relay_task);
  157. let ev_sub = event_pub.subscribe_char();
  158. let ev_relay_task = ex.spawn(async move {
  159. debug!(target: "main", "event relayer started");
  160. loop {
  161. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  162. debug!(target: "main", "Event relayer closed");
  163. break
  164. };
  165. debug!(target: "main", "char event: {:?} {:?} {}", key, mods, repeat);
  166. }
  167. });
  168. async_runtime.push_task(ev_relay_task);
  169. //let stage = gfx::Stage::new(method_rep, event_pub);
  170. gfx::run_gui(app, async_runtime, method_rep, event_pub);
  171. debug!(target: "main", "Started GFX backend");
  172. }
  173. /*
  174. use rustpython_vm::{self as pyvm, convert::ToPyObject};
  175. fn main() {
  176. let module = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  177. let source = r#"
  178. def foo():
  179. open("hihi", "w")
  180. return 110
  181. #max(1 + lw/3, 4*10) + foo(2, True)
  182. "#;
  183. //let code_obj = vm
  184. // .compile(source, pyvm::compiler::Mode::Exec, "<embedded>".to_owned())
  185. // .map_err(|err| vm.new_syntax_error(&err, Some(source))).unwrap();
  186. //code_obj
  187. pyvm::import::import_source(vm, "lain", source).unwrap()
  188. });
  189. fn foo(x: u32, y: bool) -> u32 {
  190. if y {
  191. 2 * x
  192. } else {
  193. x
  194. }
  195. }
  196. let res = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  197. let globals = vm.ctx.new_dict();
  198. globals.set_item("lw", vm.ctx.new_int(110).to_pyobject(vm), vm).unwrap();
  199. globals.set_item("lh", vm.ctx.new_int(4).to_pyobject(vm), vm).unwrap();
  200. globals.set_item("foo", vm.new_function("foo", foo).into(), vm).unwrap();
  201. let scope = pyvm::scope::Scope::new(None, globals);
  202. let foo_fn = module.get_attr("foo", vm).unwrap();
  203. foo_fn.call((), vm).unwrap()
  204. //vm.run_code_obj(code_obj, scope).unwrap()
  205. });
  206. println!("{:?}", res);
  207. }
  208. */