webview_window.rs 56 KB

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