main.rs 17 KB

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