main.rs 7.6 KB

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