webview_window.rs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! [`Window`] that hosts a single [`Webview`].
  5. use std::{
  6. borrow::Cow,
  7. path::PathBuf,
  8. sync::{Arc, MutexGuard},
  9. };
  10. use crate::{
  11. event::EventTarget,
  12. runtime::dpi::{PhysicalPosition, PhysicalSize},
  13. window::Monitor,
  14. Emitter, Listener, ResourceTable,
  15. };
  16. #[cfg(desktop)]
  17. use crate::{
  18. image::Image,
  19. menu::{ContextMenu, Menu},
  20. runtime::{
  21. dpi::{Position, Size},
  22. window::CursorIcon,
  23. UserAttentionType,
  24. },
  25. };
  26. use serde::Serialize;
  27. use tauri_runtime::window::WindowSizeConstraints;
  28. use tauri_utils::config::{WebviewUrl, WindowConfig};
  29. use url::Url;
  30. use crate::{
  31. ipc::{CommandArg, CommandItem, InvokeError, OwnedInvokeResponder},
  32. manager::{webview::WebviewLabelDef, AppManager},
  33. sealed::{ManagerBase, RuntimeOrDispatch},
  34. webview::PageLoadPayload,
  35. webview::WebviewBuilder,
  36. window::WindowBuilder,
  37. AppHandle, Event, EventId, Manager, Runtime, Webview, WindowEvent,
  38. };
  39. use tauri_macros::default_runtime;
  40. #[cfg(windows)]
  41. use windows::Win32::Foundation::HWND;
  42. use super::DownloadEvent;
  43. /// A builder for [`WebviewWindow`], a window that hosts a single webview.
  44. pub struct WebviewWindowBuilder<'a, R: Runtime, M: Manager<R>> {
  45. window_builder: WindowBuilder<'a, R, M>,
  46. webview_builder: WebviewBuilder<R>,
  47. }
  48. impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M> {
  49. /// Initializes a webview window builder with the given window label.
  50. ///
  51. /// # Known issues
  52. ///
  53. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  54. /// You should use `async` commands when creating windows.
  55. ///
  56. /// # Examples
  57. ///
  58. /// - Create a window in the setup hook:
  59. ///
  60. /// ```
  61. /// tauri::Builder::default()
  62. /// .setup(|app| {
  63. /// let webview_window = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
  64. /// .build()?;
  65. /// Ok(())
  66. /// });
  67. /// ```
  68. ///
  69. /// - Create a window in a separate thread:
  70. ///
  71. /// ```
  72. /// tauri::Builder::default()
  73. /// .setup(|app| {
  74. /// let handle = app.handle().clone();
  75. /// std::thread::spawn(move || {
  76. /// let webview_window = tauri::WebviewWindowBuilder::new(&handle, "label", tauri::WebviewUrl::App("index.html".into()))
  77. /// .build()
  78. /// .unwrap();
  79. /// });
  80. /// Ok(())
  81. /// });
  82. /// ```
  83. ///
  84. /// - Create a window in a command:
  85. ///
  86. /// ```
  87. /// #[tauri::command]
  88. /// async fn create_window(app: tauri::AppHandle) {
  89. /// let webview_window = tauri::WebviewWindowBuilder::new(&app, "label", tauri::WebviewUrl::App("index.html".into()))
  90. /// .build()
  91. /// .unwrap();
  92. /// }
  93. /// ```
  94. ///
  95. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  96. pub fn new<L: Into<String>>(manager: &'a M, label: L, url: WebviewUrl) -> Self {
  97. let label = label.into();
  98. Self {
  99. window_builder: WindowBuilder::new(manager, &label),
  100. webview_builder: WebviewBuilder::new(&label, url),
  101. }
  102. }
  103. /// Initializes a webview window builder from a [`WindowConfig`] from tauri.conf.json.
  104. /// Keep in mind that you can't create 2 windows with the same `label` so make sure
  105. /// that the initial window was closed or change the label of the new [`WebviewWindowBuilder`].
  106. ///
  107. /// # Known issues
  108. ///
  109. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  110. /// You should use `async` commands when creating windows.
  111. ///
  112. /// # Examples
  113. ///
  114. /// - Create a window in a command:
  115. ///
  116. /// ```
  117. /// #[tauri::command]
  118. /// async fn reopen_window(app: tauri::AppHandle) {
  119. /// let webview_window = tauri::WebviewWindowBuilder::from_config(&app, &app.config().app.windows.get(0).unwrap().clone())
  120. /// .unwrap()
  121. /// .build()
  122. /// .unwrap();
  123. /// }
  124. /// ```
  125. ///
  126. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  127. pub fn from_config(manager: &'a M, config: &WindowConfig) -> crate::Result<Self> {
  128. Ok(Self {
  129. window_builder: WindowBuilder::from_config(manager, config)?,
  130. webview_builder: WebviewBuilder::from_config(config),
  131. })
  132. }
  133. /// Registers a global menu event listener.
  134. ///
  135. /// Note that this handler is called for any menu event,
  136. /// whether it is coming from this window, another window or from the tray icon menu.
  137. ///
  138. /// Also note that this handler will not be called if
  139. /// the window used to register it was closed.
  140. ///
  141. /// # Examples
  142. /// ```
  143. /// use tauri::menu::{Menu, Submenu, MenuItem};
  144. /// tauri::Builder::default()
  145. /// .setup(|app| {
  146. /// let handle = app.handle();
  147. /// let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
  148. /// let menu = Menu::with_items(handle, &[
  149. /// &Submenu::with_items(handle, "File", true, &[
  150. /// &save_menu_item,
  151. /// ])?,
  152. /// ])?;
  153. /// let webview_window = tauri::WebviewWindowBuilder::new(app, "editor", tauri::WebviewUrl::App("index.html".into()))
  154. /// .menu(menu)
  155. /// .on_menu_event(move |window, event| {
  156. /// if event.id == save_menu_item.id() {
  157. /// // save menu item
  158. /// }
  159. /// })
  160. /// .build()
  161. /// .unwrap();
  162. ///
  163. /// Ok(())
  164. /// });
  165. /// ```
  166. #[cfg(desktop)]
  167. pub fn on_menu_event<F: Fn(&crate::Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
  168. mut self,
  169. f: F,
  170. ) -> Self {
  171. self.window_builder = self.window_builder.on_menu_event(f);
  172. self
  173. }
  174. /// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
  175. ///
  176. /// Currently only implemented for the `tauri` URI protocol.
  177. ///
  178. /// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
  179. /// but it might be implemented in the future. **Always** check the request URL.
  180. ///
  181. /// # Examples
  182. /// ```rust,no_run
  183. /// use tauri::{
  184. /// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  185. /// webview::WebviewWindowBuilder,
  186. /// };
  187. /// use http::header::HeaderValue;
  188. /// use std::collections::HashMap;
  189. /// tauri::Builder::default()
  190. /// .setup(|app| {
  191. /// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
  192. /// .on_web_resource_request(|request, response| {
  193. /// if request.uri().scheme_str() == Some("tauri") {
  194. /// // if we have a CSP header, Tauri is loading an HTML file
  195. /// // for this example, let's dynamically change the CSP
  196. /// if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
  197. /// // use the tauri helper to parse the CSP policy to a map
  198. /// let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
  199. /// csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
  200. /// // use the tauri helper to get a CSP string from the map
  201. /// let csp_string = Csp::from(csp_map).to_string();
  202. /// *csp = HeaderValue::from_str(&csp_string).unwrap();
  203. /// }
  204. /// }
  205. /// })
  206. /// .build()?;
  207. /// Ok(())
  208. /// });
  209. /// ```
  210. pub fn on_web_resource_request<
  211. F: Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync + 'static,
  212. >(
  213. mut self,
  214. f: F,
  215. ) -> Self {
  216. self.webview_builder = self.webview_builder.on_web_resource_request(f);
  217. self
  218. }
  219. /// Defines a closure to be executed when the webview navigates to a URL. Returning `false` cancels the navigation.
  220. ///
  221. /// # Examples
  222. /// ```rust,no_run
  223. /// use tauri::{
  224. /// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  225. /// webview::WebviewWindowBuilder,
  226. /// };
  227. /// use http::header::HeaderValue;
  228. /// use std::collections::HashMap;
  229. /// tauri::Builder::default()
  230. /// .setup(|app| {
  231. /// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
  232. /// .on_navigation(|url| {
  233. /// // allow the production URL or localhost on dev
  234. /// url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
  235. /// })
  236. /// .build()?;
  237. /// Ok(())
  238. /// });
  239. /// ```
  240. pub fn on_navigation<F: Fn(&Url) -> bool + Send + 'static>(mut self, f: F) -> Self {
  241. self.webview_builder = self.webview_builder.on_navigation(f);
  242. self
  243. }
  244. /// Set a download event handler to be notified when a download is requested or finished.
  245. ///
  246. /// Returning `false` prevents the download from happening on a [`DownloadEvent::Requested`] event.
  247. ///
  248. /// # Examples
  249. ///
  250. #[cfg_attr(
  251. feature = "unstable",
  252. doc = r####"
  253. ```rust,no_run
  254. use tauri::{
  255. utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  256. webview::{DownloadEvent, WebviewWindowBuilder},
  257. };
  258. tauri::Builder::default()
  259. .setup(|app| {
  260. let handle = app.handle();
  261. let webview_window = WebviewWindowBuilder::new(handle, "core", WebviewUrl::App("index.html".into()))
  262. .on_download(|webview, event| {
  263. match event {
  264. DownloadEvent::Requested { url, destination } => {
  265. println!("downloading {}", url);
  266. *destination = "/home/tauri/target/path".into();
  267. }
  268. DownloadEvent::Finished { url, path, success } => {
  269. println!("downloaded {} to {:?}, success: {}", url, path, success);
  270. }
  271. _ => (),
  272. }
  273. // let the download start
  274. true
  275. })
  276. .build()?;
  277. Ok(())
  278. });
  279. ```
  280. "####
  281. )]
  282. pub fn on_download<F: Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync + 'static>(
  283. mut self,
  284. f: F,
  285. ) -> Self {
  286. self.webview_builder.download_handler.replace(Arc::new(f));
  287. self
  288. }
  289. /// Defines a closure to be executed when a page load event is triggered.
  290. /// The event can be either [`tauri_runtime::webview::PageLoadEvent::Started`] if the page has started loading
  291. /// or [`tauri_runtime::webview::PageLoadEvent::Finished`] when the page finishes loading.
  292. ///
  293. /// # Examples
  294. /// ```rust,no_run
  295. /// use tauri::{
  296. /// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  297. /// webview::{PageLoadEvent, WebviewWindowBuilder},
  298. /// };
  299. /// use http::header::HeaderValue;
  300. /// use std::collections::HashMap;
  301. /// tauri::Builder::default()
  302. /// .setup(|app| {
  303. /// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
  304. /// .on_page_load(|window, payload| {
  305. /// match payload.event() {
  306. /// PageLoadEvent::Started => {
  307. /// println!("{} finished loading", payload.url());
  308. /// }
  309. /// PageLoadEvent::Finished => {
  310. /// println!("{} finished loading", payload.url());
  311. /// }
  312. /// }
  313. /// })
  314. /// .build()?;
  315. /// Ok(())
  316. /// });
  317. /// ```
  318. pub fn on_page_load<F: Fn(WebviewWindow<R>, PageLoadPayload<'_>) + Send + Sync + 'static>(
  319. mut self,
  320. f: F,
  321. ) -> Self {
  322. self.webview_builder = self
  323. .webview_builder
  324. .on_page_load(move |webview, payload| f(WebviewWindow { webview }, payload));
  325. self
  326. }
  327. /// Creates a new window.
  328. pub fn build(self) -> crate::Result<WebviewWindow<R>> {
  329. let (_window, webview) = self.window_builder.with_webview(self.webview_builder)?;
  330. Ok(WebviewWindow { webview })
  331. }
  332. pub(crate) fn build_internal(
  333. self,
  334. window_labels: &[String],
  335. webview_labels: &[WebviewLabelDef],
  336. ) -> crate::Result<WebviewWindow<R>> {
  337. let (_window, webview) = self.window_builder.with_webview_internal(
  338. self.webview_builder,
  339. window_labels,
  340. webview_labels,
  341. )?;
  342. Ok(WebviewWindow { webview })
  343. }
  344. }
  345. /// Desktop APIs.
  346. #[cfg(desktop)]
  347. impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M> {
  348. /// Sets the menu for the window.
  349. #[must_use]
  350. pub fn menu(mut self, menu: crate::menu::Menu<R>) -> Self {
  351. self.window_builder = self.window_builder.menu(menu);
  352. self
  353. }
  354. /// Show window in the center of the screen.
  355. #[must_use]
  356. pub fn center(mut self) -> Self {
  357. self.window_builder = self.window_builder.center();
  358. self
  359. }
  360. /// The initial position of the window's.
  361. #[must_use]
  362. pub fn position(mut self, x: f64, y: f64) -> Self {
  363. self.window_builder = self.window_builder.position(x, y);
  364. self
  365. }
  366. /// Window size.
  367. #[must_use]
  368. pub fn inner_size(mut self, width: f64, height: f64) -> Self {
  369. self.window_builder = self.window_builder.inner_size(width, height);
  370. self
  371. }
  372. /// Window min inner size.
  373. #[must_use]
  374. pub fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
  375. self.window_builder = self.window_builder.min_inner_size(min_width, min_height);
  376. self
  377. }
  378. /// Window max inner size.
  379. #[must_use]
  380. pub fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
  381. self.window_builder = self.window_builder.max_inner_size(max_width, max_height);
  382. self
  383. }
  384. /// Window inner size constraints.
  385. #[must_use]
  386. pub fn inner_size_constraints(mut self, constraints: WindowSizeConstraints) -> Self {
  387. self.window_builder = self.window_builder.inner_size_constraints(constraints);
  388. self
  389. }
  390. /// Whether the window is resizable or not.
  391. /// When resizable is set to false, native window's maximize button is automatically disabled.
  392. #[must_use]
  393. pub fn resizable(mut self, resizable: bool) -> Self {
  394. self.window_builder = self.window_builder.resizable(resizable);
  395. self
  396. }
  397. /// Whether the window's native maximize button is enabled or not.
  398. /// If resizable is set to false, this setting is ignored.
  399. ///
  400. /// ## Platform-specific
  401. ///
  402. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  403. /// - **Linux / iOS / Android:** Unsupported.
  404. #[must_use]
  405. pub fn maximizable(mut self, maximizable: bool) -> Self {
  406. self.window_builder = self.window_builder.maximizable(maximizable);
  407. self
  408. }
  409. /// Whether the window's native minimize button is enabled or not.
  410. ///
  411. /// ## Platform-specific
  412. ///
  413. /// - **Linux / iOS / Android:** Unsupported.
  414. #[must_use]
  415. pub fn minimizable(mut self, minimizable: bool) -> Self {
  416. self.window_builder = self.window_builder.minimizable(minimizable);
  417. self
  418. }
  419. /// Whether the window's native close button is enabled or not.
  420. ///
  421. /// ## Platform-specific
  422. ///
  423. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  424. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  425. /// - **iOS / Android:** Unsupported.
  426. #[must_use]
  427. pub fn closable(mut self, closable: bool) -> Self {
  428. self.window_builder = self.window_builder.closable(closable);
  429. self
  430. }
  431. /// The title of the window in the title bar.
  432. #[must_use]
  433. pub fn title<S: Into<String>>(mut self, title: S) -> Self {
  434. self.window_builder = self.window_builder.title(title);
  435. self
  436. }
  437. /// Whether to start the window in fullscreen or not.
  438. #[must_use]
  439. pub fn fullscreen(mut self, fullscreen: bool) -> Self {
  440. self.window_builder = self.window_builder.fullscreen(fullscreen);
  441. self
  442. }
  443. /// Sets the window to be initially focused.
  444. #[must_use]
  445. #[deprecated(
  446. since = "1.2.0",
  447. note = "The window is automatically focused by default. This function Will be removed in 2.0.0. Use `focused` instead."
  448. )]
  449. pub fn focus(mut self) -> Self {
  450. self.window_builder = self.window_builder.focused(true);
  451. self
  452. }
  453. /// Whether the window will be initially focused or not.
  454. #[must_use]
  455. pub fn focused(mut self, focused: bool) -> Self {
  456. self.window_builder = self.window_builder.focused(focused);
  457. self
  458. }
  459. /// Whether the window should be maximized upon creation.
  460. #[must_use]
  461. pub fn maximized(mut self, maximized: bool) -> Self {
  462. self.window_builder = self.window_builder.maximized(maximized);
  463. self
  464. }
  465. /// Whether the window should be immediately visible upon creation.
  466. #[must_use]
  467. pub fn visible(mut self, visible: bool) -> Self {
  468. self.window_builder = self.window_builder.visible(visible);
  469. self
  470. }
  471. /// Forces a theme or uses the system settings if None was provided.
  472. ///
  473. /// ## Platform-specific
  474. ///
  475. /// - **macOS**: Only supported on macOS 10.14+.
  476. #[must_use]
  477. pub fn theme(mut self, theme: Option<crate::Theme>) -> Self {
  478. self.window_builder = self.window_builder.theme(theme);
  479. self
  480. }
  481. /// Whether the window should be transparent. If this is true, writing colors
  482. /// with alpha values different than `1.0` will produce a transparent window.
  483. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  484. #[cfg_attr(
  485. docsrs,
  486. doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
  487. )]
  488. #[must_use]
  489. pub fn transparent(mut self, transparent: bool) -> Self {
  490. self.window_builder = self.window_builder.transparent(transparent);
  491. self.webview_builder = self.webview_builder.transparent(transparent);
  492. self
  493. }
  494. /// Whether the window should have borders and bars.
  495. #[must_use]
  496. pub fn decorations(mut self, decorations: bool) -> Self {
  497. self.window_builder = self.window_builder.decorations(decorations);
  498. self
  499. }
  500. /// Whether the window should always be below other windows.
  501. #[must_use]
  502. pub fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
  503. self.window_builder = self.window_builder.always_on_bottom(always_on_bottom);
  504. self
  505. }
  506. /// Whether the window should always be on top of other windows.
  507. #[must_use]
  508. pub fn always_on_top(mut self, always_on_top: bool) -> Self {
  509. self.window_builder = self.window_builder.always_on_top(always_on_top);
  510. self
  511. }
  512. /// Whether the window will be visible on all workspaces or virtual desktops.
  513. #[must_use]
  514. pub fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
  515. self.window_builder = self
  516. .window_builder
  517. .visible_on_all_workspaces(visible_on_all_workspaces);
  518. self
  519. }
  520. /// Prevents the window contents from being captured by other apps.
  521. #[must_use]
  522. pub fn content_protected(mut self, protected: bool) -> Self {
  523. self.window_builder = self.window_builder.content_protected(protected);
  524. self
  525. }
  526. /// Sets the window icon.
  527. pub fn icon(mut self, icon: Image<'a>) -> crate::Result<Self> {
  528. self.window_builder = self.window_builder.icon(icon)?;
  529. Ok(self)
  530. }
  531. /// Sets whether or not the window icon should be hidden from the taskbar.
  532. ///
  533. /// ## Platform-specific
  534. ///
  535. /// - **macOS**: Unsupported.
  536. #[must_use]
  537. pub fn skip_taskbar(mut self, skip: bool) -> Self {
  538. self.window_builder = self.window_builder.skip_taskbar(skip);
  539. self
  540. }
  541. /// Sets whether or not the window has shadow.
  542. ///
  543. /// ## Platform-specific
  544. ///
  545. /// - **Windows:**
  546. /// - `false` has no effect on decorated window, shadows are always ON.
  547. /// - `true` will make ndecorated window have a 1px white border,
  548. /// and on Windows 11, it will have a rounded corners.
  549. /// - **Linux:** Unsupported.
  550. #[must_use]
  551. pub fn shadow(mut self, enable: bool) -> Self {
  552. self.window_builder = self.window_builder.shadow(enable);
  553. self
  554. }
  555. /// Sets a parent to the window to be created.
  556. ///
  557. /// ## Platform-specific
  558. ///
  559. /// - **Windows**: This sets the passed parent as an owner window to the window to be created.
  560. /// From [MSDN owned windows docs](https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows):
  561. /// - An owned window is always above its owner in the z-order.
  562. /// - The system automatically destroys an owned window when its owner is destroyed.
  563. /// - An owned window is hidden when its owner is minimized.
  564. /// - **Linux**: This makes the new window transient for parent, see <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  565. /// - **macOS**: This adds the window as a child of parent, see <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
  566. pub fn parent(mut self, parent: &WebviewWindow<R>) -> crate::Result<Self> {
  567. self.window_builder = self.window_builder.parent(&parent.webview.window())?;
  568. Ok(self)
  569. }
  570. /// Set an owner to the window to be created.
  571. ///
  572. /// From MSDN:
  573. /// - An owned window is always above its owner in the z-order.
  574. /// - The system automatically destroys an owned window when its owner is destroyed.
  575. /// - An owned window is hidden when its owner is minimized.
  576. ///
  577. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
  578. #[cfg(windows)]
  579. pub fn owner(mut self, owner: &WebviewWindow<R>) -> crate::Result<Self> {
  580. self.window_builder = self.window_builder.owner(&owner.webview.window())?;
  581. Ok(self)
  582. }
  583. /// Set an owner to the window to be created.
  584. ///
  585. /// From MSDN:
  586. /// - An owned window is always above its owner in the z-order.
  587. /// - The system automatically destroys an owned window when its owner is destroyed.
  588. /// - An owned window is hidden when its owner is minimized.
  589. ///
  590. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
  591. #[cfg(windows)]
  592. #[must_use]
  593. pub fn owner_raw(mut self, owner: HWND) -> Self {
  594. self.window_builder = self.window_builder.owner_raw(owner);
  595. self
  596. }
  597. /// Sets a parent to the window to be created.
  598. ///
  599. /// A child window has the WS_CHILD style and is confined to the client area of its parent window.
  600. ///
  601. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
  602. #[cfg(windows)]
  603. #[must_use]
  604. pub fn parent_raw(mut self, parent: HWND) -> Self {
  605. self.window_builder = self.window_builder.parent_raw(parent);
  606. self
  607. }
  608. /// Sets a parent to the window to be created.
  609. ///
  610. /// See <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
  611. #[cfg(target_os = "macos")]
  612. #[must_use]
  613. pub fn parent_raw(mut self, parent: *mut std::ffi::c_void) -> Self {
  614. self.window_builder = self.window_builder.parent_raw(parent);
  615. self
  616. }
  617. /// Sets the window to be created transient for parent.
  618. ///
  619. /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  620. #[cfg(any(
  621. target_os = "linux",
  622. target_os = "dragonfly",
  623. target_os = "freebsd",
  624. target_os = "netbsd",
  625. target_os = "openbsd"
  626. ))]
  627. pub fn transient_for(mut self, parent: &WebviewWindow<R>) -> crate::Result<Self> {
  628. self.window_builder = self
  629. .window_builder
  630. .transient_for(&parent.webview.window())?;
  631. Ok(self)
  632. }
  633. /// Sets the window to be created transient for parent.
  634. ///
  635. /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  636. #[cfg(any(
  637. target_os = "linux",
  638. target_os = "dragonfly",
  639. target_os = "freebsd",
  640. target_os = "netbsd",
  641. target_os = "openbsd"
  642. ))]
  643. #[must_use]
  644. pub fn transient_for_raw(mut self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self {
  645. self.window_builder = self.window_builder.transient_for_raw(parent);
  646. self
  647. }
  648. /// Enables or disables drag and drop support.
  649. #[cfg(windows)]
  650. #[must_use]
  651. pub fn drag_and_drop(mut self, enabled: bool) -> Self {
  652. self.window_builder = self.window_builder.drag_and_drop(enabled);
  653. self
  654. }
  655. /// Sets the [`crate::TitleBarStyle`].
  656. #[cfg(target_os = "macos")]
  657. #[must_use]
  658. pub fn title_bar_style(mut self, style: crate::TitleBarStyle) -> Self {
  659. self.window_builder = self.window_builder.title_bar_style(style);
  660. self
  661. }
  662. /// Hide the window title.
  663. #[cfg(target_os = "macos")]
  664. #[must_use]
  665. pub fn hidden_title(mut self, hidden: bool) -> Self {
  666. self.window_builder = self.window_builder.hidden_title(hidden);
  667. self
  668. }
  669. /// Defines the window [tabbing identifier] for macOS.
  670. ///
  671. /// Windows with matching tabbing identifiers will be grouped together.
  672. /// If the tabbing identifier is not set, automatic tabbing will be disabled.
  673. ///
  674. /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
  675. #[cfg(target_os = "macos")]
  676. #[must_use]
  677. pub fn tabbing_identifier(mut self, identifier: &str) -> Self {
  678. self.window_builder = self.window_builder.tabbing_identifier(identifier);
  679. self
  680. }
  681. /// Sets window effects.
  682. ///
  683. /// Requires the window to be transparent.
  684. ///
  685. /// ## Platform-specific:
  686. ///
  687. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  688. /// - **Linux**: Unsupported
  689. pub fn effects(mut self, effects: crate::utils::config::WindowEffectsConfig) -> Self {
  690. self.window_builder = self.window_builder.effects(effects);
  691. self
  692. }
  693. }
  694. /// Webview attributes.
  695. impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M> {
  696. /// Sets whether clicking an inactive window also clicks through to the webview.
  697. #[must_use]
  698. pub fn accept_first_mouse(mut self, accept: bool) -> Self {
  699. self.webview_builder = self.webview_builder.accept_first_mouse(accept);
  700. self
  701. }
  702. /// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
  703. /// but before the HTML document has been parsed and before any other script included by the HTML document is run.
  704. ///
  705. /// Since it runs on all top-level document and child frame page navigations,
  706. /// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
  707. ///
  708. /// # Examples
  709. ///
  710. /// ```rust
  711. /// use tauri::{WebviewWindowBuilder, Runtime};
  712. ///
  713. /// const INIT_SCRIPT: &str = r#"
  714. /// if (window.location.origin === 'https://tauri.app') {
  715. /// console.log("hello world from js init script");
  716. ///
  717. /// window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
  718. /// }
  719. /// "#;
  720. ///
  721. /// fn main() {
  722. /// tauri::Builder::default()
  723. /// .setup(|app| {
  724. /// let webview = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
  725. /// .initialization_script(INIT_SCRIPT)
  726. /// .build()?;
  727. /// Ok(())
  728. /// });
  729. /// }
  730. /// ```
  731. #[must_use]
  732. pub fn initialization_script(mut self, script: &str) -> Self {
  733. self.webview_builder = self.webview_builder.initialization_script(script);
  734. self
  735. }
  736. /// Set the user agent for the webview
  737. #[must_use]
  738. pub fn user_agent(mut self, user_agent: &str) -> Self {
  739. self.webview_builder = self.webview_builder.user_agent(user_agent);
  740. self
  741. }
  742. /// Set additional arguments for the webview.
  743. ///
  744. /// ## Platform-specific
  745. ///
  746. /// - **macOS / Linux / Android / iOS**: Unsupported.
  747. ///
  748. /// ## Warning
  749. ///
  750. /// By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
  751. /// so if you use this method, you also need to disable these components by yourself if you want.
  752. #[must_use]
  753. pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
  754. self.webview_builder = self
  755. .webview_builder
  756. .additional_browser_args(additional_args);
  757. self
  758. }
  759. /// Data directory for the webview.
  760. #[must_use]
  761. pub fn data_directory(mut self, data_directory: PathBuf) -> Self {
  762. self.webview_builder = self.webview_builder.data_directory(data_directory);
  763. self
  764. }
  765. /// Disables the drag and drop handler. This is required to use HTML5 drag and drop APIs on the frontend on Windows.
  766. #[must_use]
  767. pub fn disable_drag_drop_handler(mut self) -> Self {
  768. self.webview_builder = self.webview_builder.disable_drag_drop_handler();
  769. self
  770. }
  771. /// Enables clipboard access for the page rendered on **Linux** and **Windows**.
  772. ///
  773. /// **macOS** doesn't provide such method and is always enabled by default,
  774. /// but you still need to add menu item accelerators to use shortcuts.
  775. #[must_use]
  776. pub fn enable_clipboard_access(mut self) -> Self {
  777. self.webview_builder = self.webview_builder.enable_clipboard_access();
  778. self
  779. }
  780. /// Enable or disable incognito mode for the WebView..
  781. ///
  782. /// ## Platform-specific:
  783. ///
  784. /// **Android**: Unsupported.
  785. #[must_use]
  786. pub fn incognito(mut self, incognito: bool) -> Self {
  787. self.webview_builder = self.webview_builder.incognito(incognito);
  788. self
  789. }
  790. /// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
  791. #[must_use]
  792. pub fn auto_resize(mut self) -> Self {
  793. self.webview_builder = self.webview_builder.auto_resize();
  794. self
  795. }
  796. /// Set a proxy URL for the WebView for all network requests.
  797. ///
  798. /// Must be either a `http://` or a `socks5://` URL.
  799. #[must_use]
  800. pub fn proxy_url(mut self, url: Url) -> Self {
  801. self.webview_builder = self.webview_builder.proxy_url(url);
  802. self
  803. }
  804. /// Whether page zooming by hotkeys is enabled
  805. ///
  806. /// ## Platform-specific:
  807. ///
  808. /// - **Windows**: Controls WebView2's [`IsZoomControlEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2settings?view=webview2-winrt-1.0.2420.47#iszoomcontrolenabled) setting.
  809. /// - **MacOS / Linux**: Injects a polyfill that zooms in and out with `ctrl/command` + `-/=`,
  810. /// 20% in each step, ranging from 20% to 1000%. Requires `webview:allow-set-webview-zoom` permission
  811. ///
  812. /// - **Android / iOS**: Unsupported.
  813. #[must_use]
  814. pub fn zoom_hotkeys_enabled(mut self, enabled: bool) -> Self {
  815. self.webview_builder = self.webview_builder.zoom_hotkeys_enabled(enabled);
  816. self
  817. }
  818. }
  819. /// A type that wraps a [`Window`] together with a [`Webview`].
  820. #[default_runtime(crate::Wry, wry)]
  821. #[derive(Debug)]
  822. pub struct WebviewWindow<R: Runtime> {
  823. pub(crate) webview: Webview<R>,
  824. }
  825. impl<R: Runtime> AsRef<Webview<R>> for WebviewWindow<R> {
  826. fn as_ref(&self) -> &Webview<R> {
  827. &self.webview
  828. }
  829. }
  830. impl<R: Runtime> Clone for WebviewWindow<R> {
  831. fn clone(&self) -> Self {
  832. Self {
  833. webview: self.webview.clone(),
  834. }
  835. }
  836. }
  837. impl<R: Runtime> Eq for WebviewWindow<R> {}
  838. impl<R: Runtime> PartialEq for WebviewWindow<R> {
  839. /// Only use the [`Window`]'s label to compare equality.
  840. fn eq(&self, other: &Self) -> bool {
  841. self.webview.eq(&other.webview)
  842. }
  843. }
  844. impl<R: Runtime> raw_window_handle::HasWindowHandle for WebviewWindow<R> {
  845. fn window_handle(
  846. &self,
  847. ) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
  848. Ok(unsafe {
  849. raw_window_handle::WindowHandle::borrow_raw(self.webview.window().window_handle()?.as_raw())
  850. })
  851. }
  852. }
  853. impl<R: Runtime> raw_window_handle::HasDisplayHandle for WebviewWindow<R> {
  854. fn display_handle(
  855. &self,
  856. ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
  857. self.webview.app_handle.display_handle()
  858. }
  859. }
  860. impl<'de, R: Runtime> CommandArg<'de, R> for WebviewWindow<R> {
  861. /// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
  862. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  863. let webview = command.message.webview();
  864. if webview.window().is_webview_window() {
  865. Ok(Self { webview })
  866. } else {
  867. Err(InvokeError::from("current webview is not a WebviewWindow"))
  868. }
  869. }
  870. }
  871. /// Base webview window functions.
  872. impl<R: Runtime> WebviewWindow<R> {
  873. /// Initializes a [`WebviewWindowBuilder`] with the given window label and webview URL.
  874. ///
  875. /// Data URLs are only supported with the `webview-data-url` feature flag.
  876. pub fn builder<M: Manager<R>, L: Into<String>>(
  877. manager: &M,
  878. label: L,
  879. url: WebviewUrl,
  880. ) -> WebviewWindowBuilder<'_, R, M> {
  881. WebviewWindowBuilder::new(manager, label, url)
  882. }
  883. /// Runs the given closure on the main thread.
  884. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  885. self.webview.run_on_main_thread(f)
  886. }
  887. /// The webview label.
  888. pub fn label(&self) -> &str {
  889. self.webview.label()
  890. }
  891. /// Registers a window event listener.
  892. pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) {
  893. self.webview.window().on_window_event(f);
  894. }
  895. }
  896. /// Menu APIs
  897. #[cfg(desktop)]
  898. impl<R: Runtime> WebviewWindow<R> {
  899. /// Registers a global menu event listener.
  900. ///
  901. /// Note that this handler is called for any menu event,
  902. /// whether it is coming from this window, another window or from the tray icon menu.
  903. ///
  904. /// Also note that this handler will not be called if
  905. /// the window used to register it was closed.
  906. ///
  907. /// # Examples
  908. ///
  909. /// ```
  910. /// use tauri::menu::{Menu, Submenu, MenuItem};
  911. /// use tauri::{WebviewWindowBuilder, WebviewUrl};
  912. ///
  913. /// tauri::Builder::default()
  914. /// .setup(|app| {
  915. /// let handle = app.handle();
  916. /// let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
  917. /// let menu = Menu::with_items(handle, &[
  918. /// &Submenu::with_items(handle, "File", true, &[
  919. /// &save_menu_item,
  920. /// ])?,
  921. /// ])?;
  922. /// let webview_window = WebviewWindowBuilder::new(app, "editor", WebviewUrl::default())
  923. /// .menu(menu)
  924. /// .build()
  925. /// .unwrap();
  926. ///
  927. /// webview_window.on_menu_event(move |window, event| {
  928. /// if event.id == save_menu_item.id() {
  929. /// // save menu item
  930. /// }
  931. /// });
  932. ///
  933. /// Ok(())
  934. /// });
  935. /// ```
  936. pub fn on_menu_event<F: Fn(&crate::Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
  937. &self,
  938. f: F,
  939. ) {
  940. self.webview.window().on_menu_event(f)
  941. }
  942. /// Returns this window menu .
  943. pub fn menu(&self) -> Option<Menu<R>> {
  944. self.webview.window().menu()
  945. }
  946. /// Sets the window menu and returns the previous one.
  947. ///
  948. /// ## Platform-specific:
  949. ///
  950. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  951. /// window, if you need to set it, use [`AppHandle::set_menu`] instead.
  952. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  953. pub fn set_menu(&self, menu: Menu<R>) -> crate::Result<Option<Menu<R>>> {
  954. self.webview.window().set_menu(menu)
  955. }
  956. /// Removes the window menu and returns it.
  957. ///
  958. /// ## Platform-specific:
  959. ///
  960. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  961. /// window, if you need to remove it, use [`AppHandle::remove_menu`] instead.
  962. pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
  963. self.webview.window().remove_menu()
  964. }
  965. /// Hides the window menu.
  966. pub fn hide_menu(&self) -> crate::Result<()> {
  967. self.webview.window().hide_menu()
  968. }
  969. /// Shows the window menu.
  970. pub fn show_menu(&self) -> crate::Result<()> {
  971. self.webview.window().show_menu()
  972. }
  973. /// Shows the window menu.
  974. pub fn is_menu_visible(&self) -> crate::Result<bool> {
  975. self.webview.window().is_menu_visible()
  976. }
  977. /// Shows the specified menu as a context menu at the cursor position.
  978. pub fn popup_menu<M: ContextMenu>(&self, menu: &M) -> crate::Result<()> {
  979. self.webview.window().popup_menu(menu)
  980. }
  981. /// Shows the specified menu as a context menu at the specified position.
  982. ///
  983. /// The position is relative to the window's top-left corner.
  984. pub fn popup_menu_at<M: ContextMenu, P: Into<Position>>(
  985. &self,
  986. menu: &M,
  987. position: P,
  988. ) -> crate::Result<()> {
  989. menu.popup_at(self.webview.window(), position)
  990. }
  991. }
  992. /// Window getters.
  993. impl<R: Runtime> WebviewWindow<R> {
  994. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  995. pub fn scale_factor(&self) -> crate::Result<f64> {
  996. self.webview.window().scale_factor()
  997. }
  998. /// Returns the position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop.
  999. pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1000. self.webview.window().inner_position()
  1001. }
  1002. /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
  1003. pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1004. self.webview.window().outer_position()
  1005. }
  1006. /// Returns the physical size of the window's client area.
  1007. ///
  1008. /// The client area is the content of the window, excluding the title bar and borders.
  1009. pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1010. self.webview.window().inner_size()
  1011. }
  1012. /// Returns the physical size of the entire window.
  1013. ///
  1014. /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
  1015. pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1016. self.webview.window().outer_size()
  1017. }
  1018. /// Gets the window's current fullscreen state.
  1019. pub fn is_fullscreen(&self) -> crate::Result<bool> {
  1020. self.webview.window().is_fullscreen()
  1021. }
  1022. /// Gets the window's current minimized state.
  1023. pub fn is_minimized(&self) -> crate::Result<bool> {
  1024. self.webview.window().is_minimized()
  1025. }
  1026. /// Gets the window's current maximized state.
  1027. pub fn is_maximized(&self) -> crate::Result<bool> {
  1028. self.webview.window().is_maximized()
  1029. }
  1030. /// Gets the window's current focus state.
  1031. pub fn is_focused(&self) -> crate::Result<bool> {
  1032. self.webview.window().is_focused()
  1033. }
  1034. /// Gets the window's current decoration state.
  1035. pub fn is_decorated(&self) -> crate::Result<bool> {
  1036. self.webview.window().is_decorated()
  1037. }
  1038. /// Gets the window's current resizable state.
  1039. pub fn is_resizable(&self) -> crate::Result<bool> {
  1040. self.webview.window().is_resizable()
  1041. }
  1042. /// Gets the window's native maximize button state
  1043. ///
  1044. /// ## Platform-specific
  1045. ///
  1046. /// - **Linux / iOS / Android:** Unsupported.
  1047. pub fn is_maximizable(&self) -> crate::Result<bool> {
  1048. self.webview.window().is_maximizable()
  1049. }
  1050. /// Gets the window's native minimize button state
  1051. ///
  1052. /// ## Platform-specific
  1053. ///
  1054. /// - **Linux / iOS / Android:** Unsupported.
  1055. pub fn is_minimizable(&self) -> crate::Result<bool> {
  1056. self.webview.window().is_minimizable()
  1057. }
  1058. /// Gets the window's native close button state
  1059. ///
  1060. /// ## Platform-specific
  1061. ///
  1062. /// - **Linux / iOS / Android:** Unsupported.
  1063. pub fn is_closable(&self) -> crate::Result<bool> {
  1064. self.webview.window().is_closable()
  1065. }
  1066. /// Gets the window's current visibility state.
  1067. pub fn is_visible(&self) -> crate::Result<bool> {
  1068. self.webview.window().is_visible()
  1069. }
  1070. /// Gets the window's current title.
  1071. pub fn title(&self) -> crate::Result<String> {
  1072. self.webview.window().title()
  1073. }
  1074. /// Returns the monitor on which the window currently resides.
  1075. ///
  1076. /// Returns None if current monitor can't be detected.
  1077. pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
  1078. self.webview.window().current_monitor()
  1079. }
  1080. /// Returns the primary monitor of the system.
  1081. ///
  1082. /// Returns None if it can't identify any monitor as a primary one.
  1083. pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
  1084. self.webview.window().primary_monitor()
  1085. }
  1086. /// Returns the monitor that contains the given point.
  1087. pub fn monitor_from_point(&self, x: f64, y: f64) -> crate::Result<Option<Monitor>> {
  1088. self.webview.window().monitor_from_point(x, y)
  1089. }
  1090. /// Returns the list of all the monitors available on the system.
  1091. pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
  1092. self.webview.window().available_monitors()
  1093. }
  1094. /// Returns the native handle that is used by this window.
  1095. #[cfg(target_os = "macos")]
  1096. pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> {
  1097. self.webview.window().ns_window()
  1098. }
  1099. /// Returns the pointer to the content view of this window.
  1100. #[cfg(target_os = "macos")]
  1101. pub fn ns_view(&self) -> crate::Result<*mut std::ffi::c_void> {
  1102. self.webview.window().ns_view()
  1103. }
  1104. /// Returns the native handle that is used by this window.
  1105. #[cfg(windows)]
  1106. pub fn hwnd(&self) -> crate::Result<HWND> {
  1107. self.webview.window().hwnd()
  1108. }
  1109. /// Returns the `ApplicationWindow` from gtk crate that is used by this window.
  1110. ///
  1111. /// Note that this type can only be used on the main thread.
  1112. #[cfg(any(
  1113. target_os = "linux",
  1114. target_os = "dragonfly",
  1115. target_os = "freebsd",
  1116. target_os = "netbsd",
  1117. target_os = "openbsd"
  1118. ))]
  1119. pub fn gtk_window(&self) -> crate::Result<gtk::ApplicationWindow> {
  1120. self.webview.window().gtk_window()
  1121. }
  1122. /// Returns the vertical [`gtk::Box`] that is added by default as the sole child of this window.
  1123. ///
  1124. /// Note that this type can only be used on the main thread.
  1125. #[cfg(any(
  1126. target_os = "linux",
  1127. target_os = "dragonfly",
  1128. target_os = "freebsd",
  1129. target_os = "netbsd",
  1130. target_os = "openbsd"
  1131. ))]
  1132. pub fn default_vbox(&self) -> crate::Result<gtk::Box> {
  1133. self.webview.window().default_vbox()
  1134. }
  1135. /// Returns the current window theme.
  1136. ///
  1137. /// ## Platform-specific
  1138. ///
  1139. /// - **macOS**: Only supported on macOS 10.14+.
  1140. pub fn theme(&self) -> crate::Result<crate::Theme> {
  1141. self.webview.window().theme()
  1142. }
  1143. }
  1144. /// Desktop window getters.
  1145. #[cfg(desktop)]
  1146. impl<R: Runtime> WebviewWindow<R> {
  1147. /// Get the cursor position relative to the top-left hand corner of the desktop.
  1148. ///
  1149. /// Note that the top-left hand corner of the desktop is not necessarily the same as the screen.
  1150. /// If the user uses a desktop with multiple monitors,
  1151. /// the top-left hand corner of the desktop is the top-left hand corner of the main monitor on Windows and macOS
  1152. /// or the top-left of the leftmost monitor on X11.
  1153. ///
  1154. /// The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region.
  1155. pub fn cursor_position(&self) -> crate::Result<PhysicalPosition<f64>> {
  1156. self.webview.cursor_position()
  1157. }
  1158. }
  1159. /// Desktop window setters and actions.
  1160. #[cfg(desktop)]
  1161. impl<R: Runtime> WebviewWindow<R> {
  1162. /// Centers the window.
  1163. pub fn center(&self) -> crate::Result<()> {
  1164. self.webview.window().center()
  1165. }
  1166. /// Requests user attention to the window, this has no effect if the application
  1167. /// is already focused. How requesting for user attention manifests is platform dependent,
  1168. /// see `UserAttentionType` for details.
  1169. ///
  1170. /// Providing `None` will unset the request for user attention. Unsetting the request for
  1171. /// user attention might not be done automatically by the WM when the window receives input.
  1172. ///
  1173. /// ## Platform-specific
  1174. ///
  1175. /// - **macOS:** `None` has no effect.
  1176. /// - **Linux:** Urgency levels have the same effect.
  1177. pub fn request_user_attention(
  1178. &self,
  1179. request_type: Option<UserAttentionType>,
  1180. ) -> crate::Result<()> {
  1181. self.webview.window().request_user_attention(request_type)
  1182. }
  1183. /// Determines if this window should be resizable.
  1184. /// When resizable is set to false, native window's maximize button is automatically disabled.
  1185. pub fn set_resizable(&self, resizable: bool) -> crate::Result<()> {
  1186. self.webview.window().set_resizable(resizable)
  1187. }
  1188. /// Determines if this window's native maximize button should be enabled.
  1189. /// If resizable is set to false, this setting is ignored.
  1190. ///
  1191. /// ## Platform-specific
  1192. ///
  1193. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  1194. /// - **Linux / iOS / Android:** Unsupported.
  1195. pub fn set_maximizable(&self, maximizable: bool) -> crate::Result<()> {
  1196. self.webview.window().set_maximizable(maximizable)
  1197. }
  1198. /// Determines if this window's native minimize button should be enabled.
  1199. ///
  1200. /// ## Platform-specific
  1201. ///
  1202. /// - **Linux / iOS / Android:** Unsupported.
  1203. pub fn set_minimizable(&self, minimizable: bool) -> crate::Result<()> {
  1204. self.webview.window().set_minimizable(minimizable)
  1205. }
  1206. /// Determines if this window's native close button should be enabled.
  1207. ///
  1208. /// ## Platform-specific
  1209. ///
  1210. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  1211. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  1212. /// - **iOS / Android:** Unsupported.
  1213. pub fn set_closable(&self, closable: bool) -> crate::Result<()> {
  1214. self.webview.window().set_closable(closable)
  1215. }
  1216. /// Set this window's title.
  1217. pub fn set_title(&self, title: &str) -> crate::Result<()> {
  1218. self.webview.window().set_title(title)
  1219. }
  1220. /// Maximizes this window.
  1221. pub fn maximize(&self) -> crate::Result<()> {
  1222. self.webview.window().maximize()
  1223. }
  1224. /// Un-maximizes this window.
  1225. pub fn unmaximize(&self) -> crate::Result<()> {
  1226. self.webview.window().unmaximize()
  1227. }
  1228. /// Minimizes this window.
  1229. pub fn minimize(&self) -> crate::Result<()> {
  1230. self.webview.window().minimize()
  1231. }
  1232. /// Un-minimizes this window.
  1233. pub fn unminimize(&self) -> crate::Result<()> {
  1234. self.webview.window().unminimize()
  1235. }
  1236. /// Show this window.
  1237. pub fn show(&self) -> crate::Result<()> {
  1238. self.webview.window().show()
  1239. }
  1240. /// Hide this window.
  1241. pub fn hide(&self) -> crate::Result<()> {
  1242. self.webview.window().hide()
  1243. }
  1244. /// Closes this window. It emits [`crate::RunEvent::CloseRequested`] first like a user-initiated close request so you can intercept it.
  1245. pub fn close(&self) -> crate::Result<()> {
  1246. self.webview.window().close()
  1247. }
  1248. /// Destroys this window. Similar to [`Self::close`] but does not emit any events and force close the window instead.
  1249. pub fn destroy(&self) -> crate::Result<()> {
  1250. self.webview.window().destroy()
  1251. }
  1252. /// Determines if this window should be [decorated].
  1253. ///
  1254. /// [decorated]: https://en.wikipedia.org/wiki/Window_(computing)#Window_decoration
  1255. pub fn set_decorations(&self, decorations: bool) -> crate::Result<()> {
  1256. self.webview.window().set_decorations(decorations)
  1257. }
  1258. /// Determines if this window should have shadow.
  1259. ///
  1260. /// ## Platform-specific
  1261. ///
  1262. /// - **Windows:**
  1263. /// - `false` has no effect on decorated window, shadow are always ON.
  1264. /// - `true` will make ndecorated window have a 1px white border,
  1265. /// and on Windows 11, it will have a rounded corners.
  1266. /// - **Linux:** Unsupported.
  1267. pub fn set_shadow(&self, enable: bool) -> crate::Result<()> {
  1268. self.webview.window().set_shadow(enable)
  1269. }
  1270. /// Sets window effects, pass [`None`] to clear any effects applied if possible.
  1271. ///
  1272. /// Requires the window to be transparent.
  1273. ///
  1274. /// See [`crate::window::EffectsBuilder`] for a convenient builder for [`crate::utils::config::WindowEffectsConfig`].
  1275. ///
  1276. ///
  1277. /// ```rust,no_run
  1278. /// use tauri::{Manager, window::{Color, Effect, EffectState, EffectsBuilder}};
  1279. /// tauri::Builder::default()
  1280. /// .setup(|app| {
  1281. /// let webview_window = app.get_webview_window("main").unwrap();
  1282. /// webview_window.set_effects(
  1283. /// EffectsBuilder::new()
  1284. /// .effect(Effect::Popover)
  1285. /// .state(EffectState::Active)
  1286. /// .radius(5.)
  1287. /// .color(Color(0, 0, 0, 255))
  1288. /// .build(),
  1289. /// )?;
  1290. /// Ok(())
  1291. /// });
  1292. /// ```
  1293. ///
  1294. /// ## Platform-specific:
  1295. ///
  1296. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  1297. /// - **Linux**: Unsupported
  1298. pub fn set_effects<E: Into<Option<crate::utils::config::WindowEffectsConfig>>>(
  1299. &self,
  1300. effects: E,
  1301. ) -> crate::Result<()> {
  1302. self.webview.window().set_effects(effects)
  1303. }
  1304. /// Determines if this window should always be below other windows.
  1305. pub fn set_always_on_bottom(&self, always_on_bottom: bool) -> crate::Result<()> {
  1306. self.webview.window().set_always_on_bottom(always_on_bottom)
  1307. }
  1308. /// Determines if this window should always be on top of other windows.
  1309. pub fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> {
  1310. self.webview.window().set_always_on_top(always_on_top)
  1311. }
  1312. /// Sets whether the window should be visible on all workspaces or virtual desktops.
  1313. pub fn set_visible_on_all_workspaces(
  1314. &self,
  1315. visible_on_all_workspaces: bool,
  1316. ) -> crate::Result<()> {
  1317. self
  1318. .webview
  1319. .window()
  1320. .set_visible_on_all_workspaces(visible_on_all_workspaces)
  1321. }
  1322. /// Prevents the window contents from being captured by other apps.
  1323. pub fn set_content_protected(&self, protected: bool) -> crate::Result<()> {
  1324. self.webview.window().set_content_protected(protected)
  1325. }
  1326. /// Resizes this window.
  1327. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
  1328. self.webview.window().set_size(size.into())
  1329. }
  1330. /// Sets this window's minimum inner size.
  1331. pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1332. self.webview.window().set_min_size(size.map(|s| s.into()))
  1333. }
  1334. /// Sets this window's maximum inner size.
  1335. pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1336. self.webview.window().set_max_size(size.map(|s| s.into()))
  1337. }
  1338. /// Sets this window's minimum inner width.
  1339. pub fn set_size_constraints(&self, constriants: WindowSizeConstraints) -> crate::Result<()> {
  1340. self.webview.window().set_size_constraints(constriants)
  1341. }
  1342. /// Sets this window's position.
  1343. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1344. self.webview.window().set_position(position)
  1345. }
  1346. /// Determines if this window should be fullscreen.
  1347. pub fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
  1348. self.webview.window().set_fullscreen(fullscreen)
  1349. }
  1350. /// Bring the window to front and focus.
  1351. pub fn set_focus(&self) -> crate::Result<()> {
  1352. self.webview.window().set_focus()
  1353. }
  1354. /// Sets this window' icon.
  1355. pub fn set_icon(&self, icon: Image<'_>) -> crate::Result<()> {
  1356. self.webview.window().set_icon(icon)
  1357. }
  1358. /// Whether to hide the window icon from the taskbar or not.
  1359. ///
  1360. /// ## Platform-specific
  1361. ///
  1362. /// - **macOS:** Unsupported.
  1363. pub fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> {
  1364. self.webview.window().set_skip_taskbar(skip)
  1365. }
  1366. /// Grabs the cursor, preventing it from leaving the window.
  1367. ///
  1368. /// There's no guarantee that the cursor will be hidden. You should
  1369. /// hide it by yourself if you want so.
  1370. ///
  1371. /// ## Platform-specific
  1372. ///
  1373. /// - **Linux:** Unsupported.
  1374. /// - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
  1375. pub fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
  1376. self.webview.window().set_cursor_grab(grab)
  1377. }
  1378. /// Modifies the cursor's visibility.
  1379. ///
  1380. /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
  1381. ///
  1382. /// ## Platform-specific
  1383. ///
  1384. /// - **Windows:** The cursor is only hidden within the confines of the window.
  1385. /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
  1386. /// outside of the window.
  1387. pub fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
  1388. self.webview.window().set_cursor_visible(visible)
  1389. }
  1390. /// Modifies the cursor icon of the window.
  1391. pub fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
  1392. self.webview.window().set_cursor_icon(icon)
  1393. }
  1394. /// Changes the position of the cursor in window coordinates.
  1395. pub fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1396. self.webview.window().set_cursor_position(position)
  1397. }
  1398. /// Ignores the window cursor events.
  1399. pub fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
  1400. self.webview.window().set_ignore_cursor_events(ignore)
  1401. }
  1402. /// Starts dragging the window.
  1403. pub fn start_dragging(&self) -> crate::Result<()> {
  1404. self.webview.window().start_dragging()
  1405. }
  1406. /// Sets the taskbar progress state.
  1407. ///
  1408. /// ## Platform-specific
  1409. ///
  1410. /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window.
  1411. /// - **Linux**: Only supported desktop environments with `libunity` (e.g. GNOME).
  1412. /// - **iOS / Android:** Unsupported.
  1413. pub fn set_progress_bar(
  1414. &self,
  1415. progress_state: crate::window::ProgressBarState,
  1416. ) -> crate::Result<()> {
  1417. self.webview.window().set_progress_bar(progress_state)
  1418. }
  1419. /// Sets the title bar style. **macOS only**.
  1420. pub fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> crate::Result<()> {
  1421. self.webview.window().set_title_bar_style(style)
  1422. }
  1423. }
  1424. /// Desktop webview setters and actions.
  1425. #[cfg(desktop)]
  1426. impl<R: Runtime> WebviewWindow<R> {
  1427. /// Opens the dialog to prints the contents of the webview.
  1428. /// Currently only supported on macOS on `wry`.
  1429. /// `window.print()` works on all platforms.
  1430. pub fn print(&self) -> crate::Result<()> {
  1431. self.webview.print()
  1432. }
  1433. }
  1434. /// Webview APIs.
  1435. impl<R: Runtime> WebviewWindow<R> {
  1436. /// Executes a closure, providing it with the webview handle that is specific to the current platform.
  1437. ///
  1438. /// The closure is executed on the main thread.
  1439. ///
  1440. /// # Examples
  1441. ///
  1442. /// ```rust,no_run
  1443. /// #[cfg(target_os = "macos")]
  1444. /// #[macro_use]
  1445. /// extern crate objc;
  1446. /// use tauri::Manager;
  1447. ///
  1448. /// fn main() {
  1449. /// tauri::Builder::default()
  1450. /// .setup(|app| {
  1451. /// let main_webview = app.get_webview_window("main").unwrap();
  1452. /// main_webview.with_webview(|webview| {
  1453. /// #[cfg(target_os = "linux")]
  1454. /// {
  1455. /// // see https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/struct.WebView.html
  1456. /// // and https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/trait.WebViewExt.html
  1457. /// use webkit2gtk::WebViewExt;
  1458. /// webview.inner().set_zoom_level(4.);
  1459. /// }
  1460. ///
  1461. /// #[cfg(windows)]
  1462. /// unsafe {
  1463. /// // see https://docs.rs/webview2-com/0.19.1/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html
  1464. /// webview.controller().SetZoomFactor(4.).unwrap();
  1465. /// }
  1466. ///
  1467. /// #[cfg(target_os = "macos")]
  1468. /// unsafe {
  1469. /// let () = msg_send![webview.inner(), setPageZoom: 4.];
  1470. /// let () = msg_send![webview.controller(), removeAllUserScripts];
  1471. /// let bg_color: cocoa::base::id = msg_send![class!(NSColor), colorWithDeviceRed:0.5 green:0.2 blue:0.4 alpha:1.];
  1472. /// let () = msg_send![webview.ns_window(), setBackgroundColor: bg_color];
  1473. /// }
  1474. ///
  1475. /// #[cfg(target_os = "android")]
  1476. /// {
  1477. /// use jni::objects::JValue;
  1478. /// webview.jni_handle().exec(|env, _, webview| {
  1479. /// env.call_method(webview, "zoomBy", "(F)V", &[JValue::Float(4.)]).unwrap();
  1480. /// })
  1481. /// }
  1482. /// });
  1483. /// Ok(())
  1484. /// });
  1485. /// }
  1486. /// ```
  1487. #[cfg(feature = "wry")]
  1488. #[cfg_attr(docsrs, doc(feature = "wry"))]
  1489. pub fn with_webview<F: FnOnce(crate::webview::PlatformWebview) + Send + 'static>(
  1490. &self,
  1491. f: F,
  1492. ) -> crate::Result<()> {
  1493. self.webview.with_webview(f)
  1494. }
  1495. /// Returns the current url of the webview.
  1496. pub fn url(&self) -> crate::Result<Url> {
  1497. self.webview.url()
  1498. }
  1499. /// Navigates the webview to the defined url.
  1500. pub fn navigate(&mut self, url: Url) -> crate::Result<()> {
  1501. self.webview.navigate(url)
  1502. }
  1503. /// Handles this window receiving an [`crate::webview::InvokeRequest`].
  1504. pub fn on_message(
  1505. self,
  1506. request: crate::webview::InvokeRequest,
  1507. responder: Box<OwnedInvokeResponder<R>>,
  1508. ) {
  1509. self.webview.on_message(request, responder)
  1510. }
  1511. /// Evaluates JavaScript on this window.
  1512. pub fn eval(&self, js: &str) -> crate::Result<()> {
  1513. self.webview.eval(js)
  1514. }
  1515. /// Opens the developer tools window (Web Inspector).
  1516. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1517. ///
  1518. /// ## Platform-specific
  1519. ///
  1520. /// - **macOS:** Only supported on macOS 10.15+.
  1521. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1522. ///
  1523. /// # Examples
  1524. ///
  1525. /// ```rust,no_run
  1526. /// use tauri::Manager;
  1527. /// tauri::Builder::default()
  1528. /// .setup(|app| {
  1529. /// #[cfg(debug_assertions)]
  1530. /// app.get_webview_window("main").unwrap().open_devtools();
  1531. /// Ok(())
  1532. /// });
  1533. /// ```
  1534. #[cfg(any(debug_assertions, feature = "devtools"))]
  1535. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1536. pub fn open_devtools(&self) {
  1537. self.webview.open_devtools();
  1538. }
  1539. /// Closes the developer tools window (Web Inspector).
  1540. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1541. ///
  1542. /// ## Platform-specific
  1543. ///
  1544. /// - **macOS:** Only supported on macOS 10.15+.
  1545. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1546. /// - **Windows:** Unsupported.
  1547. ///
  1548. /// # Examples
  1549. ///
  1550. /// ```rust,no_run
  1551. /// use tauri::Manager;
  1552. /// tauri::Builder::default()
  1553. /// .setup(|app| {
  1554. /// #[cfg(debug_assertions)]
  1555. /// {
  1556. /// let webview = app.get_webview_window("main").unwrap();
  1557. /// webview.open_devtools();
  1558. /// std::thread::spawn(move || {
  1559. /// std::thread::sleep(std::time::Duration::from_secs(10));
  1560. /// webview.close_devtools();
  1561. /// });
  1562. /// }
  1563. /// Ok(())
  1564. /// });
  1565. /// ```
  1566. #[cfg(any(debug_assertions, feature = "devtools"))]
  1567. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1568. pub fn close_devtools(&self) {
  1569. self.webview.close_devtools();
  1570. }
  1571. /// Checks if the developer tools window (Web Inspector) is opened.
  1572. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1573. ///
  1574. /// ## Platform-specific
  1575. ///
  1576. /// - **macOS:** Only supported on macOS 10.15+.
  1577. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1578. /// - **Windows:** Unsupported.
  1579. ///
  1580. /// # Examples
  1581. ///
  1582. /// ```rust,no_run
  1583. /// use tauri::Manager;
  1584. /// tauri::Builder::default()
  1585. /// .setup(|app| {
  1586. /// #[cfg(debug_assertions)]
  1587. /// {
  1588. /// let webview = app.get_webview_window("main").unwrap();
  1589. /// if !webview.is_devtools_open() {
  1590. /// webview.open_devtools();
  1591. /// }
  1592. /// }
  1593. /// Ok(())
  1594. /// });
  1595. /// ```
  1596. #[cfg(any(debug_assertions, feature = "devtools"))]
  1597. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1598. pub fn is_devtools_open(&self) -> bool {
  1599. self.webview.is_devtools_open()
  1600. }
  1601. /// Set the webview zoom level
  1602. ///
  1603. /// ## Platform-specific:
  1604. ///
  1605. /// - **Android**: Not supported.
  1606. /// - **macOS**: available on macOS 11+ only.
  1607. /// - **iOS**: available on iOS 14+ only.
  1608. pub fn set_zoom(&self, scale_factor: f64) -> crate::Result<()> {
  1609. self.webview.set_zoom(scale_factor)
  1610. }
  1611. }
  1612. impl<R: Runtime> Listener<R> for WebviewWindow<R> {
  1613. /// Listen to an event on this webview window.
  1614. ///
  1615. /// # Examples
  1616. ///
  1617. /// ```
  1618. /// use tauri::{Manager, Listener};
  1619. ///
  1620. /// tauri::Builder::default()
  1621. /// .setup(|app| {
  1622. /// let webview_window = app.get_webview_window("main").unwrap();
  1623. /// webview_window.listen("component-loaded", move |event| {
  1624. /// println!("window just loaded a component");
  1625. /// });
  1626. ///
  1627. /// Ok(())
  1628. /// });
  1629. /// ```
  1630. fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1631. where
  1632. F: Fn(Event) + Send + 'static,
  1633. {
  1634. self.manager().listen(
  1635. event.into(),
  1636. EventTarget::WebviewWindow {
  1637. label: self.label().to_string(),
  1638. },
  1639. handler,
  1640. )
  1641. }
  1642. /// Listen to an event on this window webview only once.
  1643. ///
  1644. /// See [`Self::listen`] for more information.
  1645. fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1646. where
  1647. F: FnOnce(Event) + Send + 'static,
  1648. {
  1649. self.manager().once(
  1650. event.into(),
  1651. EventTarget::WebviewWindow {
  1652. label: self.label().to_string(),
  1653. },
  1654. handler,
  1655. )
  1656. }
  1657. /// Unlisten to an event on this webview window.
  1658. ///
  1659. /// # Examples
  1660. /// ```
  1661. /// use tauri::{Manager, Listener};
  1662. ///
  1663. /// tauri::Builder::default()
  1664. /// .setup(|app| {
  1665. /// let webview_window = app.get_webview_window("main").unwrap();
  1666. /// let webview_window_ = webview_window.clone();
  1667. /// let handler = webview_window.listen("component-loaded", move |event| {
  1668. /// println!("webview_window just loaded a component");
  1669. ///
  1670. /// // we no longer need to listen to the event
  1671. /// // we also could have used `webview_window.once` instead
  1672. /// webview_window_.unlisten(event.id());
  1673. /// });
  1674. ///
  1675. /// // stop listening to the event when you do not need it anymore
  1676. /// webview_window.unlisten(handler);
  1677. ///
  1678. /// Ok(())
  1679. /// });
  1680. /// ```
  1681. fn unlisten(&self, id: EventId) {
  1682. self.manager().unlisten(id)
  1683. }
  1684. }
  1685. impl<R: Runtime> Emitter<R> for WebviewWindow<R> {
  1686. /// Emits an event to all [targets](EventTarget).
  1687. ///
  1688. /// # Examples
  1689. /// ```
  1690. /// use tauri::Emitter;
  1691. ///
  1692. /// #[tauri::command]
  1693. /// fn synchronize(window: tauri::WebviewWindow) {
  1694. /// // emits the synchronized event to all webviews
  1695. /// window.emit("synchronized", ());
  1696. /// }
  1697. /// ```
  1698. fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> crate::Result<()> {
  1699. self.manager().emit(event, payload)
  1700. }
  1701. /// Emits an event to all [targets](EventTarget) matching the given target.
  1702. ///
  1703. /// # Examples
  1704. /// ```
  1705. /// use tauri::{Emitter, EventTarget};
  1706. ///
  1707. /// #[tauri::command]
  1708. /// fn download(window: tauri::WebviewWindow) {
  1709. /// for i in 1..100 {
  1710. /// std::thread::sleep(std::time::Duration::from_millis(150));
  1711. /// // emit a download progress event to all listeners
  1712. /// window.emit_to(EventTarget::any(), "download-progress", i);
  1713. /// // emit an event to listeners that used App::listen or AppHandle::listen
  1714. /// window.emit_to(EventTarget::app(), "download-progress", i);
  1715. /// // emit an event to any webview/window/webviewWindow matching the given label
  1716. /// window.emit_to("updater", "download-progress", i); // similar to using EventTarget::labeled
  1717. /// window.emit_to(EventTarget::labeled("updater"), "download-progress", i);
  1718. /// // emit an event to listeners that used WebviewWindow::listen
  1719. /// window.emit_to(EventTarget::webview_window("updater"), "download-progress", i);
  1720. /// }
  1721. /// }
  1722. /// ```
  1723. fn emit_to<I, S>(&self, target: I, event: &str, payload: S) -> crate::Result<()>
  1724. where
  1725. I: Into<EventTarget>,
  1726. S: Serialize + Clone,
  1727. {
  1728. self.manager().emit_to(target, event, payload)
  1729. }
  1730. /// Emits an event to all [targets](EventTarget) based on the given filter.
  1731. ///
  1732. /// # Examples
  1733. /// ```
  1734. /// use tauri::{Emitter, EventTarget};
  1735. ///
  1736. /// #[tauri::command]
  1737. /// fn download(window: tauri::WebviewWindow) {
  1738. /// for i in 1..100 {
  1739. /// std::thread::sleep(std::time::Duration::from_millis(150));
  1740. /// // emit a download progress event to the updater window
  1741. /// window.emit_filter("download-progress", i, |t| match t {
  1742. /// EventTarget::WebviewWindow { label } => label == "main",
  1743. /// _ => false,
  1744. /// });
  1745. /// }
  1746. /// }
  1747. /// ```
  1748. fn emit_filter<S, F>(&self, event: &str, payload: S, filter: F) -> crate::Result<()>
  1749. where
  1750. S: Serialize + Clone,
  1751. F: Fn(&EventTarget) -> bool,
  1752. {
  1753. self.manager().emit_filter(event, payload, filter)
  1754. }
  1755. }
  1756. impl<R: Runtime> Manager<R> for WebviewWindow<R> {
  1757. fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
  1758. self
  1759. .webview
  1760. .resources_table
  1761. .lock()
  1762. .expect("poisoned window resources table")
  1763. }
  1764. }
  1765. impl<R: Runtime> ManagerBase<R> for WebviewWindow<R> {
  1766. fn manager(&self) -> &AppManager<R> {
  1767. self.webview.manager()
  1768. }
  1769. fn manager_owned(&self) -> Arc<AppManager<R>> {
  1770. self.webview.manager_owned()
  1771. }
  1772. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  1773. self.webview.runtime()
  1774. }
  1775. fn managed_app_handle(&self) -> &AppHandle<R> {
  1776. self.webview.managed_app_handle()
  1777. }
  1778. }