manager.rs 44 KB

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