manager.rs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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, HashSet},
  7. fmt,
  8. fs::create_dir_all,
  9. sync::{Arc, Mutex, MutexGuard},
  10. };
  11. use serde::Serialize;
  12. use serde_json::Value as JsonValue;
  13. use serialize_to_javascript::{default_template, DefaultTemplate, Template};
  14. use url::Url;
  15. use tauri_macros::default_runtime;
  16. use tauri_utils::debug_eprintln;
  17. #[cfg(feature = "isolation")]
  18. use tauri_utils::pattern::isolation::RawIsolationPayload;
  19. use tauri_utils::{
  20. assets::{AssetKey, CspHash},
  21. config::{Csp, CspDirectiveSources},
  22. html::{SCRIPT_NONCE_TOKEN, STYLE_NONCE_TOKEN},
  23. };
  24. use crate::app::{GlobalMenuEventListener, WindowMenuEvent};
  25. use crate::hooks::IpcJavascript;
  26. #[cfg(feature = "isolation")]
  27. use crate::hooks::IsolationJavascript;
  28. use crate::pattern::PatternJavascript;
  29. use crate::{
  30. app::{AppHandle, GlobalWindowEvent, GlobalWindowEventListener},
  31. event::{assert_event_name_is_valid, Event, EventHandler, Listeners},
  32. hooks::{InvokeHandler, InvokePayload, InvokeResponder, OnPageLoad, PageLoadPayload},
  33. plugin::PluginStore,
  34. runtime::{
  35. http::{
  36. MimeType, Request as HttpRequest, Response as HttpResponse,
  37. ResponseBuilder as HttpResponseBuilder,
  38. },
  39. webview::{WebviewIpcHandler, WindowBuilder},
  40. window::{dpi::PhysicalSize, DetachedWindow, FileDropEvent, PendingWindow},
  41. },
  42. utils::{
  43. assets::Assets,
  44. config::{AppUrl, Config, WindowUrl},
  45. PackageInfo,
  46. },
  47. Context, EventLoopMessage, Icon, Invoke, Manager, Pattern, Runtime, Scopes, StateManager, Window,
  48. WindowEvent,
  49. };
  50. #[cfg(any(target_os = "linux", target_os = "windows"))]
  51. use crate::api::path::{resolve_path, BaseDirectory};
  52. use crate::{runtime::menu::Menu, MenuEvent};
  53. const WINDOW_RESIZED_EVENT: &str = "tauri://resize";
  54. const WINDOW_MOVED_EVENT: &str = "tauri://move";
  55. const WINDOW_CLOSE_REQUESTED_EVENT: &str = "tauri://close-requested";
  56. const WINDOW_DESTROYED_EVENT: &str = "tauri://destroyed";
  57. const WINDOW_FOCUS_EVENT: &str = "tauri://focus";
  58. const WINDOW_BLUR_EVENT: &str = "tauri://blur";
  59. const WINDOW_SCALE_FACTOR_CHANGED_EVENT: &str = "tauri://scale-change";
  60. const WINDOW_THEME_CHANGED: &str = "tauri://theme-changed";
  61. const WINDOW_FILE_DROP_EVENT: &str = "tauri://file-drop";
  62. const WINDOW_FILE_DROP_HOVER_EVENT: &str = "tauri://file-drop-hover";
  63. const WINDOW_FILE_DROP_CANCELLED_EVENT: &str = "tauri://file-drop-cancelled";
  64. const MENU_EVENT: &str = "tauri://menu";
  65. pub(crate) const STRINGIFY_IPC_MESSAGE_FN: &str =
  66. include_str!("../scripts/stringify-ipc-message-fn.js");
  67. #[derive(Default)]
  68. /// Spaced and quoted Content-Security-Policy hash values.
  69. struct CspHashStrings {
  70. script: Vec<String>,
  71. style: Vec<String>,
  72. }
  73. /// Sets the CSP value to the asset HTML if needed (on Linux).
  74. /// Returns the CSP string for access on the response header (on Windows and macOS).
  75. fn set_csp<R: Runtime>(
  76. asset: &mut String,
  77. assets: Arc<dyn Assets>,
  78. asset_path: &AssetKey,
  79. manager: &WindowManager<R>,
  80. csp: Csp,
  81. ) -> String {
  82. let mut csp = csp.into();
  83. let hash_strings =
  84. assets
  85. .csp_hashes(asset_path)
  86. .fold(CspHashStrings::default(), |mut acc, hash| {
  87. match hash {
  88. CspHash::Script(hash) => {
  89. acc.script.push(hash.into());
  90. }
  91. CspHash::Style(hash) => {
  92. acc.style.push(hash.into());
  93. }
  94. _csp_hash => {
  95. debug_eprintln!("Unknown CspHash variant encountered: {:?}", _csp_hash);
  96. }
  97. }
  98. acc
  99. });
  100. let dangerous_disable_asset_csp_modification = &manager
  101. .config()
  102. .tauri
  103. .security
  104. .dangerous_disable_asset_csp_modification;
  105. if dangerous_disable_asset_csp_modification.can_modify("script-src") {
  106. replace_csp_nonce(
  107. asset,
  108. SCRIPT_NONCE_TOKEN,
  109. &mut csp,
  110. "script-src",
  111. hash_strings.script,
  112. );
  113. }
  114. if dangerous_disable_asset_csp_modification.can_modify("style-src") {
  115. replace_csp_nonce(
  116. asset,
  117. STYLE_NONCE_TOKEN,
  118. &mut csp,
  119. "style-src",
  120. hash_strings.style,
  121. );
  122. }
  123. #[cfg(feature = "isolation")]
  124. if let Pattern::Isolation { schema, .. } = &manager.inner.pattern {
  125. let default_src = csp
  126. .entry("default-src".into())
  127. .or_insert_with(Default::default);
  128. default_src.push(crate::pattern::format_real_schema(schema));
  129. }
  130. Csp::DirectiveMap(csp).to_string()
  131. }
  132. #[cfg(target_os = "linux")]
  133. fn set_html_csp(html: &str, csp: &str) -> String {
  134. html.replacen(tauri_utils::html::CSP_TOKEN, csp, 1)
  135. }
  136. // inspired by https://github.com/rust-lang/rust/blob/1be5c8f90912c446ecbdc405cbc4a89f9acd20fd/library/alloc/src/str.rs#L260-L297
  137. fn replace_with_callback<F: FnMut() -> String>(
  138. original: &str,
  139. pattern: &str,
  140. mut replacement: F,
  141. ) -> String {
  142. let mut result = String::new();
  143. let mut last_end = 0;
  144. for (start, part) in original.match_indices(pattern) {
  145. result.push_str(unsafe { original.get_unchecked(last_end..start) });
  146. result.push_str(&replacement());
  147. last_end = start + part.len();
  148. }
  149. result.push_str(unsafe { original.get_unchecked(last_end..original.len()) });
  150. result
  151. }
  152. fn replace_csp_nonce(
  153. asset: &mut String,
  154. token: &str,
  155. csp: &mut HashMap<String, CspDirectiveSources>,
  156. directive: &str,
  157. hashes: Vec<String>,
  158. ) {
  159. let mut nonces = Vec::new();
  160. *asset = replace_with_callback(asset, token, || {
  161. let nonce = rand::random::<usize>();
  162. nonces.push(nonce);
  163. nonce.to_string()
  164. });
  165. if !(nonces.is_empty() && hashes.is_empty()) {
  166. let nonce_sources = nonces
  167. .into_iter()
  168. .map(|n| format!("'nonce-{n}'"))
  169. .collect::<Vec<String>>();
  170. let sources = csp.entry(directive.into()).or_insert_with(Default::default);
  171. let self_source = "'self'".to_string();
  172. if !sources.contains(&self_source) {
  173. sources.push(self_source);
  174. }
  175. sources.extend(nonce_sources);
  176. sources.extend(hashes);
  177. }
  178. }
  179. #[default_runtime(crate::Wry, wry)]
  180. pub struct InnerWindowManager<R: Runtime> {
  181. windows: Mutex<HashMap<String, Window<R>>>,
  182. #[cfg(all(desktop, feature = "system-tray"))]
  183. pub(crate) trays: Mutex<HashMap<String, crate::SystemTrayHandle<R>>>,
  184. pub(crate) plugins: Mutex<PluginStore<R>>,
  185. listeners: Listeners,
  186. pub(crate) state: Arc<StateManager>,
  187. /// The JS message handler.
  188. invoke_handler: Box<InvokeHandler<R>>,
  189. /// The page load hook, invoked when the webview performs a navigation.
  190. on_page_load: Box<OnPageLoad<R>>,
  191. config: Arc<Config>,
  192. assets: Arc<dyn Assets>,
  193. pub(crate) default_window_icon: Option<Icon>,
  194. pub(crate) app_icon: Option<Vec<u8>>,
  195. pub(crate) tray_icon: Option<Icon>,
  196. package_info: PackageInfo,
  197. /// The webview protocols available to all windows.
  198. uri_scheme_protocols: HashMap<String, Arc<CustomProtocol<R>>>,
  199. /// The menu set to all windows.
  200. menu: Option<Menu>,
  201. /// Menu event listeners to all windows.
  202. menu_event_listeners: Arc<Vec<GlobalMenuEventListener<R>>>,
  203. /// Window event listeners to all windows.
  204. window_event_listeners: Arc<Vec<GlobalWindowEventListener<R>>>,
  205. /// Responder for invoke calls.
  206. invoke_responder: Arc<InvokeResponder<R>>,
  207. /// The script that initializes the invoke system.
  208. invoke_initialization_script: String,
  209. /// Application pattern.
  210. pub(crate) pattern: Pattern,
  211. }
  212. impl<R: Runtime> fmt::Debug for InnerWindowManager<R> {
  213. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  214. f.debug_struct("InnerWindowManager")
  215. .field("plugins", &self.plugins)
  216. .field("state", &self.state)
  217. .field("config", &self.config)
  218. .field("default_window_icon", &self.default_window_icon)
  219. .field("app_icon", &self.app_icon)
  220. .field("tray_icon", &self.tray_icon)
  221. .field("package_info", &self.package_info)
  222. .field("menu", &self.menu)
  223. .field("pattern", &self.pattern)
  224. .finish()
  225. }
  226. }
  227. /// A resolved asset.
  228. pub struct Asset {
  229. /// The asset bytes.
  230. pub bytes: Vec<u8>,
  231. /// The asset's mime type.
  232. pub mime_type: String,
  233. /// The `Content-Security-Policy` header value.
  234. pub csp_header: Option<String>,
  235. }
  236. /// Uses a custom URI scheme handler to resolve file requests
  237. pub struct CustomProtocol<R: Runtime> {
  238. /// Handler for protocol
  239. #[allow(clippy::type_complexity)]
  240. pub protocol: Box<
  241. dyn Fn(&AppHandle<R>, &HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>>
  242. + Send
  243. + Sync,
  244. >,
  245. }
  246. #[default_runtime(crate::Wry, wry)]
  247. #[derive(Debug)]
  248. pub struct WindowManager<R: Runtime> {
  249. pub inner: Arc<InnerWindowManager<R>>,
  250. }
  251. impl<R: Runtime> Clone for WindowManager<R> {
  252. fn clone(&self) -> Self {
  253. Self {
  254. inner: self.inner.clone(),
  255. }
  256. }
  257. }
  258. impl<R: Runtime> WindowManager<R> {
  259. #[allow(clippy::too_many_arguments)]
  260. pub(crate) fn with_handlers(
  261. #[allow(unused_mut)] mut context: Context<impl Assets>,
  262. plugins: PluginStore<R>,
  263. invoke_handler: Box<InvokeHandler<R>>,
  264. on_page_load: Box<OnPageLoad<R>>,
  265. uri_scheme_protocols: HashMap<String, Arc<CustomProtocol<R>>>,
  266. state: StateManager,
  267. window_event_listeners: Vec<GlobalWindowEventListener<R>>,
  268. (menu, menu_event_listeners): (Option<Menu>, Vec<GlobalMenuEventListener<R>>),
  269. (invoke_responder, invoke_initialization_script): (Arc<InvokeResponder<R>>, String),
  270. ) -> Self {
  271. // generate a random isolation key at runtime
  272. #[cfg(feature = "isolation")]
  273. if let Pattern::Isolation { ref mut key, .. } = &mut context.pattern {
  274. *key = uuid::Uuid::new_v4().to_string();
  275. }
  276. Self {
  277. inner: Arc::new(InnerWindowManager {
  278. windows: Mutex::default(),
  279. #[cfg(all(desktop, feature = "system-tray"))]
  280. trays: Default::default(),
  281. plugins: Mutex::new(plugins),
  282. listeners: Listeners::default(),
  283. state: Arc::new(state),
  284. invoke_handler,
  285. on_page_load,
  286. config: Arc::new(context.config),
  287. assets: context.assets,
  288. default_window_icon: context.default_window_icon,
  289. app_icon: context.app_icon,
  290. tray_icon: context.system_tray_icon,
  291. package_info: context.package_info,
  292. pattern: context.pattern,
  293. uri_scheme_protocols,
  294. menu,
  295. menu_event_listeners: Arc::new(menu_event_listeners),
  296. window_event_listeners: Arc::new(window_event_listeners),
  297. invoke_responder,
  298. invoke_initialization_script,
  299. }),
  300. }
  301. }
  302. pub(crate) fn pattern(&self) -> &Pattern {
  303. &self.inner.pattern
  304. }
  305. /// Get a locked handle to the windows.
  306. pub(crate) fn windows_lock(&self) -> MutexGuard<'_, HashMap<String, Window<R>>> {
  307. self.inner.windows.lock().expect("poisoned window manager")
  308. }
  309. /// State managed by the application.
  310. pub(crate) fn state(&self) -> Arc<StateManager> {
  311. self.inner.state.clone()
  312. }
  313. /// The invoke responder.
  314. pub(crate) fn invoke_responder(&self) -> Arc<InvokeResponder<R>> {
  315. self.inner.invoke_responder.clone()
  316. }
  317. /// Get the base path to serve data from.
  318. ///
  319. /// * In dev mode, this will be based on the `devPath` configuration value.
  320. /// * Otherwise, this will be based on the `distDir` configuration value.
  321. #[cfg(not(dev))]
  322. fn base_path(&self) -> &AppUrl {
  323. &self.inner.config.build.dist_dir
  324. }
  325. #[cfg(dev)]
  326. fn base_path(&self) -> &AppUrl {
  327. &self.inner.config.build.dev_path
  328. }
  329. /// Get the base URL to use for webview requests.
  330. ///
  331. /// In dev mode, this will be based on the `devPath` configuration value.
  332. pub(crate) fn get_url(&self) -> Cow<'_, Url> {
  333. match self.base_path() {
  334. AppUrl::Url(WindowUrl::External(url)) => Cow::Borrowed(url),
  335. #[cfg(windows)]
  336. _ => Cow::Owned(Url::parse("https://tauri.localhost").unwrap()),
  337. #[cfg(not(windows))]
  338. _ => Cow::Owned(Url::parse("tauri://localhost").unwrap()),
  339. }
  340. }
  341. fn csp(&self) -> Option<Csp> {
  342. if cfg!(feature = "custom-protocol") {
  343. self.inner.config.tauri.security.csp.clone()
  344. } else {
  345. self
  346. .inner
  347. .config
  348. .tauri
  349. .security
  350. .dev_csp
  351. .clone()
  352. .or_else(|| self.inner.config.tauri.security.csp.clone())
  353. }
  354. }
  355. fn prepare_pending_window(
  356. &self,
  357. mut pending: PendingWindow<EventLoopMessage, R>,
  358. label: &str,
  359. window_labels: &[String],
  360. app_handle: AppHandle<R>,
  361. ) -> crate::Result<PendingWindow<EventLoopMessage, R>> {
  362. let is_init_global = self.inner.config.build.with_global_tauri;
  363. let plugin_init = self
  364. .inner
  365. .plugins
  366. .lock()
  367. .expect("poisoned plugin store")
  368. .initialization_script();
  369. let pattern_init = PatternJavascript {
  370. pattern: self.pattern().into(),
  371. }
  372. .render_default(&Default::default())?;
  373. let ipc_init = IpcJavascript {
  374. isolation_origin: &match self.pattern() {
  375. #[cfg(feature = "isolation")]
  376. Pattern::Isolation { schema, .. } => crate::pattern::format_real_schema(schema),
  377. _ => "".to_string(),
  378. },
  379. }
  380. .render_default(&Default::default())?;
  381. let mut webview_attributes = pending.webview_attributes;
  382. let mut window_labels = window_labels.to_vec();
  383. let l = label.to_string();
  384. if !window_labels.contains(&l) {
  385. window_labels.push(l);
  386. }
  387. webview_attributes = webview_attributes
  388. .initialization_script(&self.inner.invoke_initialization_script)
  389. .initialization_script(&format!(
  390. r#"
  391. Object.defineProperty(window, '__TAURI_METADATA__', {{
  392. value: {{
  393. __windows: {window_labels_array}.map(function (label) {{ return {{ label: label }} }}),
  394. __currentWindow: {{ label: {current_window_label} }}
  395. }}
  396. }})
  397. "#,
  398. window_labels_array = serde_json::to_string(&window_labels)?,
  399. current_window_label = serde_json::to_string(&label)?,
  400. ))
  401. .initialization_script(&self.initialization_script(&ipc_init.into_string(),&pattern_init.into_string(),&plugin_init, is_init_global)?)
  402. ;
  403. #[cfg(feature = "isolation")]
  404. if let Pattern::Isolation { schema, .. } = self.pattern() {
  405. webview_attributes = webview_attributes.initialization_script(
  406. &IsolationJavascript {
  407. isolation_src: &crate::pattern::format_real_schema(schema),
  408. style: tauri_utils::pattern::isolation::IFRAME_STYLE,
  409. }
  410. .render_default(&Default::default())?
  411. .into_string(),
  412. );
  413. }
  414. pending.webview_attributes = webview_attributes;
  415. let mut registered_scheme_protocols = Vec::new();
  416. for (uri_scheme, protocol) in &self.inner.uri_scheme_protocols {
  417. registered_scheme_protocols.push(uri_scheme.clone());
  418. let protocol = protocol.clone();
  419. let app_handle = Mutex::new(app_handle.clone());
  420. pending.register_uri_scheme_protocol(uri_scheme.clone(), move |p| {
  421. (protocol.protocol)(&app_handle.lock().unwrap(), p)
  422. });
  423. }
  424. let window_url = pending.current_url.lock().unwrap().clone();
  425. let window_origin =
  426. if cfg!(windows) && window_url.scheme() != "http" && window_url.scheme() != "https" {
  427. format!("https://{}.localhost", window_url.scheme())
  428. } else {
  429. format!(
  430. "{}://{}{}",
  431. window_url.scheme(),
  432. window_url.host().unwrap(),
  433. if let Some(port) = window_url.port() {
  434. format!(":{port}")
  435. } else {
  436. "".into()
  437. }
  438. )
  439. };
  440. if !registered_scheme_protocols.contains(&"tauri".into()) {
  441. let web_resource_request_handler = pending.web_resource_request_handler.take();
  442. pending.register_uri_scheme_protocol(
  443. "tauri",
  444. self.prepare_uri_scheme_protocol(&window_origin, web_resource_request_handler),
  445. );
  446. registered_scheme_protocols.push("tauri".into());
  447. }
  448. #[cfg(protocol_asset)]
  449. if !registered_scheme_protocols.contains(&"asset".into()) {
  450. use crate::api::file::SafePathBuf;
  451. use tokio::io::{AsyncReadExt, AsyncSeekExt};
  452. use url::Position;
  453. let asset_scope = self.state().get::<crate::Scopes>().asset_protocol.clone();
  454. pending.register_uri_scheme_protocol("asset", move |request| {
  455. let parsed_path = Url::parse(request.uri())?;
  456. let filtered_path = &parsed_path[..Position::AfterPath];
  457. let path = filtered_path
  458. .strip_prefix("asset://localhost/")
  459. // the `strip_prefix` only returns None when a request is made to `https://tauri.$P` on Windows
  460. // where `$P` is not `localhost/*`
  461. .unwrap_or("");
  462. let path = percent_encoding::percent_decode(path.as_bytes())
  463. .decode_utf8_lossy()
  464. .to_string();
  465. if let Err(e) = SafePathBuf::new(path.clone().into()) {
  466. debug_eprintln!("asset protocol path \"{}\" is not valid: {}", path, e);
  467. return HttpResponseBuilder::new().status(403).body(Vec::new());
  468. }
  469. if !asset_scope.is_allowed(&path) {
  470. debug_eprintln!("asset protocol not configured to allow the path: {}", path);
  471. return HttpResponseBuilder::new().status(403).body(Vec::new());
  472. }
  473. let path_ = path.clone();
  474. let mut response =
  475. HttpResponseBuilder::new().header("Access-Control-Allow-Origin", &window_origin);
  476. // handle 206 (partial range) http request
  477. if let Some(range) = request
  478. .headers()
  479. .get("range")
  480. .and_then(|r| r.to_str().map(|r| r.to_string()).ok())
  481. {
  482. #[derive(Default)]
  483. struct RangeMetadata {
  484. file: Option<tokio::fs::File>,
  485. range: Option<crate::runtime::http::HttpRange>,
  486. metadata: Option<std::fs::Metadata>,
  487. headers: HashMap<&'static str, String>,
  488. status_code: u16,
  489. body: Vec<u8>,
  490. }
  491. let mut range_metadata = crate::async_runtime::safe_block_on(async move {
  492. let mut data = RangeMetadata::default();
  493. // open the file
  494. let mut file = match tokio::fs::File::open(path_.clone()).await {
  495. Ok(file) => file,
  496. Err(e) => {
  497. debug_eprintln!("Failed to open asset: {}", e);
  498. data.status_code = 404;
  499. return data;
  500. }
  501. };
  502. // Get the file size
  503. let file_size = match file.metadata().await {
  504. Ok(metadata) => {
  505. let len = metadata.len();
  506. data.metadata.replace(metadata);
  507. len
  508. }
  509. Err(e) => {
  510. debug_eprintln!("Failed to read asset metadata: {}", e);
  511. data.file.replace(file);
  512. data.status_code = 404;
  513. return data;
  514. }
  515. };
  516. // parse the range
  517. let range = match crate::runtime::http::HttpRange::parse(
  518. &if range.ends_with("-*") {
  519. range.chars().take(range.len() - 1).collect::<String>()
  520. } else {
  521. range.clone()
  522. },
  523. file_size,
  524. ) {
  525. Ok(r) => r,
  526. Err(e) => {
  527. debug_eprintln!("Failed to parse range {}: {:?}", range, e);
  528. data.file.replace(file);
  529. data.status_code = 400;
  530. return data;
  531. }
  532. };
  533. // FIXME: Support multiple ranges
  534. // let support only 1 range for now
  535. if let Some(range) = range.first() {
  536. data.range.replace(*range);
  537. let mut real_length = range.length;
  538. // prevent max_length;
  539. // specially on webview2
  540. if range.length > file_size / 3 {
  541. // max size sent (400ko / request)
  542. // as it's local file system we can afford to read more often
  543. real_length = std::cmp::min(file_size - range.start, 1024 * 400);
  544. }
  545. // last byte we are reading, the length of the range include the last byte
  546. // who should be skipped on the header
  547. let last_byte = range.start + real_length - 1;
  548. data.headers.insert("Connection", "Keep-Alive".into());
  549. data.headers.insert("Accept-Ranges", "bytes".into());
  550. data
  551. .headers
  552. .insert("Content-Length", real_length.to_string());
  553. data.headers.insert(
  554. "Content-Range",
  555. format!("bytes {}-{last_byte}/{file_size}", range.start),
  556. );
  557. if let Err(e) = file.seek(std::io::SeekFrom::Start(range.start)).await {
  558. debug_eprintln!("Failed to seek file to {}: {}", range.start, e);
  559. data.file.replace(file);
  560. data.status_code = 422;
  561. return data;
  562. }
  563. let mut f = file.take(real_length);
  564. let r = f.read_to_end(&mut data.body).await;
  565. file = f.into_inner();
  566. data.file.replace(file);
  567. if let Err(e) = r {
  568. debug_eprintln!("Failed read file: {}", e);
  569. data.status_code = 422;
  570. return data;
  571. }
  572. // partial content
  573. data.status_code = 206;
  574. } else {
  575. data.status_code = 200;
  576. }
  577. data
  578. });
  579. for (k, v) in range_metadata.headers {
  580. response = response.header(k, v);
  581. }
  582. let mime_type = if let (Some(mut file), Some(metadata), Some(range)) = (
  583. range_metadata.file,
  584. range_metadata.metadata,
  585. range_metadata.range,
  586. ) {
  587. // if we're already reading the beginning of the file, we do not need to re-read it
  588. if range.start == 0 {
  589. MimeType::parse(&range_metadata.body, &path)
  590. } else {
  591. let (status, bytes) = crate::async_runtime::safe_block_on(async move {
  592. let mut status = None;
  593. if let Err(e) = file.rewind().await {
  594. debug_eprintln!("Failed to rewind file: {}", e);
  595. status.replace(422);
  596. (status, Vec::with_capacity(0))
  597. } else {
  598. // taken from https://docs.rs/infer/0.9.0/src/infer/lib.rs.html#240-251
  599. let limit = std::cmp::min(metadata.len(), 8192) as usize + 1;
  600. let mut bytes = Vec::with_capacity(limit);
  601. if let Err(e) = file.take(8192).read_to_end(&mut bytes).await {
  602. debug_eprintln!("Failed read file: {}", e);
  603. status.replace(422);
  604. }
  605. (status, bytes)
  606. }
  607. });
  608. if let Some(s) = status {
  609. range_metadata.status_code = s;
  610. }
  611. MimeType::parse(&bytes, &path)
  612. }
  613. } else {
  614. MimeType::parse(&range_metadata.body, &path)
  615. };
  616. response
  617. .mimetype(&mime_type)
  618. .status(range_metadata.status_code)
  619. .body(range_metadata.body)
  620. } else {
  621. match crate::async_runtime::safe_block_on(async move { tokio::fs::read(path_).await }) {
  622. Ok(data) => {
  623. let mime_type = MimeType::parse(&data, &path);
  624. response.mimetype(&mime_type).body(data)
  625. }
  626. Err(e) => {
  627. debug_eprintln!("Failed to read file: {}", e);
  628. response.status(404).body(Vec::new())
  629. }
  630. }
  631. }
  632. });
  633. }
  634. #[cfg(feature = "isolation")]
  635. if let Pattern::Isolation {
  636. assets,
  637. schema,
  638. key: _,
  639. crypto_keys,
  640. } = &self.inner.pattern
  641. {
  642. let assets = assets.clone();
  643. let schema_ = schema.clone();
  644. let url_base = format!("{schema_}://localhost");
  645. let aes_gcm_key = *crypto_keys.aes_gcm().raw();
  646. pending.register_uri_scheme_protocol(schema, move |request| {
  647. match request_to_path(request, &url_base).as_str() {
  648. "index.html" => match assets.get(&"index.html".into()) {
  649. Some(asset) => {
  650. let asset = String::from_utf8_lossy(asset.as_ref());
  651. let template = tauri_utils::pattern::isolation::IsolationJavascriptRuntime {
  652. runtime_aes_gcm_key: &aes_gcm_key,
  653. stringify_ipc_message_fn: STRINGIFY_IPC_MESSAGE_FN,
  654. };
  655. match template.render(asset.as_ref(), &Default::default()) {
  656. Ok(asset) => HttpResponseBuilder::new()
  657. .mimetype("text/html")
  658. .body(asset.into_string().as_bytes().to_vec()),
  659. Err(_) => HttpResponseBuilder::new()
  660. .status(500)
  661. .mimetype("text/plain")
  662. .body(Vec::new()),
  663. }
  664. }
  665. None => HttpResponseBuilder::new()
  666. .status(404)
  667. .mimetype("text/plain")
  668. .body(Vec::new()),
  669. },
  670. _ => HttpResponseBuilder::new()
  671. .status(404)
  672. .mimetype("text/plain")
  673. .body(Vec::new()),
  674. }
  675. });
  676. }
  677. Ok(pending)
  678. }
  679. fn prepare_ipc_handler(
  680. &self,
  681. app_handle: AppHandle<R>,
  682. ) -> WebviewIpcHandler<EventLoopMessage, R> {
  683. let manager = self.clone();
  684. Box::new(move |window, #[allow(unused_mut)] mut request| {
  685. let window = Window::new(manager.clone(), window, app_handle.clone());
  686. #[cfg(feature = "isolation")]
  687. if let Pattern::Isolation { crypto_keys, .. } = manager.pattern() {
  688. match RawIsolationPayload::try_from(request.as_str())
  689. .and_then(|raw| crypto_keys.decrypt(raw))
  690. {
  691. Ok(json) => request = json,
  692. Err(e) => {
  693. let error: crate::Error = e.into();
  694. let _ = window.eval(&format!(
  695. r#"console.error({})"#,
  696. JsonValue::String(error.to_string())
  697. ));
  698. return;
  699. }
  700. }
  701. }
  702. match serde_json::from_str::<InvokePayload>(&request) {
  703. Ok(message) => {
  704. let _ = window.on_message(message);
  705. }
  706. Err(e) => {
  707. let error: crate::Error = e.into();
  708. let _ = window.eval(&format!(
  709. r#"console.error({})"#,
  710. JsonValue::String(error.to_string())
  711. ));
  712. }
  713. }
  714. })
  715. }
  716. pub fn get_asset(&self, mut path: String) -> Result<Asset, Box<dyn std::error::Error>> {
  717. let assets = &self.inner.assets;
  718. if path.ends_with('/') {
  719. path.pop();
  720. }
  721. path = percent_encoding::percent_decode(path.as_bytes())
  722. .decode_utf8_lossy()
  723. .to_string();
  724. let path = if path.is_empty() {
  725. // if the url is `tauri://localhost`, we should load `index.html`
  726. "index.html".to_string()
  727. } else {
  728. // skip leading `/`
  729. path.chars().skip(1).collect::<String>()
  730. };
  731. let mut asset_path = AssetKey::from(path.as_str());
  732. let asset_response = assets
  733. .get(&path.as_str().into())
  734. .or_else(|| {
  735. eprintln!("Asset `{path}` not found; fallback to {path}.html");
  736. let fallback = format!("{}.html", path.as_str()).into();
  737. let asset = assets.get(&fallback);
  738. asset_path = fallback;
  739. asset
  740. })
  741. .or_else(|| {
  742. debug_eprintln!(
  743. "Asset `{}` not found; fallback to {}/index.html",
  744. path,
  745. path
  746. );
  747. let fallback = format!("{}/index.html", path.as_str()).into();
  748. let asset = assets.get(&fallback);
  749. asset_path = fallback;
  750. asset
  751. })
  752. .or_else(|| {
  753. debug_eprintln!("Asset `{}` not found; fallback to index.html", path);
  754. let fallback = AssetKey::from("index.html");
  755. let asset = assets.get(&fallback);
  756. asset_path = fallback;
  757. asset
  758. })
  759. .ok_or_else(|| crate::Error::AssetNotFound(path.clone()))
  760. .map(Cow::into_owned);
  761. let mut csp_header = None;
  762. let is_html = asset_path.as_ref().ends_with(".html");
  763. match asset_response {
  764. Ok(asset) => {
  765. let final_data = if is_html {
  766. let mut asset = String::from_utf8_lossy(&asset).into_owned();
  767. if let Some(csp) = self.csp() {
  768. csp_header.replace(set_csp(
  769. &mut asset,
  770. self.inner.assets.clone(),
  771. &asset_path,
  772. self,
  773. csp,
  774. ));
  775. }
  776. asset.as_bytes().to_vec()
  777. } else {
  778. asset
  779. };
  780. let mime_type = MimeType::parse(&final_data, &path);
  781. Ok(Asset {
  782. bytes: final_data.to_vec(),
  783. mime_type,
  784. csp_header,
  785. })
  786. }
  787. Err(e) => {
  788. debug_eprintln!("{:?}", e); // TODO log::error!
  789. Err(Box::new(e))
  790. }
  791. }
  792. }
  793. #[allow(clippy::type_complexity)]
  794. fn prepare_uri_scheme_protocol(
  795. &self,
  796. window_origin: &str,
  797. web_resource_request_handler: Option<
  798. Box<dyn Fn(&HttpRequest, &mut HttpResponse) + Send + Sync>,
  799. >,
  800. ) -> Box<dyn Fn(&HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>> + Send + Sync>
  801. {
  802. let manager = self.clone();
  803. let window_origin = window_origin.to_string();
  804. Box::new(move |request| {
  805. let path = request
  806. .uri()
  807. .split(&['?', '#'][..])
  808. // ignore query string and fragment
  809. .next()
  810. .unwrap()
  811. .strip_prefix("tauri://localhost")
  812. .map(|p| p.to_string())
  813. // the `strip_prefix` only returns None when a request is made to `https://tauri.$P` on Windows
  814. // where `$P` is not `localhost/*`
  815. .unwrap_or_else(|| "".to_string());
  816. let asset = manager.get_asset(path)?;
  817. let mut builder = HttpResponseBuilder::new()
  818. .header("Access-Control-Allow-Origin", &window_origin)
  819. .mimetype(&asset.mime_type);
  820. if let Some(csp) = &asset.csp_header {
  821. builder = builder.header("Content-Security-Policy", csp);
  822. }
  823. let mut response = builder.body(asset.bytes)?;
  824. if let Some(handler) = &web_resource_request_handler {
  825. handler(request, &mut response);
  826. // if it's an HTML file, we need to set the CSP meta tag on Linux
  827. #[cfg(target_os = "linux")]
  828. if let Some(response_csp) = response.headers().get("Content-Security-Policy") {
  829. let response_csp = String::from_utf8_lossy(response_csp.as_bytes());
  830. let body = set_html_csp(&String::from_utf8_lossy(response.body()), &response_csp);
  831. *response.body_mut() = body.as_bytes().to_vec();
  832. }
  833. } else {
  834. #[cfg(target_os = "linux")]
  835. {
  836. if let Some(csp) = &asset.csp_header {
  837. let body = set_html_csp(&String::from_utf8_lossy(response.body()), csp);
  838. *response.body_mut() = body.as_bytes().to_vec();
  839. }
  840. }
  841. }
  842. Ok(response)
  843. })
  844. }
  845. fn initialization_script(
  846. &self,
  847. ipc_script: &str,
  848. pattern_script: &str,
  849. plugin_initialization_script: &str,
  850. with_global_tauri: bool,
  851. ) -> crate::Result<String> {
  852. #[derive(Template)]
  853. #[default_template("../scripts/init.js")]
  854. struct InitJavascript<'a> {
  855. #[raw]
  856. pattern_script: &'a str,
  857. #[raw]
  858. ipc_script: &'a str,
  859. #[raw]
  860. bundle_script: &'a str,
  861. // A function to immediately listen to an event.
  862. #[raw]
  863. listen_function: &'a str,
  864. #[raw]
  865. core_script: &'a str,
  866. #[raw]
  867. event_initialization_script: &'a str,
  868. #[raw]
  869. plugin_initialization_script: &'a str,
  870. #[raw]
  871. freeze_prototype: &'a str,
  872. #[raw]
  873. hotkeys: &'a str,
  874. }
  875. let bundle_script = if with_global_tauri {
  876. include_str!("../scripts/bundle.global.js")
  877. } else {
  878. ""
  879. };
  880. let freeze_prototype = if self.inner.config.tauri.security.freeze_prototype {
  881. include_str!("../scripts/freeze_prototype.js")
  882. } else {
  883. ""
  884. };
  885. #[cfg(any(debug_assertions, feature = "devtools"))]
  886. let hotkeys = &format!(
  887. "
  888. {};
  889. window.hotkeys('{}', () => {{
  890. window.__TAURI_INVOKE__('tauri', {{
  891. __tauriModule: 'Window',
  892. message: {{
  893. cmd: 'manage',
  894. data: {{
  895. cmd: {{
  896. type: '__toggleDevtools'
  897. }}
  898. }}
  899. }}
  900. }});
  901. }});
  902. ",
  903. include_str!("../scripts/hotkey.js"),
  904. if cfg!(target_os = "macos") {
  905. "command+option+i"
  906. } else {
  907. "ctrl+shift+i"
  908. }
  909. );
  910. #[cfg(not(any(debug_assertions, feature = "devtools")))]
  911. let hotkeys = "";
  912. InitJavascript {
  913. pattern_script,
  914. ipc_script,
  915. bundle_script,
  916. listen_function: &format!(
  917. "function listen(eventName, cb) {{ {} }}",
  918. crate::event::listen_js(
  919. self.event_listeners_object_name(),
  920. "eventName".into(),
  921. 0,
  922. None,
  923. "window['_' + window.__TAURI__.transformCallback(cb) ]".into()
  924. )
  925. ),
  926. core_script: include_str!("../scripts/core.js"),
  927. event_initialization_script: &self.event_initialization_script(),
  928. plugin_initialization_script,
  929. freeze_prototype,
  930. hotkeys,
  931. }
  932. .render_default(&Default::default())
  933. .map(|s| s.into_string())
  934. .map_err(Into::into)
  935. }
  936. fn event_initialization_script(&self) -> String {
  937. format!(
  938. "
  939. Object.defineProperty(window, '{function}', {{
  940. value: function (eventData) {{
  941. const listeners = (window['{listeners}'] && window['{listeners}'][eventData.event]) || []
  942. for (let i = listeners.length - 1; i >= 0; i--) {{
  943. const listener = listeners[i]
  944. if (listener.windowLabel === null || listener.windowLabel === eventData.windowLabel) {{
  945. eventData.id = listener.id
  946. listener.handler(eventData)
  947. }}
  948. }}
  949. }}
  950. }});
  951. ",
  952. function = self.event_emit_function_name(),
  953. listeners = self.event_listeners_object_name()
  954. )
  955. }
  956. }
  957. #[cfg(test)]
  958. mod test {
  959. use crate::{generate_context, plugin::PluginStore, StateManager, Wry};
  960. use super::WindowManager;
  961. #[test]
  962. fn check_get_url() {
  963. let context = generate_context!("test/fixture/src-tauri/tauri.conf.json", crate);
  964. let manager: WindowManager<Wry> = WindowManager::with_handlers(
  965. context,
  966. PluginStore::default(),
  967. Box::new(|_| ()),
  968. Box::new(|_, _| ()),
  969. Default::default(),
  970. StateManager::new(),
  971. Default::default(),
  972. Default::default(),
  973. (std::sync::Arc::new(|_, _, _, _| ()), "".into()),
  974. );
  975. #[cfg(custom_protocol)]
  976. {
  977. assert_eq!(
  978. manager.get_url().to_string(),
  979. if cfg!(windows) {
  980. "https://tauri.localhost/"
  981. } else {
  982. "tauri://localhost"
  983. }
  984. );
  985. }
  986. #[cfg(dev)]
  987. assert_eq!(manager.get_url().to_string(), "http://localhost:4000/");
  988. }
  989. }
  990. impl<R: Runtime> WindowManager<R> {
  991. pub fn run_invoke_handler(&self, invoke: Invoke<R>) {
  992. (self.inner.invoke_handler)(invoke);
  993. }
  994. pub fn run_on_page_load(&self, window: Window<R>, payload: PageLoadPayload) {
  995. (self.inner.on_page_load)(window.clone(), payload.clone());
  996. self
  997. .inner
  998. .plugins
  999. .lock()
  1000. .expect("poisoned plugin store")
  1001. .on_page_load(window, payload);
  1002. }
  1003. pub fn extend_api(&self, invoke: Invoke<R>) {
  1004. self
  1005. .inner
  1006. .plugins
  1007. .lock()
  1008. .expect("poisoned plugin store")
  1009. .extend_api(invoke);
  1010. }
  1011. pub fn initialize_plugins(&self, app: &AppHandle<R>) -> crate::Result<()> {
  1012. self
  1013. .inner
  1014. .plugins
  1015. .lock()
  1016. .expect("poisoned plugin store")
  1017. .initialize(app, &self.inner.config.plugins)
  1018. }
  1019. pub fn prepare_window(
  1020. &self,
  1021. app_handle: AppHandle<R>,
  1022. mut pending: PendingWindow<EventLoopMessage, R>,
  1023. window_labels: &[String],
  1024. ) -> crate::Result<PendingWindow<EventLoopMessage, R>> {
  1025. if self.windows_lock().contains_key(&pending.label) {
  1026. return Err(crate::Error::WindowLabelAlreadyExists(pending.label));
  1027. }
  1028. #[allow(unused_mut)] // mut url only for the data-url parsing
  1029. let mut url = match &pending.webview_attributes.url {
  1030. WindowUrl::App(path) => {
  1031. let url = self.get_url();
  1032. // ignore "index.html" just to simplify the url
  1033. if path.to_str() != Some("index.html") {
  1034. url
  1035. .join(&path.to_string_lossy())
  1036. .map_err(crate::Error::InvalidUrl)
  1037. // this will never fail
  1038. .unwrap()
  1039. } else {
  1040. url.into_owned()
  1041. }
  1042. }
  1043. WindowUrl::External(url) => url.clone(),
  1044. _ => unimplemented!(),
  1045. };
  1046. #[cfg(not(feature = "window-data-url"))]
  1047. if url.scheme() == "data" {
  1048. return Err(crate::Error::InvalidWindowUrl(
  1049. "data URLs are not supported without the `window-data-url` feature.",
  1050. ));
  1051. }
  1052. #[cfg(feature = "window-data-url")]
  1053. if let Some(csp) = self.csp() {
  1054. if url.scheme() == "data" {
  1055. if let Ok(data_url) = data_url::DataUrl::process(url.as_str()) {
  1056. let (body, _) = data_url.decode_to_vec().unwrap();
  1057. let html = String::from_utf8_lossy(&body).into_owned();
  1058. // naive way to check if it's an html
  1059. if html.contains('<') && html.contains('>') {
  1060. let mut document = tauri_utils::html::parse(html);
  1061. tauri_utils::html::inject_csp(&mut document, &csp.to_string());
  1062. url.set_path(&format!("text/html,{}", document.to_string()));
  1063. }
  1064. }
  1065. }
  1066. }
  1067. *pending.current_url.lock().unwrap() = url;
  1068. if !pending.window_builder.has_icon() {
  1069. if let Some(default_window_icon) = self.inner.default_window_icon.clone() {
  1070. pending.window_builder = pending
  1071. .window_builder
  1072. .icon(default_window_icon.try_into()?)?;
  1073. }
  1074. }
  1075. if pending.window_builder.get_menu().is_none() {
  1076. if let Some(menu) = &self.inner.menu {
  1077. pending = pending.set_menu(menu.clone());
  1078. }
  1079. }
  1080. let label = pending.label.clone();
  1081. pending = self.prepare_pending_window(pending, &label, window_labels, app_handle.clone())?;
  1082. pending.ipc_handler = Some(self.prepare_ipc_handler(app_handle));
  1083. // in `Windows`, we need to force a data_directory
  1084. // but we do respect user-specification
  1085. #[cfg(any(target_os = "linux", target_os = "windows"))]
  1086. if pending.webview_attributes.data_directory.is_none() {
  1087. let local_app_data = resolve_path(
  1088. &self.inner.config,
  1089. &self.inner.package_info,
  1090. self.inner.state.get::<crate::Env>().inner(),
  1091. &self.inner.config.tauri.bundle.identifier,
  1092. Some(BaseDirectory::LocalData),
  1093. );
  1094. if let Ok(user_data_dir) = local_app_data {
  1095. pending.webview_attributes.data_directory = Some(user_data_dir);
  1096. }
  1097. }
  1098. // make sure the directory is created and available to prevent a panic
  1099. if let Some(user_data_dir) = &pending.webview_attributes.data_directory {
  1100. if !user_data_dir.exists() {
  1101. create_dir_all(user_data_dir)?;
  1102. }
  1103. }
  1104. #[cfg(feature = "isolation")]
  1105. let pattern = self.pattern().clone();
  1106. let current_url_ = pending.current_url.clone();
  1107. let navigation_handler = pending.navigation_handler.take();
  1108. pending.navigation_handler = Some(Box::new(move |url| {
  1109. // always allow navigation events for the isolation iframe and do not emit them for consumers
  1110. #[cfg(feature = "isolation")]
  1111. if let Pattern::Isolation { schema, .. } = &pattern {
  1112. if url.scheme() == schema
  1113. && url.domain() == Some(crate::pattern::ISOLATION_IFRAME_SRC_DOMAIN)
  1114. {
  1115. return true;
  1116. }
  1117. }
  1118. *current_url_.lock().unwrap() = url.clone();
  1119. if let Some(handler) = &navigation_handler {
  1120. handler(url)
  1121. } else {
  1122. true
  1123. }
  1124. }));
  1125. Ok(pending)
  1126. }
  1127. pub fn attach_window(
  1128. &self,
  1129. app_handle: AppHandle<R>,
  1130. window: DetachedWindow<EventLoopMessage, R>,
  1131. ) -> Window<R> {
  1132. let window = Window::new(self.clone(), window, app_handle);
  1133. let window_ = window.clone();
  1134. let window_event_listeners = self.inner.window_event_listeners.clone();
  1135. let manager = self.clone();
  1136. window.on_window_event(move |event| {
  1137. let _ = on_window_event(&window_, &manager, event);
  1138. for handler in window_event_listeners.iter() {
  1139. handler(GlobalWindowEvent {
  1140. window: window_.clone(),
  1141. event: event.clone(),
  1142. });
  1143. }
  1144. });
  1145. {
  1146. let window_ = window.clone();
  1147. let menu_event_listeners = self.inner.menu_event_listeners.clone();
  1148. window.on_menu_event(move |event| {
  1149. let _ = on_menu_event(&window_, &event);
  1150. for handler in menu_event_listeners.iter() {
  1151. handler(WindowMenuEvent {
  1152. window: window_.clone(),
  1153. menu_item_id: event.menu_item_id.clone(),
  1154. });
  1155. }
  1156. });
  1157. }
  1158. // insert the window into our manager
  1159. {
  1160. self
  1161. .windows_lock()
  1162. .insert(window.label().to_string(), window.clone());
  1163. }
  1164. // let plugins know that a new window has been added to the manager
  1165. let manager = self.inner.clone();
  1166. let window_ = window.clone();
  1167. // run on main thread so the plugin store doesn't dead lock with the event loop handler in App
  1168. let _ = window.run_on_main_thread(move || {
  1169. manager
  1170. .plugins
  1171. .lock()
  1172. .expect("poisoned plugin store")
  1173. .created(window_);
  1174. });
  1175. window
  1176. }
  1177. pub(crate) fn on_window_close(&self, label: &str) {
  1178. self.windows_lock().remove(label);
  1179. }
  1180. pub fn emit_filter<S, F>(
  1181. &self,
  1182. event: &str,
  1183. source_window_label: Option<&str>,
  1184. payload: S,
  1185. filter: F,
  1186. ) -> crate::Result<()>
  1187. where
  1188. S: Serialize + Clone,
  1189. F: Fn(&Window<R>) -> bool,
  1190. {
  1191. assert_event_name_is_valid(event);
  1192. self
  1193. .windows_lock()
  1194. .values()
  1195. .filter(|&w| filter(w))
  1196. .try_for_each(|window| window.emit_internal(event, source_window_label, payload.clone()))
  1197. }
  1198. pub fn eval_script_all<S: Into<String>>(&self, script: S) -> crate::Result<()> {
  1199. let script = script.into();
  1200. self
  1201. .windows_lock()
  1202. .values()
  1203. .try_for_each(|window| window.eval(&script))
  1204. }
  1205. pub fn labels(&self) -> HashSet<String> {
  1206. self.windows_lock().keys().cloned().collect()
  1207. }
  1208. pub fn config(&self) -> Arc<Config> {
  1209. self.inner.config.clone()
  1210. }
  1211. pub fn package_info(&self) -> &PackageInfo {
  1212. &self.inner.package_info
  1213. }
  1214. pub fn unlisten(&self, handler_id: EventHandler) {
  1215. self.inner.listeners.unlisten(handler_id)
  1216. }
  1217. pub fn trigger(&self, event: &str, window: Option<String>, data: Option<String>) {
  1218. assert_event_name_is_valid(event);
  1219. self.inner.listeners.trigger(event, window, data)
  1220. }
  1221. pub fn listen<F: Fn(Event) + Send + 'static>(
  1222. &self,
  1223. event: String,
  1224. window: Option<String>,
  1225. handler: F,
  1226. ) -> EventHandler {
  1227. assert_event_name_is_valid(&event);
  1228. self.inner.listeners.listen(event, window, handler)
  1229. }
  1230. pub fn once<F: FnOnce(Event) + Send + 'static>(
  1231. &self,
  1232. event: String,
  1233. window: Option<String>,
  1234. handler: F,
  1235. ) -> EventHandler {
  1236. assert_event_name_is_valid(&event);
  1237. self.inner.listeners.once(event, window, handler)
  1238. }
  1239. pub fn event_listeners_object_name(&self) -> String {
  1240. self.inner.listeners.listeners_object_name()
  1241. }
  1242. pub fn event_emit_function_name(&self) -> String {
  1243. self.inner.listeners.function_name()
  1244. }
  1245. pub fn get_window(&self, label: &str) -> Option<Window<R>> {
  1246. self.windows_lock().get(label).cloned()
  1247. }
  1248. pub fn windows(&self) -> HashMap<String, Window<R>> {
  1249. self.windows_lock().clone()
  1250. }
  1251. }
  1252. /// Tray APIs
  1253. #[cfg(all(desktop, feature = "system-tray"))]
  1254. impl<R: Runtime> WindowManager<R> {
  1255. pub fn get_tray(&self, id: &str) -> Option<crate::SystemTrayHandle<R>> {
  1256. self.inner.trays.lock().unwrap().get(id).cloned()
  1257. }
  1258. pub fn trays(&self) -> HashMap<String, crate::SystemTrayHandle<R>> {
  1259. self.inner.trays.lock().unwrap().clone()
  1260. }
  1261. pub fn attach_tray(&self, id: String, tray: crate::SystemTrayHandle<R>) {
  1262. self.inner.trays.lock().unwrap().insert(id, tray);
  1263. }
  1264. pub fn get_tray_by_runtime_id(&self, id: u16) -> Option<(String, crate::SystemTrayHandle<R>)> {
  1265. let trays = self.inner.trays.lock().unwrap();
  1266. let iter = trays.iter();
  1267. for (tray_id, tray) in iter {
  1268. if tray.id == id {
  1269. return Some((tray_id.clone(), tray.clone()));
  1270. }
  1271. }
  1272. None
  1273. }
  1274. }
  1275. fn on_window_event<R: Runtime>(
  1276. window: &Window<R>,
  1277. manager: &WindowManager<R>,
  1278. event: &WindowEvent,
  1279. ) -> crate::Result<()> {
  1280. match event {
  1281. WindowEvent::Resized(size) => window.emit(WINDOW_RESIZED_EVENT, size)?,
  1282. WindowEvent::Moved(position) => window.emit(WINDOW_MOVED_EVENT, position)?,
  1283. WindowEvent::CloseRequested { api } => {
  1284. if window.has_js_listener(Some(window.label().into()), WINDOW_CLOSE_REQUESTED_EVENT) {
  1285. api.prevent_close();
  1286. }
  1287. window.emit(WINDOW_CLOSE_REQUESTED_EVENT, ())?;
  1288. }
  1289. WindowEvent::Destroyed => {
  1290. window.emit(WINDOW_DESTROYED_EVENT, ())?;
  1291. let label = window.label();
  1292. let windows_map = manager.inner.windows.lock().unwrap();
  1293. let windows = windows_map.values();
  1294. for window in windows {
  1295. window.eval(&format!(
  1296. r#"(function () {{ const metadata = window.__TAURI_METADATA__; if (metadata != null) {{ metadata.__windows = window.__TAURI_METADATA__.__windows.filter(w => w.label !== "{label}"); }} }})()"#
  1297. ))?;
  1298. }
  1299. }
  1300. WindowEvent::Focused(focused) => window.emit(
  1301. if *focused {
  1302. WINDOW_FOCUS_EVENT
  1303. } else {
  1304. WINDOW_BLUR_EVENT
  1305. },
  1306. (),
  1307. )?,
  1308. WindowEvent::ScaleFactorChanged {
  1309. scale_factor,
  1310. new_inner_size,
  1311. ..
  1312. } => window.emit(
  1313. WINDOW_SCALE_FACTOR_CHANGED_EVENT,
  1314. ScaleFactorChanged {
  1315. scale_factor: *scale_factor,
  1316. size: *new_inner_size,
  1317. },
  1318. )?,
  1319. WindowEvent::FileDrop(event) => match event {
  1320. FileDropEvent::Hovered(paths) => window.emit(WINDOW_FILE_DROP_HOVER_EVENT, paths)?,
  1321. FileDropEvent::Dropped(paths) => {
  1322. let scopes = window.state::<Scopes>();
  1323. for path in paths {
  1324. if path.is_file() {
  1325. let _ = scopes.allow_file(path);
  1326. } else {
  1327. let _ = scopes.allow_directory(path, false);
  1328. }
  1329. }
  1330. window.emit(WINDOW_FILE_DROP_EVENT, paths)?
  1331. }
  1332. FileDropEvent::Cancelled => window.emit(WINDOW_FILE_DROP_CANCELLED_EVENT, ())?,
  1333. _ => unimplemented!(),
  1334. },
  1335. WindowEvent::ThemeChanged(theme) => window.emit(WINDOW_THEME_CHANGED, theme.to_string())?,
  1336. }
  1337. Ok(())
  1338. }
  1339. #[derive(Clone, Serialize)]
  1340. #[serde(rename_all = "camelCase")]
  1341. struct ScaleFactorChanged {
  1342. scale_factor: f64,
  1343. size: PhysicalSize<u32>,
  1344. }
  1345. fn on_menu_event<R: Runtime>(window: &Window<R>, event: &MenuEvent) -> crate::Result<()> {
  1346. window.emit(MENU_EVENT, event.menu_item_id.clone())
  1347. }
  1348. #[cfg(feature = "isolation")]
  1349. fn request_to_path(request: &tauri_runtime::http::Request, base_url: &str) -> String {
  1350. let mut path = request
  1351. .uri()
  1352. .split(&['?', '#'][..])
  1353. // ignore query string
  1354. .next()
  1355. .unwrap()
  1356. .trim_start_matches(base_url)
  1357. .to_string();
  1358. if path.ends_with('/') {
  1359. path.pop();
  1360. }
  1361. let path = percent_encoding::percent_decode(path.as_bytes())
  1362. .decode_utf8_lossy()
  1363. .to_string();
  1364. if path.is_empty() {
  1365. // if the url has no path, we should load `index.html`
  1366. "index.html".to_string()
  1367. } else {
  1368. // skip leading `/`
  1369. path.chars().skip(1).collect()
  1370. }
  1371. }
  1372. #[cfg(test)]
  1373. mod tests {
  1374. use super::replace_with_callback;
  1375. #[test]
  1376. fn string_replace_with_callback() {
  1377. let mut tauri_index = 0;
  1378. #[allow(clippy::single_element_loop)]
  1379. for (src, pattern, replacement, result) in [(
  1380. "tauri is awesome, tauri is amazing",
  1381. "tauri",
  1382. || {
  1383. tauri_index += 1;
  1384. tauri_index.to_string()
  1385. },
  1386. "1 is awesome, 2 is amazing",
  1387. )] {
  1388. assert_eq!(replace_with_callback(src, pattern, replacement), result);
  1389. }
  1390. }
  1391. }