main.rs 18 KB

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