main.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. // Hides the cmd.exe terminal on Windows.
  19. // Enable this when making release builds.
  20. #![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
  21. use clap::Parser;
  22. use darkfi::system::CondVar;
  23. use std::sync::{Arc, OnceLock};
  24. #[macro_use]
  25. extern crate tracing;
  26. #[derive(Debug)]
  27. pub enum AndroidSuggestEvent {
  28. Init,
  29. CreateInputConnect,
  30. Compose { text: String, cursor_pos: i32, is_commit: bool },
  31. ComposeRegion { start: usize, end: usize },
  32. FinishCompose,
  33. DeleteSurroundingText { left: usize, right: usize },
  34. }
  35. #[cfg(target_os = "android")]
  36. mod android;
  37. mod app;
  38. mod build_info;
  39. mod error;
  40. mod expr;
  41. mod gfx;
  42. mod logger;
  43. mod mesh;
  44. #[cfg(feature = "enable-netdebug")]
  45. mod net;
  46. mod plugin;
  47. mod prop;
  48. mod pubsub;
  49. //mod py;
  50. //mod ringbuf;
  51. mod scene;
  52. mod shape;
  53. mod text;
  54. mod text2;
  55. mod ui;
  56. mod util;
  57. use crate::{
  58. app::{App, AppPtr},
  59. gfx::EpochIndex,
  60. prop::{Property, PropertySubType, PropertyType},
  61. scene::{CallArgType, SceneNode, SceneNodeType},
  62. text::TextShaper,
  63. util::AsyncRuntime,
  64. };
  65. #[cfg(feature = "enable-netdebug")]
  66. use net::ZeroMQAdapter;
  67. #[cfg(feature = "enable-plugins")]
  68. use {
  69. darkfi_serial::{deserialize, Decodable, Encodable},
  70. gfx::RenderApi,
  71. prop::{PropertyBool, PropertyStr, Role},
  72. scene::{SceneNodePtr, Slot},
  73. std::io::Cursor,
  74. ui::chatview,
  75. };
  76. // This is historical, but ideally we can fix the entire project and remove this import.
  77. pub use util::ExecutorPtr;
  78. macro_rules! t { ($($arg:tt)*) => { trace!(target: "main", $($arg)*); } }
  79. #[cfg(feature = "enable-plugins")]
  80. macro_rules! d { ($($arg:tt)*) => { trace!(target: "main", $($arg)*); } }
  81. #[cfg(feature = "enable-plugins")]
  82. macro_rules! i { ($($arg:tt)*) => { trace!(target: "main", $($arg)*); } }
  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. /// Contains values which persist between app restarts. For example on Android, we are
  89. /// running a foreground service. Everytime the UI restarts main() is called again.
  90. /// However the global state remains intact.
  91. struct God {
  92. _bg_runtime: AsyncRuntime,
  93. _bg_ex: ExecutorPtr,
  94. pub fg_runtime: AsyncRuntime,
  95. pub fg_ex: ExecutorPtr,
  96. /// App must fully finish setup() before start() is allowed to begin.
  97. cv_app_is_setup: Arc<CondVar>,
  98. app: AppPtr,
  99. /// This is the main rendering API used to send commands to the gfx subsystem.
  100. /// We have a ref here so the gfx subsystem can increment the epoch counter.
  101. render_api: gfx::RenderApi,
  102. /// This is how the gfx subsystem receives messages from the render API.
  103. method_recv: async_channel::Receiver<(gfx::EpochIndex, gfx::GraphicsMethod)>,
  104. /// Publisher to send input and window events to subscribers.
  105. event_pub: gfx::GraphicsEventPublisherPtr,
  106. /// A WorkerGuard for file logging used to ensure buffered logs are flushed
  107. /// to their output in the case of abrupt terminations of a process.
  108. _file_logging_guard: Option<tracing_appender::non_blocking::WorkerGuard>,
  109. }
  110. impl God {
  111. fn new() -> Self {
  112. // Abort the application on panic right away
  113. std::panic::set_hook(Box::new(panic_hook));
  114. text2::init_txt_ctx();
  115. let file_logging_guard = logger::setup_logging();
  116. info!(target: "main", "Creating the app");
  117. #[cfg(target_os = "android")]
  118. {
  119. use crate::android::get_appdata_path;
  120. // Workaround for this bug
  121. // https://gitlab.torproject.org/tpo/core/arti/-/issues/999
  122. unsafe {
  123. std::env::set_var("HOME", get_appdata_path().as_os_str());
  124. }
  125. }
  126. let exe_path = std::env::current_exe().unwrap();
  127. let basename = exe_path.parent().unwrap();
  128. std::env::set_current_dir(basename).unwrap();
  129. let bg_ex = Arc::new(smol::Executor::new());
  130. let fg_ex = Arc::new(smol::Executor::new());
  131. let sg_root = SceneNode::root();
  132. let bg_runtime = AsyncRuntime::new(bg_ex.clone(), "bg");
  133. bg_runtime.start();
  134. let fg_runtime = AsyncRuntime::new(fg_ex.clone(), "fg");
  135. let (method_send, method_recv) = async_channel::unbounded();
  136. // The UI actually needs to be running for this to reply back.
  137. // Otherwise calls will just hang.
  138. let render_api = gfx::RenderApi::new(method_send);
  139. let event_pub = gfx::GraphicsEventPublisher::new();
  140. let text_shaper = TextShaper::new();
  141. let app = App::new(sg_root.clone(), render_api.clone(), text_shaper, fg_ex.clone());
  142. let app2 = app.clone();
  143. let cv_app_is_setup = Arc::new(CondVar::new());
  144. let cv = cv_app_is_setup.clone();
  145. let app_task = fg_ex.spawn(async move {
  146. app2.setup().await.unwrap();
  147. cv.notify();
  148. });
  149. fg_runtime.push_task(app_task);
  150. #[cfg(feature = "enable-netdebug")]
  151. {
  152. let sg_root = sg_root.clone();
  153. let ex = bg_ex.clone();
  154. let render_api = render_api.clone();
  155. let zmq_task = bg_ex.spawn(async {
  156. let zmq_rpc = ZeroMQAdapter::new(sg_root, render_api, ex).await;
  157. zmq_rpc.run().await;
  158. });
  159. bg_runtime.push_task(zmq_task);
  160. }
  161. #[cfg(feature = "enable-plugins")]
  162. {
  163. let ex = bg_ex.clone();
  164. let cv = cv_app_is_setup.clone();
  165. let render_api = render_api.clone();
  166. let plug_task = bg_ex.spawn(async move {
  167. load_plugins(ex, sg_root, render_api, cv).await;
  168. });
  169. bg_runtime.push_task(plug_task);
  170. }
  171. #[cfg(not(feature = "enable-plugins"))]
  172. warn!(target: "main", "Plugins are disabled in this build");
  173. Self {
  174. _bg_runtime: bg_runtime,
  175. _bg_ex: bg_ex,
  176. fg_runtime,
  177. fg_ex,
  178. cv_app_is_setup,
  179. app,
  180. render_api,
  181. method_recv,
  182. event_pub,
  183. _file_logging_guard: file_logging_guard,
  184. }
  185. }
  186. /// Start the app. Can only happen once the window is ready.
  187. pub fn start_app(&self, epoch: EpochIndex) {
  188. info!(target: "main", "Starting the app");
  189. #[cfg(target_os = "android")]
  190. {
  191. use crate::android::{get_appdata_path, get_external_storage_path};
  192. info!("App internal data path: {:?}", get_appdata_path());
  193. info!("App external storage path: {:?}", get_external_storage_path());
  194. //let paths = std::fs::read_dir("/data/data/darkfi.darkfi/").unwrap();
  195. //for path in paths {
  196. // debug!("{}", path.unwrap().path().display())
  197. //}
  198. }
  199. info!("Target OS: {}", build_info::TARGET_OS);
  200. info!("Target arch: {}", build_info::TARGET_ARCH);
  201. let cwd = std::env::current_dir().unwrap();
  202. info!("Current dir: {}", cwd.display());
  203. self.fg_runtime.start_with_count(2);
  204. let app = self.app.clone();
  205. let cv = self.cv_app_is_setup.clone();
  206. let event_pub = self.event_pub.clone();
  207. smol::block_on(async move {
  208. cv.wait().await;
  209. app.start(event_pub, epoch).await;
  210. });
  211. }
  212. /// Put the app to sleep until the next restart.
  213. pub fn stop_app(&self) {
  214. self.fg_runtime.stop();
  215. self.app.stop();
  216. info!(target: "main", "App stopped");
  217. }
  218. }
  219. impl std::fmt::Debug for God {
  220. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  221. write!(f, "God")
  222. }
  223. }
  224. static GOD: OnceLock<God> = OnceLock::new();
  225. #[cfg(feature = "enable-plugins")]
  226. async fn load_plugins(
  227. ex: ExecutorPtr,
  228. sg_root: SceneNodePtr,
  229. render_api: RenderApi,
  230. cv: Arc<CondVar>,
  231. ) {
  232. let plugin = SceneNode::new("plugin", SceneNodeType::PluginRoot);
  233. let plugin = plugin.setup_null();
  234. sg_root.link(plugin.clone());
  235. let darkirc = create_darkirc("darkirc");
  236. let darkirc = darkirc
  237. .setup(|me| async {
  238. plugin::DarkIrc::new(me, ex.clone()).await.expect("DarkIrc pimpl setup")
  239. })
  240. .await;
  241. let (slot, recvr) = Slot::new("recvmsg");
  242. darkirc.register("recv", slot).unwrap();
  243. let sg_root2 = sg_root.clone();
  244. let darkirc_nick = PropertyStr::wrap(&darkirc, Role::App, "nick", 0).unwrap();
  245. let render_api2 = render_api.clone();
  246. let listen_recv = ex.spawn(async move {
  247. while let Ok(data) = recvr.recv().await {
  248. let atom = &mut render_api2.make_guard(gfxtag!("darkirc msg recv"));
  249. let mut cur = Cursor::new(&data);
  250. let channel = String::decode(&mut cur).unwrap();
  251. let timestamp = chatview::Timestamp::decode(&mut cur).unwrap();
  252. let id = chatview::MessageId::decode(&mut cur).unwrap();
  253. let nick = String::decode(&mut cur).unwrap();
  254. let msg = String::decode(&mut cur).unwrap();
  255. let node_path = format!("/window/{channel}_chat_layer/content/chatty");
  256. t!("Attempting to relay message to {node_path}");
  257. let Some(chatview) = sg_root2.lookup_node(&node_path) else {
  258. d!("Ignoring message since {node_path} doesn't exist");
  259. continue
  260. };
  261. // I prefer to just re-encode because the code is clearer.
  262. let mut data = vec![];
  263. timestamp.encode(&mut data).unwrap();
  264. id.encode(&mut data).unwrap();
  265. nick.encode(&mut data).unwrap();
  266. msg.encode(&mut data).unwrap();
  267. if let Err(err) = chatview.call_method("insert_line", data).await {
  268. error!(
  269. target: "app",
  270. "Call method {node_path}::insert_line({timestamp}, {id}, {nick}, '{msg}'): {err:?}"
  271. );
  272. }
  273. // Apply coloring when you get a message
  274. let chat_path = format!("/window/{channel}_chat_layer");
  275. let chat_layer = sg_root2.lookup_node(chat_path).unwrap();
  276. if chat_layer.get_property_bool("is_visible").unwrap() {
  277. continue
  278. }
  279. let node_path = format!("/window/menu_layer/{channel}_channel_label");
  280. let menu_label = sg_root2.lookup_node(&node_path).unwrap();
  281. let prop = menu_label.get_property("text_color").unwrap();
  282. if msg.contains(&darkirc_nick.get()) {
  283. // Nick highlight
  284. prop.set_f32(atom, Role::App, 0, 0.56).unwrap();
  285. prop.set_f32(atom, Role::App, 1, 0.61).unwrap();
  286. prop.set_f32(atom, Role::App, 2, 1.).unwrap();
  287. prop.set_f32(atom, Role::App, 3, 1.).unwrap();
  288. } else {
  289. // Normal channel activity
  290. prop.set_f32(atom, Role::App, 0, 0.36).unwrap();
  291. prop.set_f32(atom, Role::App, 1, 1.).unwrap();
  292. prop.set_f32(atom, Role::App, 2, 0.51).unwrap();
  293. prop.set_f32(atom, Role::App, 3, 1.).unwrap();
  294. }
  295. }
  296. });
  297. let (slot, recvr) = Slot::new("connect");
  298. darkirc.register("connect", slot).unwrap();
  299. let sg_root2 = sg_root.clone();
  300. let listen_connect = ex.spawn(async move {
  301. cv.wait().await;
  302. let net0 = sg_root2.lookup_node("/window/netstatus_layer/net0").unwrap();
  303. let net1 = sg_root2.lookup_node("/window/netstatus_layer/net1").unwrap();
  304. let net2 = sg_root2.lookup_node("/window/netstatus_layer/net2").unwrap();
  305. let net3 = sg_root2.lookup_node("/window/netstatus_layer/net3").unwrap();
  306. let net0_is_visible = PropertyBool::wrap(&net0, Role::App, "is_visible", 0).unwrap();
  307. let net1_is_visible = PropertyBool::wrap(&net1, Role::App, "is_visible", 0).unwrap();
  308. let net2_is_visible = PropertyBool::wrap(&net2, Role::App, "is_visible", 0).unwrap();
  309. let net3_is_visible = PropertyBool::wrap(&net3, Role::App, "is_visible", 0).unwrap();
  310. while let Ok(data) = recvr.recv().await {
  311. let (peers_count, is_dag_synced): (u32, bool) = deserialize(&data).unwrap();
  312. let atom = &mut render_api.make_guard(gfxtag!("netstatus change"));
  313. if peers_count == 0 {
  314. net0_is_visible.set(atom, true);
  315. net1_is_visible.set(atom, false);
  316. net2_is_visible.set(atom, false);
  317. net3_is_visible.set(atom, false);
  318. continue
  319. }
  320. assert!(peers_count > 0);
  321. if !is_dag_synced {
  322. net0_is_visible.set(atom, false);
  323. net1_is_visible.set(atom, true);
  324. net2_is_visible.set(atom, false);
  325. net3_is_visible.set(atom, false);
  326. continue
  327. }
  328. assert!(peers_count > 0 && is_dag_synced);
  329. if peers_count == 1 {
  330. net0_is_visible.set(atom, false);
  331. net1_is_visible.set(atom, false);
  332. net2_is_visible.set(atom, true);
  333. net3_is_visible.set(atom, false);
  334. continue
  335. }
  336. net0_is_visible.set(atom, false);
  337. net1_is_visible.set(atom, false);
  338. net2_is_visible.set(atom, false);
  339. net3_is_visible.set(atom, true);
  340. }
  341. });
  342. plugin.link(darkirc);
  343. i!("Plugins loaded");
  344. futures::join!(listen_recv, listen_connect);
  345. }
  346. pub fn create_darkirc(name: &str) -> SceneNode {
  347. t!("create_darkirc({name})");
  348. let mut node = SceneNode::new(name, SceneNodeType::Plugin);
  349. let mut prop = Property::new("nick", PropertyType::Str, PropertySubType::Null);
  350. prop.set_ui_text("Nick", "Nickname");
  351. prop.set_defaults_str(vec!["anon".to_string()]).unwrap();
  352. node.add_property(prop).unwrap();
  353. node.add_signal(
  354. "recv",
  355. "Message received",
  356. vec![
  357. ("channel", "Channel", CallArgType::Str),
  358. ("timestamp", "Timestamp", CallArgType::Uint64),
  359. ("id", "ID", CallArgType::Hash),
  360. ("nick", "Nick", CallArgType::Str),
  361. ("msg", "Message", CallArgType::Str),
  362. ],
  363. )
  364. .unwrap();
  365. node.add_signal(
  366. "connect",
  367. "Connections and disconnects",
  368. vec![
  369. ("peers_count", "Peers Count", CallArgType::Uint32),
  370. ("dag_synced", "Is DAG Synced", CallArgType::Bool),
  371. ],
  372. )
  373. .unwrap();
  374. node.add_method(
  375. "send",
  376. vec![("channel", "Channel", CallArgType::Str), ("msg", "Message", CallArgType::Str)],
  377. None,
  378. )
  379. .unwrap();
  380. node
  381. }
  382. /// Simple program to greet a person
  383. #[derive(Parser, Debug)]
  384. #[command(version, about, long_about = None)]
  385. struct Args {
  386. /// On Linux use the X11 backend
  387. #[arg(long)]
  388. linux_x11_backend: bool,
  389. /// On Linux use the wayland backend
  390. #[arg(long)]
  391. linux_wayland_backend: bool,
  392. }
  393. fn main() {
  394. let args = Args::parse();
  395. GOD.get_or_init(God::new);
  396. // Reuse render_api, event_pub and text_shaper
  397. // No need for setup(), just wait for gfx start then call .start()
  398. // ZMQ, darkirc stay running
  399. let linux_backend = if args.linux_wayland_backend {
  400. if args.linux_x11_backend {
  401. miniquad::conf::LinuxBackend::WaylandWithX11Fallback
  402. } else {
  403. miniquad::conf::LinuxBackend::WaylandOnly
  404. }
  405. } else if args.linux_x11_backend {
  406. miniquad::conf::LinuxBackend::X11Only
  407. } else {
  408. miniquad::conf::LinuxBackend::WaylandWithX11Fallback
  409. };
  410. gfx::run_gui(linux_backend);
  411. debug!(target: "main", "Started GFX backend");
  412. }
  413. /*
  414. use rustpython_vm::{self as pyvm, convert::ToPyObject};
  415. fn main() {
  416. let module = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  417. let source = r#"
  418. def foo():
  419. open("hihi", "w")
  420. return 110
  421. #max(1 + lw/3, 4*10) + foo(2, True)
  422. "#;
  423. //let code_obj = vm
  424. // .compile(source, pyvm::compiler::Mode::Exec, "<embedded>".to_owned())
  425. // .map_err(|err| vm.new_syntax_error(&err, Some(source))).unwrap();
  426. //code_obj
  427. pyvm::import::import_source(vm, "lain", source).unwrap()
  428. });
  429. fn foo(x: u32, y: bool) -> u32 {
  430. if y {
  431. 2 * x
  432. } else {
  433. x
  434. }
  435. }
  436. let res = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  437. let globals = vm.ctx.new_dict();
  438. globals.set_item("lw", vm.ctx.new_int(110).to_pyobject(vm), vm).unwrap();
  439. globals.set_item("lh", vm.ctx.new_int(4).to_pyobject(vm), vm).unwrap();
  440. globals.set_item("foo", vm.new_function("foo", foo).into(), vm).unwrap();
  441. let scope = pyvm::scope::Scope::new(None, globals);
  442. let foo_fn = module.get_attr("foo", vm).unwrap();
  443. foo_fn.call((), vm).unwrap()
  444. //vm.run_code_obj(code_obj, scope).unwrap()
  445. });
  446. println!("{:?}", res);
  447. }
  448. */