lib.rs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. #![cfg_attr(
  5. all(not(debug_assertions), target_os = "windows"),
  6. windows_subsystem = "windows"
  7. )]
  8. mod cmd;
  9. #[cfg(mobile)]
  10. mod mobile;
  11. #[cfg(mobile)]
  12. pub use mobile::*;
  13. use serde::Serialize;
  14. use tauri::{window::WindowBuilder, App, AppHandle, RunEvent, WindowUrl};
  15. #[derive(Clone, Serialize)]
  16. struct Reply {
  17. data: String,
  18. }
  19. pub type SetupHook = Box<dyn FnOnce(&mut App) -> Result<(), Box<dyn std::error::Error>> + Send>;
  20. pub type OnEvent = Box<dyn FnMut(&AppHandle, RunEvent)>;
  21. #[derive(Default)]
  22. pub struct AppBuilder {
  23. setup: Option<SetupHook>,
  24. on_event: Option<OnEvent>,
  25. }
  26. impl AppBuilder {
  27. pub fn new() -> Self {
  28. Self::default()
  29. }
  30. #[must_use]
  31. pub fn setup<F>(mut self, setup: F) -> Self
  32. where
  33. F: FnOnce(&mut App) -> Result<(), Box<dyn std::error::Error>> + Send + 'static,
  34. {
  35. self.setup.replace(Box::new(setup));
  36. self
  37. }
  38. #[must_use]
  39. pub fn on_event<F>(mut self, on_event: F) -> Self
  40. where
  41. F: Fn(&AppHandle, RunEvent) + 'static,
  42. {
  43. self.on_event.replace(Box::new(on_event));
  44. self
  45. }
  46. pub fn run(self) {
  47. let setup = self.setup;
  48. let mut on_event = self.on_event;
  49. #[allow(unused_mut)]
  50. let mut builder = tauri::Builder::default()
  51. .setup(move |app| {
  52. if let Some(setup) = setup {
  53. (setup)(app)?;
  54. }
  55. let mut window_builder = WindowBuilder::new(app, "main", WindowUrl::default());
  56. #[cfg(desktop)]
  57. {
  58. window_builder = window_builder
  59. .user_agent("Tauri API")
  60. .title("Tauri API Validation")
  61. .inner_size(1000., 800.)
  62. .min_inner_size(600., 400.);
  63. }
  64. #[cfg(target_os = "windows")]
  65. {
  66. window_builder = window_builder.transparent(true);
  67. window_builder = window_builder.decorations(false);
  68. }
  69. let window = window_builder.build().unwrap();
  70. #[cfg(target_os = "windows")]
  71. {
  72. let _ = window_shadows::set_shadow(&window, true);
  73. let _ = window_vibrancy::apply_blur(&window, Some((0, 0, 0, 0)));
  74. }
  75. #[cfg(debug_assertions)]
  76. window.open_devtools();
  77. std::thread::spawn(|| {
  78. let server = match tiny_http::Server::http("localhost:3003") {
  79. Ok(s) => s,
  80. Err(e) => {
  81. eprintln!("{}", e);
  82. std::process::exit(1);
  83. }
  84. };
  85. loop {
  86. if let Ok(mut request) = server.recv() {
  87. let mut body = Vec::new();
  88. let _ = request.as_reader().read_to_end(&mut body);
  89. let response = tiny_http::Response::new(
  90. tiny_http::StatusCode(200),
  91. request.headers().to_vec(),
  92. std::io::Cursor::new(body),
  93. request.body_length(),
  94. None,
  95. );
  96. let _ = request.respond(response);
  97. }
  98. }
  99. });
  100. Ok(())
  101. })
  102. .on_page_load(|window, _| {
  103. let window_ = window.clone();
  104. window.listen("js-event", move |event| {
  105. println!("got js-event with message '{:?}'", event.payload());
  106. let reply = Reply {
  107. data: "something else".to_string(),
  108. };
  109. window_
  110. .emit("rust-event", Some(reply))
  111. .expect("failed to emit");
  112. });
  113. });
  114. #[cfg(target_os = "macos")]
  115. {
  116. builder = builder.menu(tauri::Menu::os_default("Tauri API Validation"));
  117. }
  118. #[allow(unused_mut)]
  119. let mut app = builder
  120. .invoke_handler(tauri::generate_handler![
  121. cmd::log_operation,
  122. cmd::perform_request,
  123. ])
  124. .build(tauri::tauri_build_context!())
  125. .expect("error while building tauri application");
  126. #[cfg(target_os = "macos")]
  127. app.set_activation_policy(tauri::ActivationPolicy::Regular);
  128. #[allow(unused_variables)]
  129. app.run(move |app_handle, e| {
  130. if let RunEvent::ExitRequested { api, .. } = &e {
  131. // Keep the event loop running even if all windows are closed
  132. // This allow us to catch system tray events when there is no window
  133. api.prevent_exit();
  134. }
  135. if let Some(on_event) = &mut on_event {
  136. (on_event)(app_handle, e);
  137. }
  138. })
  139. }
  140. }