mod.rs 26 KB

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