lib.rs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // Copyright 2019-2023 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(desktop)]
  10. mod tray;
  11. use serde::Serialize;
  12. use tauri::{window::WindowBuilder, App, AppHandle, RunEvent, WindowUrl};
  13. use tauri_plugin_sample::{PingRequest, SampleExt};
  14. #[derive(Clone, Serialize)]
  15. struct Reply {
  16. data: String,
  17. }
  18. pub type SetupHook = Box<dyn FnOnce(&mut App) -> Result<(), Box<dyn std::error::Error>> + Send>;
  19. pub type OnEvent = Box<dyn FnMut(&AppHandle, RunEvent)>;
  20. #[cfg_attr(mobile, tauri::mobile_entry_point)]
  21. pub fn run() {
  22. #[allow(unused_mut)]
  23. let mut builder = tauri::Builder::default()
  24. .plugin(
  25. tauri_plugin_log::Builder::default()
  26. .level(log::LevelFilter::Info)
  27. .build(),
  28. )
  29. .plugin(tauri_plugin_sample::init())
  30. .setup(move |app| {
  31. #[cfg(desktop)]
  32. {
  33. tray::create_tray(app)?;
  34. app.handle().plugin(tauri_plugin_cli::init())?;
  35. }
  36. let mut window_builder = WindowBuilder::new(app, "main", WindowUrl::default());
  37. #[cfg(desktop)]
  38. {
  39. window_builder = window_builder
  40. .user_agent("Tauri API")
  41. .title("Tauri API Validation")
  42. .inner_size(1000., 800.)
  43. .min_inner_size(600., 400.)
  44. .content_protected(true);
  45. }
  46. #[cfg(target_os = "windows")]
  47. {
  48. window_builder = window_builder.transparent(true).decorations(false);
  49. }
  50. let window = window_builder.build().unwrap();
  51. #[cfg(debug_assertions)]
  52. window.open_devtools();
  53. let value = Some("test".to_string());
  54. let response = app.sample().ping(PingRequest {
  55. value: value.clone(),
  56. });
  57. log::info!("got response: {:?}", response);
  58. if let Ok(res) = response {
  59. assert_eq!(res.value, value);
  60. }
  61. #[cfg(desktop)]
  62. std::thread::spawn(|| {
  63. let server = match tiny_http::Server::http("localhost:3003") {
  64. Ok(s) => s,
  65. Err(e) => {
  66. eprintln!("{}", e);
  67. std::process::exit(1);
  68. }
  69. };
  70. loop {
  71. if let Ok(mut request) = server.recv() {
  72. let mut body = Vec::new();
  73. let _ = request.as_reader().read_to_end(&mut body);
  74. let response = tiny_http::Response::new(
  75. tiny_http::StatusCode(200),
  76. request.headers().to_vec(),
  77. std::io::Cursor::new(body),
  78. request.body_length(),
  79. None,
  80. );
  81. let _ = request.respond(response);
  82. }
  83. }
  84. });
  85. Ok(())
  86. })
  87. .on_page_load(|window, _| {
  88. let window_ = window.clone();
  89. window.listen("js-event", move |event| {
  90. println!("got js-event with message '{:?}'", event.payload());
  91. let reply = Reply {
  92. data: "something else".to_string(),
  93. };
  94. window_
  95. .emit("rust-event", Some(reply))
  96. .expect("failed to emit");
  97. });
  98. });
  99. #[cfg(target_os = "macos")]
  100. {
  101. builder = builder.menu(tauri::Menu::os_default("Tauri API Validation"));
  102. }
  103. #[allow(unused_mut)]
  104. let mut app = builder
  105. .invoke_handler(tauri::generate_handler![
  106. cmd::log_operation,
  107. cmd::perform_request,
  108. ])
  109. .build(tauri::tauri_build_context!())
  110. .expect("error while building tauri application");
  111. #[cfg(target_os = "macos")]
  112. app.set_activation_policy(tauri::ActivationPolicy::Regular);
  113. app.run(move |_app_handle, _event| {
  114. #[cfg(desktop)]
  115. if let RunEvent::ExitRequested { api, .. } = &_event {
  116. // Keep the event loop running even if all windows are closed
  117. // This allow us to catch system tray events when there is no window
  118. api.prevent_exit();
  119. }
  120. })
  121. }