main.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 fud = create_fud("fud");
  242. let sg_root2 = sg_root.clone();
  243. let fud = fud
  244. .setup(|me| async {
  245. plugin::FudPlugin::new(me, sg_root2, ex.clone()).await.expect("Fud pimpl setup")
  246. })
  247. .await;
  248. let (slot, recvr) = Slot::new("recvmsg");
  249. darkirc.register("recv", slot).unwrap();
  250. let sg_root2 = sg_root.clone();
  251. let darkirc_nick = PropertyStr::wrap(&darkirc, Role::App, "nick", 0).unwrap();
  252. let render_api2 = render_api.clone();
  253. let listen_recv = ex.spawn(async move {
  254. while let Ok(data) = recvr.recv().await {
  255. let atom = &mut render_api2.make_guard(gfxtag!("darkirc msg recv"));
  256. let mut cur = Cursor::new(&data);
  257. let channel = String::decode(&mut cur).unwrap();
  258. let timestamp = chatview::Timestamp::decode(&mut cur).unwrap();
  259. let id = chatview::MessageId::decode(&mut cur).unwrap();
  260. let nick = String::decode(&mut cur).unwrap();
  261. let msg = String::decode(&mut cur).unwrap();
  262. let node_path = format!("/window/{channel}_chat_layer/content/chatty");
  263. t!("Attempting to relay message to {node_path}");
  264. let Some(chatview) = sg_root2.lookup_node(&node_path) else {
  265. d!("Ignoring message since {node_path} doesn't exist");
  266. continue
  267. };
  268. // I prefer to just re-encode because the code is clearer.
  269. let mut data = vec![];
  270. timestamp.encode(&mut data).unwrap();
  271. id.encode(&mut data).unwrap();
  272. nick.encode(&mut data).unwrap();
  273. msg.encode(&mut data).unwrap();
  274. if let Err(err) = chatview.call_method("insert_line", data).await {
  275. error!(
  276. target: "app",
  277. "Call method {node_path}::insert_line({timestamp}, {id}, {nick}, '{msg}'): {err:?}"
  278. );
  279. }
  280. // Apply coloring when you get a message
  281. let chat_path = format!("/window/{channel}_chat_layer");
  282. let chat_layer = sg_root2.lookup_node(chat_path).unwrap();
  283. if chat_layer.get_property_bool("is_visible").unwrap() {
  284. continue
  285. }
  286. let node_path = format!("/window/menu_layer/{channel}_channel_label");
  287. let menu_label = sg_root2.lookup_node(&node_path).unwrap();
  288. let prop = menu_label.get_property("text_color").unwrap();
  289. if msg.contains(&darkirc_nick.get()) {
  290. // Nick highlight
  291. prop.set_f32(atom, Role::App, 0, 0.56).unwrap();
  292. prop.set_f32(atom, Role::App, 1, 0.61).unwrap();
  293. prop.set_f32(atom, Role::App, 2, 1.).unwrap();
  294. prop.set_f32(atom, Role::App, 3, 1.).unwrap();
  295. } else {
  296. // Normal channel activity
  297. prop.set_f32(atom, Role::App, 0, 0.36).unwrap();
  298. prop.set_f32(atom, Role::App, 1, 1.).unwrap();
  299. prop.set_f32(atom, Role::App, 2, 0.51).unwrap();
  300. prop.set_f32(atom, Role::App, 3, 1.).unwrap();
  301. }
  302. }
  303. });
  304. let (slot, recvr) = Slot::new("connect");
  305. darkirc.register("connect", slot).unwrap();
  306. let sg_root2 = sg_root.clone();
  307. let listen_connect = ex.spawn(async move {
  308. cv.wait().await;
  309. let net0 = sg_root2.lookup_node("/window/netstatus_layer/net0").unwrap();
  310. let net1 = sg_root2.lookup_node("/window/netstatus_layer/net1").unwrap();
  311. let net2 = sg_root2.lookup_node("/window/netstatus_layer/net2").unwrap();
  312. let net3 = sg_root2.lookup_node("/window/netstatus_layer/net3").unwrap();
  313. let net0_is_visible = PropertyBool::wrap(&net0, Role::App, "is_visible", 0).unwrap();
  314. let net1_is_visible = PropertyBool::wrap(&net1, Role::App, "is_visible", 0).unwrap();
  315. let net2_is_visible = PropertyBool::wrap(&net2, Role::App, "is_visible", 0).unwrap();
  316. let net3_is_visible = PropertyBool::wrap(&net3, Role::App, "is_visible", 0).unwrap();
  317. while let Ok(data) = recvr.recv().await {
  318. let (peers_count, is_dag_synced): (u32, bool) = deserialize(&data).unwrap();
  319. let atom = &mut render_api.make_guard(gfxtag!("netstatus change"));
  320. if peers_count == 0 {
  321. net0_is_visible.set(atom, true);
  322. net1_is_visible.set(atom, false);
  323. net2_is_visible.set(atom, false);
  324. net3_is_visible.set(atom, false);
  325. continue
  326. }
  327. assert!(peers_count > 0);
  328. if !is_dag_synced {
  329. net0_is_visible.set(atom, false);
  330. net1_is_visible.set(atom, true);
  331. net2_is_visible.set(atom, false);
  332. net3_is_visible.set(atom, false);
  333. continue
  334. }
  335. assert!(peers_count > 0 && is_dag_synced);
  336. if peers_count == 1 {
  337. net0_is_visible.set(atom, false);
  338. net1_is_visible.set(atom, false);
  339. net2_is_visible.set(atom, true);
  340. net3_is_visible.set(atom, false);
  341. continue
  342. }
  343. net0_is_visible.set(atom, false);
  344. net1_is_visible.set(atom, false);
  345. net2_is_visible.set(atom, false);
  346. net3_is_visible.set(atom, true);
  347. }
  348. });
  349. plugin.link(darkirc);
  350. plugin.link(fud);
  351. i!("Plugins loaded");
  352. futures::join!(listen_recv, listen_connect);
  353. }
  354. pub fn create_darkirc(name: &str) -> SceneNode {
  355. t!("create_darkirc({name})");
  356. let mut node = SceneNode::new(name, SceneNodeType::Plugin);
  357. let mut prop = Property::new("nick", PropertyType::Str, PropertySubType::Null);
  358. prop.set_ui_text("Nick", "Nickname");
  359. prop.set_defaults_str(vec!["anon".to_string()]).unwrap();
  360. node.add_property(prop).unwrap();
  361. node.add_signal(
  362. "recv",
  363. "Message received",
  364. vec![
  365. ("channel", "Channel", CallArgType::Str),
  366. ("timestamp", "Timestamp", CallArgType::Uint64),
  367. ("id", "ID", CallArgType::Hash),
  368. ("nick", "Nick", CallArgType::Str),
  369. ("msg", "Message", CallArgType::Str),
  370. ],
  371. )
  372. .unwrap();
  373. node.add_signal(
  374. "connect",
  375. "Connections and disconnects",
  376. vec![
  377. ("peers_count", "Peers Count", CallArgType::Uint32),
  378. ("dag_synced", "Is DAG Synced", CallArgType::Bool),
  379. ],
  380. )
  381. .unwrap();
  382. node.add_method(
  383. "send",
  384. vec![("channel", "Channel", CallArgType::Str), ("msg", "Message", CallArgType::Str)],
  385. None,
  386. )
  387. .unwrap();
  388. node
  389. }
  390. pub fn create_fud(name: &str) -> SceneNode {
  391. t!("create_fud({name})");
  392. let mut node = SceneNode::new(name, SceneNodeType::Plugin);
  393. let mut prop = Property::new("ready", PropertyType::Bool, PropertySubType::Null);
  394. prop.set_defaults_bool(vec![false]).unwrap();
  395. node.add_property(prop).unwrap();
  396. node.add_method("get", vec![("hash", "Hash", CallArgType::Str)], None).unwrap();
  397. node
  398. }
  399. /// Simple program to greet a person
  400. #[derive(Parser, Debug)]
  401. #[command(version, about, long_about = None)]
  402. struct Args {
  403. /// On Linux use the X11 backend
  404. #[arg(long)]
  405. linux_x11_backend: bool,
  406. /// On Linux use the wayland backend
  407. #[arg(long)]
  408. linux_wayland_backend: bool,
  409. }
  410. fn main() {
  411. let args = Args::parse();
  412. GOD.get_or_init(God::new);
  413. // Reuse render_api, event_pub and text_shaper
  414. // No need for setup(), just wait for gfx start then call .start()
  415. // ZMQ, darkirc stay running
  416. let linux_backend = if args.linux_wayland_backend {
  417. if args.linux_x11_backend {
  418. miniquad::conf::LinuxBackend::WaylandWithX11Fallback
  419. } else {
  420. miniquad::conf::LinuxBackend::WaylandOnly
  421. }
  422. } else if args.linux_x11_backend {
  423. miniquad::conf::LinuxBackend::X11Only
  424. } else {
  425. miniquad::conf::LinuxBackend::WaylandWithX11Fallback
  426. };
  427. gfx::run_gui(linux_backend);
  428. debug!(target: "main", "Started GFX backend");
  429. }
  430. /*
  431. use rustpython_vm::{self as pyvm, convert::ToPyObject};
  432. fn main() {
  433. let module = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  434. let source = r#"
  435. def foo():
  436. open("hihi", "w")
  437. return 110
  438. #max(1 + lw/3, 4*10) + foo(2, True)
  439. "#;
  440. //let code_obj = vm
  441. // .compile(source, pyvm::compiler::Mode::Exec, "<embedded>".to_owned())
  442. // .map_err(|err| vm.new_syntax_error(&err, Some(source))).unwrap();
  443. //code_obj
  444. pyvm::import::import_source(vm, "lain", source).unwrap()
  445. });
  446. fn foo(x: u32, y: bool) -> u32 {
  447. if y {
  448. 2 * x
  449. } else {
  450. x
  451. }
  452. }
  453. let res = pyvm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
  454. let globals = vm.ctx.new_dict();
  455. globals.set_item("lw", vm.ctx.new_int(110).to_pyobject(vm), vm).unwrap();
  456. globals.set_item("lh", vm.ctx.new_int(4).to_pyobject(vm), vm).unwrap();
  457. globals.set_item("foo", vm.new_function("foo", foo).into(), vm).unwrap();
  458. let scope = pyvm::scope::Scope::new(None, globals);
  459. let foo_fn = module.get_attr("foo", vm).unwrap();
  460. foo_fn.call((), vm).unwrap()
  461. //vm.run_code_obj(code_obj, scope).unwrap()
  462. });
  463. println!("{:?}", res);
  464. }
  465. */