manager.rs 47 KB

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