mod.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use std::{
  5. borrow::Cow,
  6. collections::HashMap,
  7. fmt,
  8. sync::{Arc, Mutex, MutexGuard},
  9. };
  10. use serde::Serialize;
  11. use url::Url;
  12. use tauri_macros::default_runtime;
  13. use tauri_utils::debug_eprintln;
  14. use tauri_utils::{
  15. assets::{AssetKey, CspHash},
  16. config::{Csp, CspDirectiveSources},
  17. html::{SCRIPT_NONCE_TOKEN, STYLE_NONCE_TOKEN},
  18. };
  19. use crate::{
  20. app::{AppHandle, GlobalWebviewEventListener, GlobalWindowEventListener, OnPageLoad},
  21. event::{assert_event_name_is_valid, Event, EventId, EventTarget, Listeners},
  22. ipc::{Invoke, InvokeHandler, InvokeResponder, RuntimeAuthority},
  23. plugin::PluginStore,
  24. utils::{assets::Assets, config::Config, PackageInfo},
  25. Context, Pattern, Runtime, StateManager, Window,
  26. };
  27. use crate::{event::EmitArgs, resources::ResourceTable, Webview};
  28. #[cfg(desktop)]
  29. mod menu;
  30. #[cfg(all(desktop, feature = "tray-icon"))]
  31. mod tray;
  32. pub mod webview;
  33. pub mod window;
  34. #[derive(Default)]
  35. /// Spaced and quoted Content-Security-Policy hash values.
  36. struct CspHashStrings {
  37. script: Vec<String>,
  38. style: Vec<String>,
  39. }
  40. /// Sets the CSP value to the asset HTML if needed (on Linux).
  41. /// Returns the CSP string for access on the response header (on Windows and macOS).
  42. #[allow(clippy::borrowed_box)]
  43. fn set_csp<R: Runtime>(
  44. asset: &mut String,
  45. assets: &Box<dyn Assets>,
  46. asset_path: &AssetKey,
  47. manager: &AppManager<R>,
  48. csp: Csp,
  49. ) -> String {
  50. let mut csp = csp.into();
  51. let hash_strings =
  52. assets
  53. .csp_hashes(asset_path)
  54. .fold(CspHashStrings::default(), |mut acc, hash| {
  55. match hash {
  56. CspHash::Script(hash) => {
  57. acc.script.push(hash.into());
  58. }
  59. CspHash::Style(hash) => {
  60. acc.style.push(hash.into());
  61. }
  62. _csp_hash => {
  63. debug_eprintln!("Unknown CspHash variant encountered: {:?}", _csp_hash);
  64. }
  65. }
  66. acc
  67. });
  68. let dangerous_disable_asset_csp_modification = &manager
  69. .config()
  70. .app
  71. .security
  72. .dangerous_disable_asset_csp_modification;
  73. if dangerous_disable_asset_csp_modification.can_modify("script-src") {
  74. replace_csp_nonce(
  75. asset,
  76. SCRIPT_NONCE_TOKEN,
  77. &mut csp,
  78. "script-src",
  79. hash_strings.script,
  80. );
  81. }
  82. if dangerous_disable_asset_csp_modification.can_modify("style-src") {
  83. replace_csp_nonce(
  84. asset,
  85. STYLE_NONCE_TOKEN,
  86. &mut csp,
  87. "style-src",
  88. hash_strings.style,
  89. );
  90. }
  91. #[cfg(feature = "isolation")]
  92. if let Pattern::Isolation { schema, .. } = &*manager.pattern {
  93. let default_src = csp
  94. .entry("default-src".into())
  95. .or_insert_with(Default::default);
  96. default_src.push(crate::pattern::format_real_schema(schema));
  97. }
  98. Csp::DirectiveMap(csp).to_string()
  99. }
  100. // inspired by https://github.com/rust-lang/rust/blob/1be5c8f90912c446ecbdc405cbc4a89f9acd20fd/library/alloc/src/str.rs#L260-L297
  101. fn replace_with_callback<F: FnMut() -> String>(
  102. original: &str,
  103. pattern: &str,
  104. mut replacement: F,
  105. ) -> String {
  106. let mut result = String::new();
  107. let mut last_end = 0;
  108. for (start, part) in original.match_indices(pattern) {
  109. result.push_str(unsafe { original.get_unchecked(last_end..start) });
  110. result.push_str(&replacement());
  111. last_end = start + part.len();
  112. }
  113. result.push_str(unsafe { original.get_unchecked(last_end..original.len()) });
  114. result
  115. }
  116. fn replace_csp_nonce(
  117. asset: &mut String,
  118. token: &str,
  119. csp: &mut HashMap<String, CspDirectiveSources>,
  120. directive: &str,
  121. hashes: Vec<String>,
  122. ) {
  123. let mut nonces = Vec::new();
  124. *asset = replace_with_callback(asset, token, || {
  125. #[cfg(target_pointer_width = "64")]
  126. let mut raw = [0u8; 8];
  127. #[cfg(target_pointer_width = "32")]
  128. let mut raw = [0u8; 4];
  129. #[cfg(target_pointer_width = "16")]
  130. let mut raw = [0u8; 2];
  131. getrandom::getrandom(&mut raw).expect("failed to get random bytes");
  132. let nonce = usize::from_ne_bytes(raw);
  133. nonces.push(nonce);
  134. nonce.to_string()
  135. });
  136. if !(nonces.is_empty() && hashes.is_empty()) {
  137. let nonce_sources = nonces
  138. .into_iter()
  139. .map(|n| format!("'nonce-{n}'"))
  140. .collect::<Vec<String>>();
  141. let sources = csp.entry(directive.into()).or_default();
  142. let self_source = "'self'".to_string();
  143. if !sources.contains(&self_source) {
  144. sources.push(self_source);
  145. }
  146. sources.extend(nonce_sources);
  147. sources.extend(hashes);
  148. }
  149. }
  150. /// A resolved asset.
  151. pub struct Asset {
  152. /// The asset bytes.
  153. pub bytes: Vec<u8>,
  154. /// The asset's mime type.
  155. pub mime_type: String,
  156. /// The `Content-Security-Policy` header value.
  157. pub csp_header: Option<String>,
  158. }
  159. #[default_runtime(crate::Wry, wry)]
  160. pub struct AppManager<R: Runtime> {
  161. pub runtime_authority: RuntimeAuthority,
  162. pub window: window::WindowManager<R>,
  163. pub webview: webview::WebviewManager<R>,
  164. #[cfg(all(desktop, feature = "tray-icon"))]
  165. pub tray: tray::TrayManager<R>,
  166. #[cfg(desktop)]
  167. pub menu: menu::MenuManager<R>,
  168. pub(crate) plugins: Mutex<PluginStore<R>>,
  169. pub listeners: Listeners,
  170. pub state: Arc<StateManager>,
  171. pub config: Config,
  172. pub assets: Box<dyn Assets>,
  173. pub app_icon: Option<Vec<u8>>,
  174. pub package_info: PackageInfo,
  175. /// Application pattern.
  176. pub pattern: Arc<Pattern>,
  177. /// Application Resources Table
  178. pub(crate) resources_table: Arc<Mutex<ResourceTable>>,
  179. }
  180. impl<R: Runtime> fmt::Debug for AppManager<R> {
  181. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  182. let mut d = f.debug_struct("AppManager");
  183. d.field("window", &self.window)
  184. .field("plugins", &self.plugins)
  185. .field("state", &self.state)
  186. .field("config", &self.config)
  187. .field("app_icon", &self.app_icon)
  188. .field("package_info", &self.package_info)
  189. .field("pattern", &self.pattern);
  190. #[cfg(all(desktop, feature = "tray-icon"))]
  191. {
  192. d.field("tray", &self.tray);
  193. }
  194. d.finish()
  195. }
  196. }
  197. impl<R: Runtime> AppManager<R> {
  198. #[allow(clippy::too_many_arguments, clippy::type_complexity)]
  199. pub(crate) fn with_handlers(
  200. #[allow(unused_mut)] mut context: Context<impl Assets>,
  201. plugins: PluginStore<R>,
  202. invoke_handler: Box<InvokeHandler<R>>,
  203. on_page_load: Option<Arc<OnPageLoad<R>>>,
  204. uri_scheme_protocols: HashMap<String, Arc<webview::UriSchemeProtocol<R>>>,
  205. state: StateManager,
  206. window_event_listeners: Vec<GlobalWindowEventListener<R>>,
  207. webiew_event_listeners: Vec<GlobalWebviewEventListener<R>>,
  208. #[cfg(desktop)] window_menu_event_listeners: HashMap<
  209. String,
  210. crate::app::GlobalMenuEventListener<Window<R>>,
  211. >,
  212. (invoke_responder, invoke_initialization_script): (Option<Arc<InvokeResponder<R>>>, String),
  213. ) -> Self {
  214. // generate a random isolation key at runtime
  215. #[cfg(feature = "isolation")]
  216. if let Pattern::Isolation { ref mut key, .. } = &mut context.pattern {
  217. *key = uuid::Uuid::new_v4().to_string();
  218. }
  219. Self {
  220. runtime_authority: RuntimeAuthority::new(context.resolved_acl),
  221. window: window::WindowManager {
  222. windows: Mutex::default(),
  223. default_icon: context.default_window_icon,
  224. event_listeners: Arc::new(window_event_listeners),
  225. },
  226. webview: webview::WebviewManager {
  227. webviews: Mutex::default(),
  228. invoke_handler,
  229. on_page_load,
  230. uri_scheme_protocols: Mutex::new(uri_scheme_protocols),
  231. event_listeners: Arc::new(webiew_event_listeners),
  232. invoke_responder,
  233. invoke_initialization_script,
  234. },
  235. #[cfg(all(desktop, feature = "tray-icon"))]
  236. tray: tray::TrayManager {
  237. icon: context.tray_icon,
  238. icons: Default::default(),
  239. global_event_listeners: Default::default(),
  240. event_listeners: Default::default(),
  241. },
  242. #[cfg(desktop)]
  243. menu: menu::MenuManager {
  244. menus: Default::default(),
  245. menu: Default::default(),
  246. global_event_listeners: Default::default(),
  247. event_listeners: Mutex::new(window_menu_event_listeners),
  248. },
  249. plugins: Mutex::new(plugins),
  250. listeners: Listeners::default(),
  251. state: Arc::new(state),
  252. config: context.config,
  253. assets: context.assets,
  254. app_icon: context.app_icon,
  255. package_info: context.package_info,
  256. pattern: Arc::new(context.pattern),
  257. resources_table: Arc::default(),
  258. }
  259. }
  260. /// State managed by the application.
  261. pub(crate) fn state(&self) -> Arc<StateManager> {
  262. self.state.clone()
  263. }
  264. /// Get the base path to serve data from.
  265. ///
  266. /// * In dev mode, this will be based on the `devUrl` configuration value.
  267. /// * Otherwise, this will be based on the `frontendDist` configuration value.
  268. #[cfg(not(dev))]
  269. fn base_path(&self) -> Option<&Url> {
  270. use crate::utils::config::FrontendDist;
  271. match self.config.build.frontend_dist.as_ref() {
  272. Some(FrontendDist::Url(url)) => Some(url),
  273. _ => None,
  274. }
  275. }
  276. #[cfg(dev)]
  277. fn base_path(&self) -> Option<&Url> {
  278. self.config.build.dev_url.as_ref()
  279. }
  280. pub(crate) fn protocol_url(&self) -> Cow<'_, Url> {
  281. if cfg!(windows) || cfg!(target_os = "android") {
  282. Cow::Owned(Url::parse("http://tauri.localhost").unwrap())
  283. } else {
  284. Cow::Owned(Url::parse("tauri://localhost").unwrap())
  285. }
  286. }
  287. /// Get the base URL to use for webview requests.
  288. ///
  289. /// In dev mode, this will be based on the `devUrl` configuration value.
  290. pub(crate) fn get_url(&self) -> Cow<'_, Url> {
  291. match self.base_path() {
  292. Some(url) => Cow::Borrowed(url),
  293. _ => self.protocol_url(),
  294. }
  295. }
  296. fn csp(&self) -> Option<Csp> {
  297. if cfg!(feature = "custom-protocol") {
  298. self.config.app.security.csp.clone()
  299. } else {
  300. self
  301. .config
  302. .app
  303. .security
  304. .dev_csp
  305. .clone()
  306. .or_else(|| self.config.app.security.csp.clone())
  307. }
  308. }
  309. pub fn get_asset(&self, mut path: String) -> Result<Asset, Box<dyn std::error::Error>> {
  310. let assets = &self.assets;
  311. if path.ends_with('/') {
  312. path.pop();
  313. }
  314. path = percent_encoding::percent_decode(path.as_bytes())
  315. .decode_utf8_lossy()
  316. .to_string();
  317. let path = if path.is_empty() {
  318. // if the url is `tauri://localhost`, we should load `index.html`
  319. "index.html".to_string()
  320. } else {
  321. // skip leading `/`
  322. path.chars().skip(1).collect::<String>()
  323. };
  324. let mut asset_path = AssetKey::from(path.as_str());
  325. let asset_response = assets
  326. .get(&path.as_str().into())
  327. .or_else(|| {
  328. debug_eprintln!("Asset `{path}` not found; fallback to {path}.html");
  329. let fallback = format!("{}.html", path.as_str()).into();
  330. let asset = assets.get(&fallback);
  331. asset_path = fallback;
  332. asset
  333. })
  334. .or_else(|| {
  335. debug_eprintln!(
  336. "Asset `{}` not found; fallback to {}/index.html",
  337. path,
  338. path
  339. );
  340. let fallback = format!("{}/index.html", path.as_str()).into();
  341. let asset = assets.get(&fallback);
  342. asset_path = fallback;
  343. asset
  344. })
  345. .or_else(|| {
  346. debug_eprintln!("Asset `{}` not found; fallback to index.html", path);
  347. let fallback = AssetKey::from("index.html");
  348. let asset = assets.get(&fallback);
  349. asset_path = fallback;
  350. asset
  351. })
  352. .ok_or_else(|| crate::Error::AssetNotFound(path.clone()))
  353. .map(Cow::into_owned);
  354. let mut csp_header = None;
  355. let is_html = asset_path.as_ref().ends_with(".html");
  356. match asset_response {
  357. Ok(asset) => {
  358. let final_data = if is_html {
  359. let mut asset = String::from_utf8_lossy(&asset).into_owned();
  360. if let Some(csp) = self.csp() {
  361. csp_header.replace(set_csp(&mut asset, &self.assets, &asset_path, self, csp));
  362. }
  363. asset.as_bytes().to_vec()
  364. } else {
  365. asset
  366. };
  367. let mime_type = tauri_utils::mime_type::MimeType::parse(&final_data, &path);
  368. Ok(Asset {
  369. bytes: final_data.to_vec(),
  370. mime_type,
  371. csp_header,
  372. })
  373. }
  374. Err(e) => {
  375. debug_eprintln!("{:?}", e); // TODO log::error!
  376. Err(Box::new(e))
  377. }
  378. }
  379. }
  380. pub(crate) fn listeners(&self) -> &Listeners {
  381. &self.listeners
  382. }
  383. pub fn run_invoke_handler(&self, invoke: Invoke<R>) -> bool {
  384. (self.webview.invoke_handler)(invoke)
  385. }
  386. pub fn extend_api(&self, plugin: &str, invoke: Invoke<R>) -> bool {
  387. self
  388. .plugins
  389. .lock()
  390. .expect("poisoned plugin store")
  391. .extend_api(plugin, invoke)
  392. }
  393. pub fn initialize_plugins(&self, app: &AppHandle<R>) -> crate::Result<()> {
  394. self
  395. .plugins
  396. .lock()
  397. .expect("poisoned plugin store")
  398. .initialize_all(app, &self.config.plugins)
  399. }
  400. pub fn config(&self) -> &Config {
  401. &self.config
  402. }
  403. pub fn package_info(&self) -> &PackageInfo {
  404. &self.package_info
  405. }
  406. pub fn listen<F: Fn(Event) + Send + 'static>(
  407. &self,
  408. event: String,
  409. target: EventTarget,
  410. handler: F,
  411. ) -> EventId {
  412. assert_event_name_is_valid(&event);
  413. self.listeners().listen(event, target, handler)
  414. }
  415. pub fn unlisten(&self, id: EventId) {
  416. self.listeners().unlisten(id)
  417. }
  418. pub fn once<F: FnOnce(Event) + Send + 'static>(
  419. &self,
  420. event: String,
  421. target: EventTarget,
  422. handler: F,
  423. ) {
  424. assert_event_name_is_valid(&event);
  425. self.listeners().once(event, target, handler)
  426. }
  427. pub fn emit_filter<S, F>(&self, event: &str, payload: S, filter: F) -> crate::Result<()>
  428. where
  429. S: Serialize + Clone,
  430. F: Fn(&EventTarget) -> bool,
  431. {
  432. assert_event_name_is_valid(event);
  433. #[cfg(feature = "tracing")]
  434. let _span = tracing::debug_span!("emit::run").entered();
  435. let emit_args = EmitArgs::new(event, payload)?;
  436. let listeners = self.listeners();
  437. listeners.emit_js_filter(
  438. self.webview.webviews_lock().values(),
  439. event,
  440. &emit_args,
  441. Some(&filter),
  442. )?;
  443. listeners.emit_filter(emit_args, Some(filter))?;
  444. Ok(())
  445. }
  446. pub fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> crate::Result<()> {
  447. assert_event_name_is_valid(event);
  448. #[cfg(feature = "tracing")]
  449. let _span = tracing::debug_span!("emit::run").entered();
  450. let emit_args = EmitArgs::new(event, payload)?;
  451. let listeners = self.listeners();
  452. listeners.emit_js(self.webview.webviews_lock().values(), event, &emit_args)?;
  453. listeners.emit(emit_args)?;
  454. Ok(())
  455. }
  456. pub fn get_window(&self, label: &str) -> Option<Window<R>> {
  457. self.window.windows_lock().get(label).cloned()
  458. }
  459. pub fn get_focused_window(&self) -> Option<Window<R>> {
  460. self
  461. .window
  462. .windows_lock()
  463. .iter()
  464. .find(|w| w.1.is_focused().unwrap_or(false))
  465. .map(|w| w.1.clone())
  466. }
  467. pub(crate) fn on_window_close(&self, label: &str) {
  468. if let Some(window) = self.window.windows_lock().remove(label) {
  469. for webview in window.webviews() {
  470. self.webview.webviews_lock().remove(webview.label());
  471. }
  472. }
  473. }
  474. pub(crate) fn on_webview_close(&self, label: &str) {
  475. self.webview.webviews_lock().remove(label);
  476. }
  477. pub fn windows(&self) -> HashMap<String, Window<R>> {
  478. self.window.windows_lock().clone()
  479. }
  480. pub fn get_webview(&self, label: &str) -> Option<Webview<R>> {
  481. self.webview.webviews_lock().get(label).cloned()
  482. }
  483. pub fn webviews(&self) -> HashMap<String, Webview<R>> {
  484. self.webview.webviews_lock().clone()
  485. }
  486. /// Resources table managed by the application.
  487. pub(crate) fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
  488. self
  489. .resources_table
  490. .lock()
  491. .expect("poisoned window manager")
  492. }
  493. }
  494. #[cfg(desktop)]
  495. impl<R: Runtime> AppManager<R> {
  496. pub fn remove_menu_from_stash_by_id(&self, id: Option<&crate::menu::MenuId>) {
  497. if let Some(id) = id {
  498. let is_used_by_a_window = self
  499. .window
  500. .windows_lock()
  501. .values()
  502. .any(|w| w.is_menu_in_use(id));
  503. if !(self.menu.is_menu_in_use(id) || is_used_by_a_window) {
  504. self.menu.menus_stash_lock().remove(id);
  505. }
  506. }
  507. }
  508. }
  509. #[cfg(test)]
  510. mod tests {
  511. use super::replace_with_callback;
  512. #[test]
  513. fn string_replace_with_callback() {
  514. let mut tauri_index = 0;
  515. #[allow(clippy::single_element_loop)]
  516. for (src, pattern, replacement, result) in [(
  517. "tauri is awesome, tauri is amazing",
  518. "tauri",
  519. || {
  520. tauri_index += 1;
  521. tauri_index.to_string()
  522. },
  523. "1 is awesome, 2 is amazing",
  524. )] {
  525. assert_eq!(replace_with_callback(src, pattern, replacement), result);
  526. }
  527. }
  528. }
  529. #[cfg(test)]
  530. mod test {
  531. use std::{
  532. sync::mpsc::{channel, Receiver, Sender},
  533. time::Duration,
  534. };
  535. use crate::{
  536. event::EventTarget,
  537. generate_context,
  538. plugin::PluginStore,
  539. test::{mock_app, MockRuntime},
  540. webview::WebviewBuilder,
  541. window::WindowBuilder,
  542. App, Manager, StateManager, Webview, WebviewWindow, WebviewWindowBuilder, Window, Wry,
  543. };
  544. use super::AppManager;
  545. const APP_LISTEN_ID: &str = "App::listen";
  546. const APP_LISTEN_ANY_ID: &str = "App::listen_any";
  547. const WINDOW_LISTEN_ID: &str = "Window::listen";
  548. const WINDOW_LISTEN_ANY_ID: &str = "Window::listen_any";
  549. const WEBVIEW_LISTEN_ID: &str = "Webview::listen";
  550. const WEBVIEW_LISTEN_ANY_ID: &str = "Webview::listen_any";
  551. const WEBVIEW_WINDOW_LISTEN_ID: &str = "WebviewWindow::listen";
  552. const WEBVIEW_WINDOW_LISTEN_ANY_ID: &str = "WebviewWindow::listen_any";
  553. const TEST_EVENT_NAME: &str = "event";
  554. #[test]
  555. fn check_get_url() {
  556. let context = generate_context!("test/fixture/src-tauri/tauri.conf.json", crate);
  557. let manager: AppManager<Wry> = AppManager::with_handlers(
  558. context,
  559. PluginStore::default(),
  560. Box::new(|_| false),
  561. None,
  562. Default::default(),
  563. StateManager::new(),
  564. Default::default(),
  565. Default::default(),
  566. Default::default(),
  567. (None, "".into()),
  568. );
  569. #[cfg(custom_protocol)]
  570. {
  571. assert_eq!(
  572. manager.get_url().to_string(),
  573. if cfg!(windows) || cfg!(target_os = "android") {
  574. "http://tauri.localhost/"
  575. } else {
  576. "tauri://localhost"
  577. }
  578. );
  579. }
  580. #[cfg(dev)]
  581. assert_eq!(manager.get_url().to_string(), "http://localhost:4000/");
  582. }
  583. struct EventSetup {
  584. app: App<MockRuntime>,
  585. window: Window<MockRuntime>,
  586. webview: Webview<MockRuntime>,
  587. webview_window: WebviewWindow<MockRuntime>,
  588. tx: Sender<(&'static str, String)>,
  589. rx: Receiver<(&'static str, String)>,
  590. }
  591. fn setup_events(setup_any: bool) -> EventSetup {
  592. let app = mock_app();
  593. let window = WindowBuilder::new(&app, "main-window").build().unwrap();
  594. let webview = window
  595. .add_child(
  596. WebviewBuilder::new("main-webview", Default::default()),
  597. crate::LogicalPosition::new(0, 0),
  598. window.inner_size().unwrap(),
  599. )
  600. .unwrap();
  601. let webview_window = WebviewWindowBuilder::new(&app, "main-webview-window", Default::default())
  602. .build()
  603. .unwrap();
  604. let (tx, rx) = channel();
  605. macro_rules! setup_listener {
  606. ($type:ident, $id:ident, $any_id:ident) => {
  607. let tx_ = tx.clone();
  608. $type.listen(TEST_EVENT_NAME, move |evt| {
  609. tx_
  610. .send(($id, serde_json::from_str::<String>(evt.payload()).unwrap()))
  611. .unwrap();
  612. });
  613. if setup_any {
  614. let tx_ = tx.clone();
  615. $type.listen_any(TEST_EVENT_NAME, move |evt| {
  616. tx_
  617. .send((
  618. $any_id,
  619. serde_json::from_str::<String>(evt.payload()).unwrap(),
  620. ))
  621. .unwrap();
  622. });
  623. }
  624. };
  625. }
  626. setup_listener!(app, APP_LISTEN_ID, APP_LISTEN_ANY_ID);
  627. setup_listener!(window, WINDOW_LISTEN_ID, WINDOW_LISTEN_ANY_ID);
  628. setup_listener!(webview, WEBVIEW_LISTEN_ID, WEBVIEW_LISTEN_ANY_ID);
  629. setup_listener!(
  630. webview_window,
  631. WEBVIEW_WINDOW_LISTEN_ID,
  632. WEBVIEW_WINDOW_LISTEN_ANY_ID
  633. );
  634. EventSetup {
  635. app,
  636. window,
  637. webview,
  638. webview_window,
  639. tx,
  640. rx,
  641. }
  642. }
  643. fn assert_events(kind: &str, received: &[&str], expected: &[&str]) {
  644. for e in expected {
  645. assert!(received.contains(e), "{e} did not receive `{kind}` event");
  646. }
  647. assert_eq!(
  648. received.len(),
  649. expected.len(),
  650. "received {:?} `{kind}` events but expected {:?}",
  651. received,
  652. expected
  653. );
  654. }
  655. #[test]
  656. fn emit() {
  657. let EventSetup {
  658. app,
  659. window,
  660. webview,
  661. webview_window,
  662. tx: _,
  663. rx,
  664. } = setup_events(true);
  665. run_emit_test("emit (app)", app, &rx);
  666. run_emit_test("emit (window)", window, &rx);
  667. run_emit_test("emit (webview)", webview, &rx);
  668. run_emit_test("emit (webview_window)", webview_window, &rx);
  669. }
  670. fn run_emit_test<M: Manager<MockRuntime>>(kind: &str, m: M, rx: &Receiver<(&str, String)>) {
  671. let mut received = Vec::new();
  672. let payload = "global-payload";
  673. m.emit(TEST_EVENT_NAME, payload).unwrap();
  674. while let Ok((source, p)) = rx.recv_timeout(Duration::from_secs(1)) {
  675. assert_eq!(p, payload);
  676. received.push(source);
  677. }
  678. assert_events(
  679. kind,
  680. &received,
  681. &[
  682. APP_LISTEN_ID,
  683. APP_LISTEN_ANY_ID,
  684. WINDOW_LISTEN_ID,
  685. WINDOW_LISTEN_ANY_ID,
  686. WEBVIEW_LISTEN_ID,
  687. WEBVIEW_LISTEN_ANY_ID,
  688. WEBVIEW_WINDOW_LISTEN_ID,
  689. WEBVIEW_WINDOW_LISTEN_ANY_ID,
  690. ],
  691. );
  692. }
  693. #[test]
  694. fn emit_to() {
  695. let EventSetup {
  696. app,
  697. window,
  698. webview,
  699. webview_window,
  700. tx,
  701. rx,
  702. } = setup_events(false);
  703. run_emit_to_test(
  704. "emit_to (App)",
  705. &app,
  706. &window,
  707. &webview,
  708. &webview_window,
  709. tx.clone(),
  710. &rx,
  711. );
  712. run_emit_to_test(
  713. "emit_to (window)",
  714. &window,
  715. &window,
  716. &webview,
  717. &webview_window,
  718. tx.clone(),
  719. &rx,
  720. );
  721. run_emit_to_test(
  722. "emit_to (webview)",
  723. &webview,
  724. &window,
  725. &webview,
  726. &webview_window,
  727. tx.clone(),
  728. &rx,
  729. );
  730. run_emit_to_test(
  731. "emit_to (webview_window)",
  732. &webview_window,
  733. &window,
  734. &webview,
  735. &webview_window,
  736. tx.clone(),
  737. &rx,
  738. );
  739. }
  740. fn run_emit_to_test<M: Manager<MockRuntime>>(
  741. kind: &str,
  742. m: &M,
  743. window: &Window<MockRuntime>,
  744. webview: &Webview<MockRuntime>,
  745. webview_window: &WebviewWindow<MockRuntime>,
  746. tx: Sender<(&'static str, String)>,
  747. rx: &Receiver<(&'static str, String)>,
  748. ) {
  749. let mut received = Vec::new();
  750. let payload = "global-payload";
  751. macro_rules! test_target {
  752. ($target:expr, $id:ident) => {
  753. m.emit_to($target, TEST_EVENT_NAME, payload).unwrap();
  754. while let Ok((source, p)) = rx.recv_timeout(Duration::from_secs(1)) {
  755. assert_eq!(p, payload);
  756. received.push(source);
  757. }
  758. assert_events(kind, &received, &[$id]);
  759. received.clear();
  760. };
  761. }
  762. test_target!(EventTarget::App, APP_LISTEN_ID);
  763. test_target!(window.label(), WINDOW_LISTEN_ID);
  764. test_target!(webview.label(), WEBVIEW_LISTEN_ID);
  765. test_target!(webview_window.label(), WEBVIEW_WINDOW_LISTEN_ID);
  766. let other_webview_listen_id = "OtherWebview::listen";
  767. let other_webview = WebviewWindowBuilder::new(
  768. window,
  769. kind.replace(['(', ')', ' '], ""),
  770. Default::default(),
  771. )
  772. .build()
  773. .unwrap();
  774. other_webview.listen(TEST_EVENT_NAME, move |evt| {
  775. tx.send((
  776. other_webview_listen_id,
  777. serde_json::from_str::<String>(evt.payload()).unwrap(),
  778. ))
  779. .unwrap();
  780. });
  781. m.emit_to(other_webview.label(), TEST_EVENT_NAME, payload)
  782. .unwrap();
  783. while let Ok((source, p)) = rx.recv_timeout(Duration::from_secs(1)) {
  784. assert_eq!(p, payload);
  785. received.push(source);
  786. }
  787. assert_events("emit_to", &received, &[other_webview_listen_id]);
  788. }
  789. }