mod.rs 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! The Tauri window types and functions.
  5. pub(crate) mod plugin;
  6. use http::HeaderMap;
  7. pub use tauri_runtime::window::PageLoadEvent;
  8. pub use tauri_utils::{config::Color, WindowEffect as Effect, WindowEffectState as EffectState};
  9. use url::Url;
  10. #[cfg(target_os = "macos")]
  11. use crate::TitleBarStyle;
  12. use crate::{
  13. app::{AppHandle, UriSchemeResponder},
  14. command::{CommandArg, CommandItem},
  15. event::{EmitArgs, Event, EventId},
  16. ipc::{
  17. CallbackFn, Invoke, InvokeBody, InvokeError, InvokeMessage, InvokeResolver,
  18. OwnedInvokeResponder,
  19. },
  20. manager::WindowManager,
  21. runtime::{
  22. monitor::Monitor as RuntimeMonitor,
  23. webview::{WebviewAttributes, WindowBuilder as _},
  24. window::{
  25. dpi::{PhysicalPosition, PhysicalSize},
  26. DetachedWindow, PendingWindow,
  27. },
  28. Dispatch, RuntimeHandle,
  29. },
  30. sealed::ManagerBase,
  31. sealed::RuntimeOrDispatch,
  32. utils::config::{WindowConfig, WindowEffectsConfig, WindowUrl},
  33. EventLoopMessage, Manager, Runtime, Theme, WindowEvent,
  34. };
  35. #[cfg(desktop)]
  36. use crate::{
  37. menu::{ContextMenu, Menu, MenuId},
  38. runtime::{
  39. window::dpi::{Position, Size},
  40. UserAttentionType,
  41. },
  42. CursorIcon, Icon,
  43. };
  44. use serde::Serialize;
  45. #[cfg(windows)]
  46. use windows::Win32::Foundation::HWND;
  47. use tauri_macros::default_runtime;
  48. use std::{
  49. borrow::Cow,
  50. collections::{HashMap, HashSet},
  51. fmt,
  52. hash::{Hash, Hasher},
  53. path::PathBuf,
  54. sync::{Arc, Mutex},
  55. };
  56. pub(crate) type WebResourceRequestHandler =
  57. dyn Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync;
  58. pub(crate) type NavigationHandler = dyn Fn(&Url) -> bool + Send;
  59. pub(crate) type UriSchemeProtocolHandler =
  60. Box<dyn Fn(http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync>;
  61. pub(crate) type OnPageLoad<R> = dyn Fn(Window<R>, PageLoadPayload<'_>) + Send + Sync + 'static;
  62. #[derive(Clone, Serialize)]
  63. struct WindowCreatedEvent {
  64. label: String,
  65. }
  66. /// The payload for the [`WindowBuilder::on_page_load`] hook.
  67. #[derive(Debug, Clone)]
  68. pub struct PageLoadPayload<'a> {
  69. pub(crate) url: &'a Url,
  70. pub(crate) event: PageLoadEvent,
  71. }
  72. impl<'a> PageLoadPayload<'a> {
  73. /// The page URL.
  74. pub fn url(&self) -> &'a Url {
  75. self.url
  76. }
  77. /// The page load event.
  78. pub fn event(&self) -> PageLoadEvent {
  79. self.event
  80. }
  81. }
  82. /// Monitor descriptor.
  83. #[derive(Debug, Clone, Serialize)]
  84. #[serde(rename_all = "camelCase")]
  85. pub struct Monitor {
  86. pub(crate) name: Option<String>,
  87. pub(crate) size: PhysicalSize<u32>,
  88. pub(crate) position: PhysicalPosition<i32>,
  89. pub(crate) scale_factor: f64,
  90. }
  91. impl From<RuntimeMonitor> for Monitor {
  92. fn from(monitor: RuntimeMonitor) -> Self {
  93. Self {
  94. name: monitor.name,
  95. size: monitor.size,
  96. position: monitor.position,
  97. scale_factor: monitor.scale_factor,
  98. }
  99. }
  100. }
  101. impl Monitor {
  102. /// Returns a human-readable name of the monitor.
  103. /// Returns None if the monitor doesn't exist anymore.
  104. pub fn name(&self) -> Option<&String> {
  105. self.name.as_ref()
  106. }
  107. /// Returns the monitor's resolution.
  108. pub fn size(&self) -> &PhysicalSize<u32> {
  109. &self.size
  110. }
  111. /// Returns the top-left corner position of the monitor relative to the larger full screen area.
  112. pub fn position(&self) -> &PhysicalPosition<i32> {
  113. &self.position
  114. }
  115. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  116. pub fn scale_factor(&self) -> f64 {
  117. self.scale_factor
  118. }
  119. }
  120. /// A builder for a webview window managed by Tauri.
  121. #[default_runtime(crate::Wry, wry)]
  122. pub struct WindowBuilder<'a, R: Runtime> {
  123. manager: WindowManager<R>,
  124. runtime: RuntimeOrDispatch<'a, R>,
  125. app_handle: AppHandle<R>,
  126. label: String,
  127. pub(crate) window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder,
  128. #[cfg(desktop)]
  129. pub(crate) menu: Option<Menu<R>>,
  130. pub(crate) webview_attributes: WebviewAttributes,
  131. web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
  132. navigation_handler: Option<Box<NavigationHandler>>,
  133. on_page_load_handler: Option<Box<OnPageLoad<R>>>,
  134. #[cfg(desktop)]
  135. on_menu_event: Option<crate::app::GlobalMenuEventListener<Window<R>>>,
  136. }
  137. impl<'a, R: Runtime> fmt::Debug for WindowBuilder<'a, R> {
  138. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  139. f.debug_struct("WindowBuilder")
  140. .field("manager", &self.manager)
  141. .field("app_handle", &self.app_handle)
  142. .field("label", &self.label)
  143. .field("window_builder", &self.window_builder)
  144. .field("webview_attributes", &self.webview_attributes)
  145. .finish()
  146. }
  147. }
  148. impl<'a, R: Runtime> WindowBuilder<'a, R> {
  149. /// Initializes a webview window builder with the given window label and URL to load on the webview.
  150. ///
  151. /// # Known issues
  152. ///
  153. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  154. /// You should use `async` commands when creating windows.
  155. ///
  156. /// # Examples
  157. ///
  158. /// - Create a window in the setup hook:
  159. ///
  160. /// ```
  161. /// tauri::Builder::default()
  162. /// .setup(|app| {
  163. /// let window = tauri::WindowBuilder::new(app, "label", tauri::WindowUrl::App("index.html".into()))
  164. /// .build()?;
  165. /// Ok(())
  166. /// });
  167. /// ```
  168. ///
  169. /// - Create a window in a separate thread:
  170. ///
  171. /// ```
  172. /// tauri::Builder::default()
  173. /// .setup(|app| {
  174. /// let handle = app.handle().clone();
  175. /// std::thread::spawn(move || {
  176. /// let window = tauri::WindowBuilder::new(&handle, "label", tauri::WindowUrl::App("index.html".into()))
  177. /// .build()
  178. /// .unwrap();
  179. /// });
  180. /// Ok(())
  181. /// });
  182. /// ```
  183. ///
  184. /// - Create a window in a command:
  185. ///
  186. /// ```
  187. /// #[tauri::command]
  188. /// async fn create_window(app: tauri::AppHandle) {
  189. /// let window = tauri::WindowBuilder::new(&app, "label", tauri::WindowUrl::External("https://tauri.app/".parse().unwrap()))
  190. /// .build()
  191. /// .unwrap();
  192. /// }
  193. /// ```
  194. ///
  195. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  196. pub fn new<M: Manager<R>, L: Into<String>>(manager: &'a M, label: L, url: WindowUrl) -> Self {
  197. let runtime = manager.runtime();
  198. let app_handle = manager.app_handle().clone();
  199. Self {
  200. manager: manager.manager().clone(),
  201. runtime,
  202. app_handle,
  203. label: label.into(),
  204. window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder::new(),
  205. #[cfg(desktop)]
  206. menu: None,
  207. webview_attributes: WebviewAttributes::new(url),
  208. web_resource_request_handler: None,
  209. navigation_handler: None,
  210. on_page_load_handler: None,
  211. #[cfg(desktop)]
  212. on_menu_event: None,
  213. }
  214. }
  215. /// Initializes a webview window builder from a window config from tauri.conf.json.
  216. /// Keep in mind that you can't create 2 windows with the same `label` so make sure
  217. /// that the initial window was closed or change the label of the new `WindowBuilder`.
  218. ///
  219. /// # Known issues
  220. ///
  221. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  222. /// You should use `async` commands when creating windows.
  223. ///
  224. /// # Examples
  225. ///
  226. /// - Create a window in a command:
  227. ///
  228. /// ```
  229. /// #[tauri::command]
  230. /// async fn reopen_window(app: tauri::AppHandle) {
  231. /// let window = tauri::WindowBuilder::from_config(&app, app.config().tauri.windows.get(0).unwrap().clone())
  232. /// .build()
  233. /// .unwrap();
  234. /// }
  235. /// ```
  236. ///
  237. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  238. pub fn from_config<M: Manager<R>>(manager: &'a M, config: WindowConfig) -> Self {
  239. let builder = Self {
  240. manager: manager.manager().clone(),
  241. runtime: manager.runtime(),
  242. app_handle: manager.app_handle().clone(),
  243. label: config.label.clone(),
  244. webview_attributes: WebviewAttributes::from(&config),
  245. window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder::with_config(
  246. config,
  247. ),
  248. web_resource_request_handler: None,
  249. #[cfg(desktop)]
  250. menu: None,
  251. navigation_handler: None,
  252. #[cfg(desktop)]
  253. on_menu_event: None,
  254. on_page_load_handler: None,
  255. };
  256. builder
  257. }
  258. /// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
  259. ///
  260. /// Currently only implemented for the `tauri` URI protocol.
  261. ///
  262. /// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
  263. /// but it might be implemented in the future. **Always** check the request URL.
  264. ///
  265. /// # Examples
  266. ///
  267. /// ```rust,no_run
  268. /// use tauri::{
  269. /// utils::config::{Csp, CspDirectiveSources, WindowUrl},
  270. /// window::WindowBuilder,
  271. /// };
  272. /// use http::header::HeaderValue;
  273. /// use std::collections::HashMap;
  274. /// tauri::Builder::default()
  275. /// .setup(|app| {
  276. /// WindowBuilder::new(app, "core", WindowUrl::App("index.html".into()))
  277. /// .on_web_resource_request(|request, response| {
  278. /// if request.uri().scheme_str() == Some("tauri") {
  279. /// // if we have a CSP header, Tauri is loading an HTML file
  280. /// // for this example, let's dynamically change the CSP
  281. /// if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
  282. /// // use the tauri helper to parse the CSP policy to a map
  283. /// let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
  284. /// csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
  285. /// // use the tauri helper to get a CSP string from the map
  286. /// let csp_string = Csp::from(csp_map).to_string();
  287. /// *csp = HeaderValue::from_str(&csp_string).unwrap();
  288. /// }
  289. /// }
  290. /// })
  291. /// .build()?;
  292. /// Ok(())
  293. /// });
  294. /// ```
  295. pub fn on_web_resource_request<
  296. F: Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync + 'static,
  297. >(
  298. mut self,
  299. f: F,
  300. ) -> Self {
  301. self.web_resource_request_handler.replace(Box::new(f));
  302. self
  303. }
  304. /// Defines a closure to be executed when the webview navigates to a URL. Returning `false` cancels the navigation.
  305. ///
  306. /// # Examples
  307. ///
  308. /// ```rust,no_run
  309. /// use tauri::{
  310. /// utils::config::{Csp, CspDirectiveSources, WindowUrl},
  311. /// window::WindowBuilder,
  312. /// };
  313. /// use http::header::HeaderValue;
  314. /// use std::collections::HashMap;
  315. /// tauri::Builder::default()
  316. /// .setup(|app| {
  317. /// WindowBuilder::new(app, "core", WindowUrl::App("index.html".into()))
  318. /// .on_navigation(|url| {
  319. /// // allow the production URL or localhost on dev
  320. /// url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
  321. /// })
  322. /// .build()?;
  323. /// Ok(())
  324. /// });
  325. /// ```
  326. pub fn on_navigation<F: Fn(&Url) -> bool + Send + 'static>(mut self, f: F) -> Self {
  327. self.navigation_handler.replace(Box::new(f));
  328. self
  329. }
  330. /// Defines a closure to be executed when a page load event is triggered.
  331. /// The event can be either [`PageLoadEvent::Started`] if the page has started loading
  332. /// or [`PageLoadEvent::Finished`] when the page finishes loading.
  333. ///
  334. /// # Examples
  335. ///
  336. /// ```rust,no_run
  337. /// use tauri::{
  338. /// utils::config::{Csp, CspDirectiveSources, WindowUrl},
  339. /// window::{PageLoadEvent, WindowBuilder},
  340. /// };
  341. /// use http::header::HeaderValue;
  342. /// use std::collections::HashMap;
  343. /// tauri::Builder::default()
  344. /// .setup(|app| {
  345. /// WindowBuilder::new(app, "core", WindowUrl::App("index.html".into()))
  346. /// .on_page_load(|window, payload| {
  347. /// match payload.event() {
  348. /// PageLoadEvent::Started => {
  349. /// println!("{} finished loading", payload.url());
  350. /// }
  351. /// PageLoadEvent::Finished => {
  352. /// println!("{} finished loading", payload.url());
  353. /// }
  354. /// }
  355. /// })
  356. /// .build()?;
  357. /// Ok(())
  358. /// });
  359. /// ```
  360. pub fn on_page_load<F: Fn(Window<R>, PageLoadPayload<'_>) + Send + Sync + 'static>(
  361. mut self,
  362. f: F,
  363. ) -> Self {
  364. self.on_page_load_handler.replace(Box::new(f));
  365. self
  366. }
  367. /// Registers a global menu event listener.
  368. ///
  369. /// Note that this handler is called for any menu event,
  370. /// whether it is coming from this window, another window or from the tray icon menu.
  371. ///
  372. /// Also note that this handler will not be called if
  373. /// the window used to register it was closed.
  374. ///
  375. /// # Examples
  376. /// ```
  377. /// use tauri::menu::{Menu, Submenu, MenuItem};
  378. /// tauri::Builder::default()
  379. /// .setup(|app| {
  380. /// let handle = app.handle();
  381. /// let save_menu_item = MenuItem::new(handle, "Save", true, None);
  382. /// let menu = Menu::with_items(handle, &[
  383. /// &Submenu::with_items(handle, "File", true, &[
  384. /// &save_menu_item,
  385. /// ])?,
  386. /// ])?;
  387. /// let window = tauri::WindowBuilder::new(app, "editor", tauri::WindowUrl::default())
  388. /// .menu(menu)
  389. /// .on_menu_event(move |window, event| {
  390. /// if event.id == save_menu_item.id() {
  391. /// // save menu item
  392. /// }
  393. /// })
  394. /// .build()
  395. /// .unwrap();
  396. ///
  397. /// Ok(())
  398. /// });
  399. /// ```
  400. #[cfg(desktop)]
  401. pub fn on_menu_event<F: Fn(&Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
  402. mut self,
  403. f: F,
  404. ) -> Self {
  405. self.on_menu_event.replace(Box::new(f));
  406. self
  407. }
  408. /// Creates a new webview window.
  409. pub fn build(mut self) -> crate::Result<Window<R>> {
  410. let mut pending = PendingWindow::new(
  411. self.window_builder.clone(),
  412. self.webview_attributes.clone(),
  413. self.label.clone(),
  414. )?;
  415. pending.navigation_handler = self.navigation_handler.take();
  416. pending.web_resource_request_handler = self.web_resource_request_handler.take();
  417. if let Some(on_page_load_handler) = self.on_page_load_handler.take() {
  418. let label = pending.label.clone();
  419. let manager = self.app_handle.manager.clone();
  420. pending
  421. .on_page_load_handler
  422. .replace(Box::new(move |url, event| {
  423. if let Some(w) = manager.get_window(&label) {
  424. on_page_load_handler(w, PageLoadPayload { url: &url, event });
  425. }
  426. }));
  427. }
  428. let labels = self.manager.labels().into_iter().collect::<Vec<_>>();
  429. let pending = self
  430. .manager
  431. .prepare_window(self.app_handle.clone(), pending, &labels)?;
  432. #[cfg(desktop)]
  433. let window_menu = {
  434. let is_app_wide = self.menu.is_none();
  435. self
  436. .menu
  437. .or_else(|| self.app_handle.menu())
  438. .map(|menu| WindowMenu { is_app_wide, menu })
  439. };
  440. #[cfg(desktop)]
  441. let handler = self
  442. .manager
  443. .prepare_window_menu_creation_handler(window_menu.as_ref());
  444. #[cfg(not(desktop))]
  445. #[allow(clippy::type_complexity)]
  446. let handler: Option<Box<dyn Fn(tauri_runtime::window::RawWindow<'_>) + Send>> = None;
  447. let window_effects = pending.webview_attributes.window_effects.clone();
  448. let window = match &mut self.runtime {
  449. RuntimeOrDispatch::Runtime(runtime) => runtime.create_window(pending, handler),
  450. RuntimeOrDispatch::RuntimeHandle(handle) => handle.create_window(pending, handler),
  451. RuntimeOrDispatch::Dispatch(dispatcher) => dispatcher.create_window(pending, handler),
  452. }
  453. .map(|window| {
  454. self.manager.attach_window(
  455. self.app_handle.clone(),
  456. window,
  457. #[cfg(desktop)]
  458. window_menu,
  459. )
  460. })?;
  461. #[cfg(desktop)]
  462. if let Some(handler) = self.on_menu_event {
  463. window.on_menu_event(handler);
  464. }
  465. if let Some(effects) = window_effects {
  466. crate::vibrancy::set_window_effects(&window, Some(effects))?;
  467. }
  468. self.manager.eval_script_all(format!(
  469. "window.__TAURI_INTERNALS__.metadata.windows = {window_labels_array}.map(function (label) {{ return {{ label: label }} }})",
  470. window_labels_array = serde_json::to_string(&self.manager.labels())?,
  471. ))?;
  472. self.manager.emit_filter(
  473. "tauri://window-created",
  474. None,
  475. Some(WindowCreatedEvent {
  476. label: window.label().into(),
  477. }),
  478. |w| w != &window,
  479. )?;
  480. Ok(window)
  481. }
  482. }
  483. /// Desktop APIs.
  484. #[cfg(desktop)]
  485. impl<'a, R: Runtime> WindowBuilder<'a, R> {
  486. /// Sets the menu for the window.
  487. #[must_use]
  488. pub fn menu(mut self, menu: Menu<R>) -> Self {
  489. self.menu.replace(menu);
  490. self
  491. }
  492. /// Show window in the center of the screen.
  493. #[must_use]
  494. pub fn center(mut self) -> Self {
  495. self.window_builder = self.window_builder.center();
  496. self
  497. }
  498. /// The initial position of the window's.
  499. #[must_use]
  500. pub fn position(mut self, x: f64, y: f64) -> Self {
  501. self.window_builder = self.window_builder.position(x, y);
  502. self
  503. }
  504. /// Window size.
  505. #[must_use]
  506. pub fn inner_size(mut self, width: f64, height: f64) -> Self {
  507. self.window_builder = self.window_builder.inner_size(width, height);
  508. self
  509. }
  510. /// Window min inner size.
  511. #[must_use]
  512. pub fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
  513. self.window_builder = self.window_builder.min_inner_size(min_width, min_height);
  514. self
  515. }
  516. /// Window max inner size.
  517. #[must_use]
  518. pub fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
  519. self.window_builder = self.window_builder.max_inner_size(max_width, max_height);
  520. self
  521. }
  522. /// Whether the window is resizable or not.
  523. /// When resizable is set to false, native window's maximize button is automatically disabled.
  524. #[must_use]
  525. pub fn resizable(mut self, resizable: bool) -> Self {
  526. self.window_builder = self.window_builder.resizable(resizable);
  527. self
  528. }
  529. /// Whether the window's native maximize button is enabled or not.
  530. /// If resizable is set to false, this setting is ignored.
  531. ///
  532. /// ## Platform-specific
  533. ///
  534. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  535. /// - **Linux / iOS / Android:** Unsupported.
  536. #[must_use]
  537. pub fn maximizable(mut self, maximizable: bool) -> Self {
  538. self.window_builder = self.window_builder.maximizable(maximizable);
  539. self
  540. }
  541. /// Whether the window's native minimize button is enabled or not.
  542. ///
  543. /// ## Platform-specific
  544. ///
  545. /// - **Linux / iOS / Android:** Unsupported.
  546. #[must_use]
  547. pub fn minimizable(mut self, minimizable: bool) -> Self {
  548. self.window_builder = self.window_builder.minimizable(minimizable);
  549. self
  550. }
  551. /// Whether the window's native close button is enabled or not.
  552. ///
  553. /// ## Platform-specific
  554. ///
  555. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  556. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  557. /// - **iOS / Android:** Unsupported.
  558. #[must_use]
  559. pub fn closable(mut self, closable: bool) -> Self {
  560. self.window_builder = self.window_builder.closable(closable);
  561. self
  562. }
  563. /// The title of the window in the title bar.
  564. #[must_use]
  565. pub fn title<S: Into<String>>(mut self, title: S) -> Self {
  566. self.window_builder = self.window_builder.title(title);
  567. self
  568. }
  569. /// Whether to start the window in fullscreen or not.
  570. #[must_use]
  571. pub fn fullscreen(mut self, fullscreen: bool) -> Self {
  572. self.window_builder = self.window_builder.fullscreen(fullscreen);
  573. self
  574. }
  575. /// Sets the window to be initially focused.
  576. #[must_use]
  577. #[deprecated(
  578. since = "1.2.0",
  579. note = "The window is automatically focused by default. This function Will be removed in 2.0.0. Use `focused` instead."
  580. )]
  581. pub fn focus(mut self) -> Self {
  582. self.window_builder = self.window_builder.focused(true);
  583. self
  584. }
  585. /// Whether the window will be initially focused or not.
  586. #[must_use]
  587. pub fn focused(mut self, focused: bool) -> Self {
  588. self.window_builder = self.window_builder.focused(focused);
  589. self
  590. }
  591. /// Whether the window should be maximized upon creation.
  592. #[must_use]
  593. pub fn maximized(mut self, maximized: bool) -> Self {
  594. self.window_builder = self.window_builder.maximized(maximized);
  595. self
  596. }
  597. /// Whether the window should be immediately visible upon creation.
  598. #[must_use]
  599. pub fn visible(mut self, visible: bool) -> Self {
  600. self.window_builder = self.window_builder.visible(visible);
  601. self
  602. }
  603. /// Forces a theme or uses the system settings if None was provided.
  604. ///
  605. /// ## Platform-specific
  606. ///
  607. /// - **macOS**: Only supported on macOS 10.14+.
  608. #[must_use]
  609. pub fn theme(mut self, theme: Option<Theme>) -> Self {
  610. self.window_builder = self.window_builder.theme(theme);
  611. self
  612. }
  613. /// Whether the window should be transparent. If this is true, writing colors
  614. /// with alpha values different than `1.0` will produce a transparent window.
  615. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  616. #[cfg_attr(
  617. docsrs,
  618. doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
  619. )]
  620. #[must_use]
  621. pub fn transparent(mut self, transparent: bool) -> Self {
  622. self.window_builder = self.window_builder.transparent(transparent);
  623. self
  624. }
  625. /// Whether the window should have borders and bars.
  626. #[must_use]
  627. pub fn decorations(mut self, decorations: bool) -> Self {
  628. self.window_builder = self.window_builder.decorations(decorations);
  629. self
  630. }
  631. /// Whether the window should always be below other windows.
  632. #[must_use]
  633. pub fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
  634. self.window_builder = self.window_builder.always_on_bottom(always_on_bottom);
  635. self
  636. }
  637. /// Whether the window should always be on top of other windows.
  638. #[must_use]
  639. pub fn always_on_top(mut self, always_on_top: bool) -> Self {
  640. self.window_builder = self.window_builder.always_on_top(always_on_top);
  641. self
  642. }
  643. /// Whether the window will be visible on all workspaces or virtual desktops.
  644. #[must_use]
  645. pub fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
  646. self.window_builder = self
  647. .window_builder
  648. .visible_on_all_workspaces(visible_on_all_workspaces);
  649. self
  650. }
  651. /// Prevents the window contents from being captured by other apps.
  652. #[must_use]
  653. pub fn content_protected(mut self, protected: bool) -> Self {
  654. self.window_builder = self.window_builder.content_protected(protected);
  655. self
  656. }
  657. /// Sets the window icon.
  658. pub fn icon(mut self, icon: Icon) -> crate::Result<Self> {
  659. self.window_builder = self.window_builder.icon(icon.try_into()?)?;
  660. Ok(self)
  661. }
  662. /// Sets whether or not the window icon should be hidden from the taskbar.
  663. ///
  664. /// ## Platform-specific
  665. ///
  666. /// - **macOS**: Unsupported.
  667. #[must_use]
  668. pub fn skip_taskbar(mut self, skip: bool) -> Self {
  669. self.window_builder = self.window_builder.skip_taskbar(skip);
  670. self
  671. }
  672. /// Sets whether or not the window has shadow.
  673. ///
  674. /// ## Platform-specific
  675. ///
  676. /// - **Windows:**
  677. /// - `false` has no effect on decorated window, shadows are always ON.
  678. /// - `true` will make ndecorated window have a 1px white border,
  679. /// and on Windows 11, it will have a rounded corners.
  680. /// - **Linux:** Unsupported.
  681. #[must_use]
  682. pub fn shadow(mut self, enable: bool) -> Self {
  683. self.window_builder = self.window_builder.shadow(enable);
  684. self
  685. }
  686. /// Sets a parent to the window to be created.
  687. ///
  688. /// A child window has the WS_CHILD style and is confined to the client area of its parent window.
  689. ///
  690. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
  691. #[cfg(windows)]
  692. #[must_use]
  693. pub fn parent_window(mut self, parent: HWND) -> Self {
  694. self.window_builder = self.window_builder.parent_window(parent);
  695. self
  696. }
  697. /// Sets a parent to the window to be created.
  698. #[cfg(target_os = "macos")]
  699. #[must_use]
  700. pub fn parent_window(mut self, parent: *mut std::ffi::c_void) -> Self {
  701. self.window_builder = self.window_builder.parent_window(parent);
  702. self
  703. }
  704. /// Set an owner to the window to be created.
  705. ///
  706. /// From MSDN:
  707. /// - An owned window is always above its owner in the z-order.
  708. /// - The system automatically destroys an owned window when its owner is destroyed.
  709. /// - An owned window is hidden when its owner is minimized.
  710. ///
  711. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
  712. #[cfg(windows)]
  713. #[must_use]
  714. pub fn owner_window(mut self, owner: HWND) -> Self {
  715. self.window_builder = self.window_builder.owner_window(owner);
  716. self
  717. }
  718. /// Sets the [`TitleBarStyle`].
  719. #[cfg(target_os = "macos")]
  720. #[must_use]
  721. pub fn title_bar_style(mut self, style: TitleBarStyle) -> Self {
  722. self.window_builder = self.window_builder.title_bar_style(style);
  723. self
  724. }
  725. /// Hide the window title.
  726. #[cfg(target_os = "macos")]
  727. #[must_use]
  728. pub fn hidden_title(mut self, hidden: bool) -> Self {
  729. self.window_builder = self.window_builder.hidden_title(hidden);
  730. self
  731. }
  732. /// Defines the window [tabbing identifier] for macOS.
  733. ///
  734. /// Windows with matching tabbing identifiers will be grouped together.
  735. /// If the tabbing identifier is not set, automatic tabbing will be disabled.
  736. ///
  737. /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
  738. #[cfg(target_os = "macos")]
  739. #[must_use]
  740. pub fn tabbing_identifier(mut self, identifier: &str) -> Self {
  741. self.window_builder = self.window_builder.tabbing_identifier(identifier);
  742. self
  743. }
  744. /// Sets whether clicking an inactive window also clicks through to the webview.
  745. #[must_use]
  746. pub fn accept_first_mouse(mut self, accept: bool) -> Self {
  747. self.webview_attributes.accept_first_mouse = accept;
  748. self
  749. }
  750. /// Sets window effects.
  751. ///
  752. /// Requires the window to be transparent.
  753. ///
  754. /// ## Platform-specific:
  755. ///
  756. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  757. /// - **Linux**: Unsupported
  758. pub fn effects(mut self, effects: WindowEffectsConfig) -> Self {
  759. self.webview_attributes = self.webview_attributes.window_effects(effects);
  760. self
  761. }
  762. }
  763. /// Webview attributes.
  764. impl<'a, R: Runtime> WindowBuilder<'a, R> {
  765. /// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
  766. /// but before the HTML document has been parsed and before any other script included by the HTML document is run.
  767. ///
  768. /// Since it runs on all top-level document and child frame page navigations,
  769. /// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
  770. ///
  771. /// # Examples
  772. ///
  773. /// ```rust
  774. /// use tauri::{WindowBuilder, Runtime};
  775. ///
  776. /// const INIT_SCRIPT: &str = r#"
  777. /// if (window.location.origin === 'https://tauri.app') {
  778. /// console.log("hello world from js init script");
  779. ///
  780. /// window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
  781. /// }
  782. /// "#;
  783. ///
  784. /// fn main() {
  785. /// tauri::Builder::default()
  786. /// .setup(|app| {
  787. /// let window = tauri::WindowBuilder::new(app, "label", tauri::WindowUrl::App("index.html".into()))
  788. /// .initialization_script(INIT_SCRIPT)
  789. /// .build()?;
  790. /// Ok(())
  791. /// });
  792. /// }
  793. /// ```
  794. #[must_use]
  795. pub fn initialization_script(mut self, script: &str) -> Self {
  796. self
  797. .webview_attributes
  798. .initialization_scripts
  799. .push(script.to_string());
  800. self
  801. }
  802. /// Set the user agent for the webview
  803. #[must_use]
  804. pub fn user_agent(mut self, user_agent: &str) -> Self {
  805. self.webview_attributes.user_agent = Some(user_agent.to_string());
  806. self
  807. }
  808. /// Set additional arguments for the webview.
  809. ///
  810. /// ## Platform-specific
  811. ///
  812. /// - **macOS / Linux / Android / iOS**: Unsupported.
  813. ///
  814. /// ## Warning
  815. ///
  816. /// By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
  817. /// so if you use this method, you also need to disable these components by yourself if you want.
  818. #[must_use]
  819. pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
  820. self.webview_attributes.additional_browser_args = Some(additional_args.to_string());
  821. self
  822. }
  823. /// Data directory for the webview.
  824. #[must_use]
  825. pub fn data_directory(mut self, data_directory: PathBuf) -> Self {
  826. self
  827. .webview_attributes
  828. .data_directory
  829. .replace(data_directory);
  830. self
  831. }
  832. /// Disables the file drop handler. This is required to use drag and drop APIs on the front end on Windows.
  833. #[must_use]
  834. pub fn disable_file_drop_handler(mut self) -> Self {
  835. self.webview_attributes.file_drop_handler_enabled = false;
  836. self
  837. }
  838. /// Enables clipboard access for the page rendered on **Linux** and **Windows**.
  839. ///
  840. /// **macOS** doesn't provide such method and is always enabled by default,
  841. /// but you still need to add menu item accelerators to use shortcuts.
  842. #[must_use]
  843. pub fn enable_clipboard_access(mut self) -> Self {
  844. self.webview_attributes.clipboard = true;
  845. self
  846. }
  847. /// Enable or disable incognito mode for the WebView..
  848. ///
  849. /// ## Platform-specific:
  850. ///
  851. /// **Android**: Unsupported.
  852. #[must_use]
  853. pub fn incognito(mut self, incognito: bool) -> Self {
  854. self.webview_attributes.incognito = incognito;
  855. self
  856. }
  857. }
  858. /// Key for a JS event listener.
  859. #[derive(Debug, Clone, PartialEq, Eq, Hash)]
  860. struct JsEventListenerKey {
  861. /// The associated window label.
  862. pub window_label: Option<String>,
  863. /// The event name.
  864. pub event: String,
  865. }
  866. /// The IPC invoke request.
  867. #[derive(Debug)]
  868. pub struct InvokeRequest {
  869. /// The invoke command.
  870. pub cmd: String,
  871. /// The success callback.
  872. pub callback: CallbackFn,
  873. /// The error callback.
  874. pub error: CallbackFn,
  875. /// The body of the request.
  876. pub body: InvokeBody,
  877. /// The request headers.
  878. pub headers: HeaderMap,
  879. }
  880. /// A wrapper struct to hold the window menu state
  881. /// and whether it is global per-app or specific to this window.
  882. #[cfg(desktop)]
  883. pub(crate) struct WindowMenu<R: Runtime> {
  884. pub(crate) is_app_wide: bool,
  885. pub(crate) menu: Menu<R>,
  886. }
  887. // TODO: expand these docs since this is a pretty important type
  888. /// A webview window managed by Tauri.
  889. ///
  890. /// This type also implements [`Manager`] which allows you to manage other windows attached to
  891. /// the same application.
  892. #[default_runtime(crate::Wry, wry)]
  893. pub struct Window<R: Runtime> {
  894. /// The webview window created by the runtime.
  895. pub(crate) window: DetachedWindow<EventLoopMessage, R>,
  896. /// The manager to associate this webview window with.
  897. pub(crate) manager: WindowManager<R>,
  898. pub(crate) app_handle: AppHandle<R>,
  899. js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<EventId>>>>,
  900. // The menu set for this window
  901. #[cfg(desktop)]
  902. pub(crate) menu: Arc<Mutex<Option<WindowMenu<R>>>>,
  903. }
  904. impl<R: Runtime> std::fmt::Debug for Window<R> {
  905. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  906. f.debug_struct("Window")
  907. .field("window", &self.window)
  908. .field("manager", &self.manager)
  909. .field("app_handle", &self.app_handle)
  910. .field("js_event_listeners", &self.js_event_listeners)
  911. .finish()
  912. }
  913. }
  914. unsafe impl<R: Runtime> raw_window_handle::HasRawWindowHandle for Window<R> {
  915. fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle {
  916. self.window.dispatcher.raw_window_handle().unwrap()
  917. }
  918. }
  919. impl<R: Runtime> Clone for Window<R> {
  920. fn clone(&self) -> Self {
  921. Self {
  922. window: self.window.clone(),
  923. manager: self.manager.clone(),
  924. app_handle: self.app_handle.clone(),
  925. js_event_listeners: self.js_event_listeners.clone(),
  926. #[cfg(desktop)]
  927. menu: self.menu.clone(),
  928. }
  929. }
  930. }
  931. impl<R: Runtime> Hash for Window<R> {
  932. /// Only use the [`Window`]'s label to represent its hash.
  933. fn hash<H: Hasher>(&self, state: &mut H) {
  934. self.window.label.hash(state)
  935. }
  936. }
  937. impl<R: Runtime> Eq for Window<R> {}
  938. impl<R: Runtime> PartialEq for Window<R> {
  939. /// Only use the [`Window`]'s label to compare equality.
  940. fn eq(&self, other: &Self) -> bool {
  941. self.window.label.eq(&other.window.label)
  942. }
  943. }
  944. impl<R: Runtime> Manager<R> for Window<R> {
  945. fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> crate::Result<()> {
  946. self.manager().emit(event, Some(self.label()), payload)?;
  947. Ok(())
  948. }
  949. fn emit_to<S: Serialize + Clone>(
  950. &self,
  951. label: &str,
  952. event: &str,
  953. payload: S,
  954. ) -> crate::Result<()> {
  955. self
  956. .manager()
  957. .emit_filter(event, Some(self.label()), payload, |w| label == w.label())
  958. }
  959. fn emit_filter<S, F>(&self, event: &str, payload: S, filter: F) -> crate::Result<()>
  960. where
  961. S: Serialize + Clone,
  962. F: Fn(&Window<R>) -> bool,
  963. {
  964. self
  965. .manager()
  966. .emit_filter(event, Some(self.label()), payload, filter)
  967. }
  968. }
  969. impl<R: Runtime> ManagerBase<R> for Window<R> {
  970. fn manager(&self) -> &WindowManager<R> {
  971. &self.manager
  972. }
  973. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  974. RuntimeOrDispatch::Dispatch(self.dispatcher())
  975. }
  976. fn managed_app_handle(&self) -> &AppHandle<R> {
  977. &self.app_handle
  978. }
  979. }
  980. impl<'de, R: Runtime> CommandArg<'de, R> for Window<R> {
  981. /// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
  982. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  983. Ok(command.message.window())
  984. }
  985. }
  986. /// The platform webview handle. Accessed with [`Window#method.with_webview`];
  987. #[cfg(feature = "wry")]
  988. #[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
  989. pub struct PlatformWebview(tauri_runtime_wry::Webview);
  990. #[cfg(feature = "wry")]
  991. impl PlatformWebview {
  992. /// Returns [`webkit2gtk::WebView`] handle.
  993. #[cfg(any(
  994. target_os = "linux",
  995. target_os = "dragonfly",
  996. target_os = "freebsd",
  997. target_os = "netbsd",
  998. target_os = "openbsd"
  999. ))]
  1000. #[cfg_attr(
  1001. docsrs,
  1002. doc(cfg(any(
  1003. target_os = "linux",
  1004. target_os = "dragonfly",
  1005. target_os = "freebsd",
  1006. target_os = "netbsd",
  1007. target_os = "openbsd"
  1008. )))
  1009. )]
  1010. pub fn inner(&self) -> std::rc::Rc<webkit2gtk::WebView> {
  1011. self.0.clone()
  1012. }
  1013. /// Returns the WebView2 controller.
  1014. #[cfg(windows)]
  1015. #[cfg_attr(docsrs, doc(cfg(windows)))]
  1016. pub fn controller(
  1017. &self,
  1018. ) -> webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller {
  1019. self.0.controller.clone()
  1020. }
  1021. /// Returns the [WKWebView] handle.
  1022. ///
  1023. /// [WKWebView]: https://developer.apple.com/documentation/webkit/wkwebview
  1024. #[cfg(any(target_os = "macos", target_os = "ios"))]
  1025. #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
  1026. pub fn inner(&self) -> cocoa::base::id {
  1027. self.0.webview
  1028. }
  1029. /// Returns WKWebView [controller] handle.
  1030. ///
  1031. /// [controller]: https://developer.apple.com/documentation/webkit/wkusercontentcontroller
  1032. #[cfg(any(target_os = "macos", target_os = "ios"))]
  1033. #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
  1034. pub fn controller(&self) -> cocoa::base::id {
  1035. self.0.manager
  1036. }
  1037. /// Returns [NSWindow] associated with the WKWebView webview.
  1038. ///
  1039. /// [NSWindow]: https://developer.apple.com/documentation/appkit/nswindow
  1040. #[cfg(target_os = "macos")]
  1041. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  1042. pub fn ns_window(&self) -> cocoa::base::id {
  1043. self.0.ns_window
  1044. }
  1045. /// Returns [UIViewController] used by the WKWebView webview NSWindow.
  1046. ///
  1047. /// [UIViewController]: https://developer.apple.com/documentation/uikit/uiviewcontroller
  1048. #[cfg(target_os = "ios")]
  1049. #[cfg_attr(docsrs, doc(cfg(target_os = "ios")))]
  1050. pub fn view_controller(&self) -> cocoa::base::id {
  1051. self.0.view_controller
  1052. }
  1053. /// Returns handle for JNI execution.
  1054. #[cfg(target_os = "android")]
  1055. pub fn jni_handle(&self) -> tauri_runtime_wry::wry::webview::JniHandle {
  1056. self.0
  1057. }
  1058. }
  1059. /// Base window functions.
  1060. impl<R: Runtime> Window<R> {
  1061. /// Create a new window that is attached to the manager.
  1062. pub(crate) fn new(
  1063. manager: WindowManager<R>,
  1064. window: DetachedWindow<EventLoopMessage, R>,
  1065. app_handle: AppHandle<R>,
  1066. #[cfg(desktop)] menu: Option<WindowMenu<R>>,
  1067. ) -> Self {
  1068. Self {
  1069. window,
  1070. manager,
  1071. app_handle,
  1072. js_event_listeners: Default::default(),
  1073. #[cfg(desktop)]
  1074. menu: Arc::new(Mutex::new(menu)),
  1075. }
  1076. }
  1077. /// Initializes a webview window builder with the given window label and URL to load on the webview.
  1078. ///
  1079. /// Data URLs are only supported with the `window-data-url` feature flag.
  1080. pub fn builder<'a, M: Manager<R>, L: Into<String>>(
  1081. manager: &'a M,
  1082. label: L,
  1083. url: WindowUrl,
  1084. ) -> WindowBuilder<'a, R> {
  1085. WindowBuilder::<'a, R>::new(manager, label.into(), url)
  1086. }
  1087. /// The current window's dispatcher.
  1088. pub(crate) fn dispatcher(&self) -> R::Dispatcher {
  1089. self.window.dispatcher.clone()
  1090. }
  1091. /// Runs the given closure on the main thread.
  1092. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  1093. self
  1094. .window
  1095. .dispatcher
  1096. .run_on_main_thread(f)
  1097. .map_err(Into::into)
  1098. }
  1099. /// The label of this window.
  1100. pub fn label(&self) -> &str {
  1101. &self.window.label
  1102. }
  1103. /// Registers a window event listener.
  1104. pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) {
  1105. self
  1106. .window
  1107. .dispatcher
  1108. .on_window_event(move |event| f(&event.clone().into()));
  1109. }
  1110. /// Executes a closure, providing it with the webview handle that is specific to the current platform.
  1111. ///
  1112. /// The closure is executed on the main thread.
  1113. ///
  1114. /// # Examples
  1115. ///
  1116. /// ```rust,no_run
  1117. /// #[cfg(target_os = "macos")]
  1118. /// #[macro_use]
  1119. /// extern crate objc;
  1120. /// use tauri::Manager;
  1121. ///
  1122. /// fn main() {
  1123. /// tauri::Builder::default()
  1124. /// .setup(|app| {
  1125. /// let main_window = app.get_window("main").unwrap();
  1126. /// main_window.with_webview(|webview| {
  1127. /// #[cfg(target_os = "linux")]
  1128. /// {
  1129. /// // see https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/struct.WebView.html
  1130. /// // and https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/trait.WebViewExt.html
  1131. /// use webkit2gtk::WebViewExt;
  1132. /// webview.inner().set_zoom_level(4.);
  1133. /// }
  1134. ///
  1135. /// #[cfg(windows)]
  1136. /// unsafe {
  1137. /// // see https://docs.rs/webview2-com/0.19.1/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html
  1138. /// webview.controller().SetZoomFactor(4.).unwrap();
  1139. /// }
  1140. ///
  1141. /// #[cfg(target_os = "macos")]
  1142. /// unsafe {
  1143. /// let () = msg_send![webview.inner(), setPageZoom: 4.];
  1144. /// let () = msg_send![webview.controller(), removeAllUserScripts];
  1145. /// let bg_color: cocoa::base::id = msg_send![class!(NSColor), colorWithDeviceRed:0.5 green:0.2 blue:0.4 alpha:1.];
  1146. /// let () = msg_send![webview.ns_window(), setBackgroundColor: bg_color];
  1147. /// }
  1148. ///
  1149. /// #[cfg(target_os = "android")]
  1150. /// {
  1151. /// use jni::objects::JValue;
  1152. /// webview.jni_handle().exec(|env, _, webview| {
  1153. /// env.call_method(webview, "zoomBy", "(F)V", &[JValue::Float(4.)]).unwrap();
  1154. /// })
  1155. /// }
  1156. /// });
  1157. /// Ok(())
  1158. /// });
  1159. /// }
  1160. /// ```
  1161. #[cfg(feature = "wry")]
  1162. #[cfg_attr(docsrs, doc(feature = "wry"))]
  1163. pub fn with_webview<F: FnOnce(PlatformWebview) + Send + 'static>(
  1164. &self,
  1165. f: F,
  1166. ) -> crate::Result<()> {
  1167. self
  1168. .window
  1169. .dispatcher
  1170. .with_webview(|w| f(PlatformWebview(*w.downcast().unwrap())))
  1171. .map_err(Into::into)
  1172. }
  1173. }
  1174. /// Menu APIs
  1175. #[cfg(desktop)]
  1176. impl<R: Runtime> Window<R> {
  1177. /// Registers a global menu event listener.
  1178. ///
  1179. /// Note that this handler is called for any menu event,
  1180. /// whether it is coming from this window, another window or from the tray icon menu.
  1181. ///
  1182. /// Also note that this handler will not be called if
  1183. /// the window used to register it was closed.
  1184. ///
  1185. /// # Examples
  1186. /// ```
  1187. /// use tauri::menu::{Menu, Submenu, MenuItem};
  1188. /// tauri::Builder::default()
  1189. /// .setup(|app| {
  1190. /// let handle = app.handle();
  1191. /// let save_menu_item = MenuItem::new(handle, "Save", true, None);
  1192. /// let menu = Menu::with_items(handle, &[
  1193. /// &Submenu::with_items(handle, "File", true, &[
  1194. /// &save_menu_item,
  1195. /// ])?,
  1196. /// ])?;
  1197. /// let window = tauri::WindowBuilder::new(app, "editor", tauri::WindowUrl::default())
  1198. /// .menu(menu)
  1199. /// .build()
  1200. /// .unwrap();
  1201. ///
  1202. /// window.on_menu_event(move |window, event| {
  1203. /// if event.id == save_menu_item.id() {
  1204. /// // save menu item
  1205. /// }
  1206. /// });
  1207. ///
  1208. /// Ok(())
  1209. /// });
  1210. /// ```
  1211. pub fn on_menu_event<F: Fn(&Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
  1212. &self,
  1213. f: F,
  1214. ) {
  1215. self
  1216. .manager
  1217. .inner
  1218. .window_menu_event_listeners
  1219. .lock()
  1220. .unwrap()
  1221. .insert(self.label().to_string(), Box::new(f));
  1222. }
  1223. pub(crate) fn menu_lock(&self) -> std::sync::MutexGuard<'_, Option<WindowMenu<R>>> {
  1224. self.menu.lock().expect("poisoned window")
  1225. }
  1226. #[cfg_attr(target_os = "macos", allow(dead_code))]
  1227. pub(crate) fn has_app_wide_menu(&self) -> bool {
  1228. self
  1229. .menu_lock()
  1230. .as_ref()
  1231. .map(|m| m.is_app_wide)
  1232. .unwrap_or(false)
  1233. }
  1234. #[cfg_attr(target_os = "macos", allow(dead_code))]
  1235. pub(crate) fn is_menu_in_use<I: PartialEq<MenuId>>(&self, id: &I) -> bool {
  1236. self
  1237. .menu_lock()
  1238. .as_ref()
  1239. .map(|m| id.eq(m.menu.id()))
  1240. .unwrap_or(false)
  1241. }
  1242. /// Returns this window menu .
  1243. pub fn menu(&self) -> Option<Menu<R>> {
  1244. self.menu_lock().as_ref().map(|m| m.menu.clone())
  1245. }
  1246. /// Sets the window menu and returns the previous one.
  1247. ///
  1248. /// ## Platform-specific:
  1249. ///
  1250. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  1251. /// window, if you need to set it, use [`AppHandle::set_menu`] instead.
  1252. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1253. pub fn set_menu(&self, menu: Menu<R>) -> crate::Result<Option<Menu<R>>> {
  1254. let prev_menu = self.remove_menu()?;
  1255. self.manager.insert_menu_into_stash(&menu);
  1256. let window = self.clone();
  1257. let menu_ = menu.clone();
  1258. self.run_on_main_thread(move || {
  1259. #[cfg(windows)]
  1260. if let Ok(hwnd) = window.hwnd() {
  1261. let _ = menu_.inner().init_for_hwnd(hwnd.0);
  1262. }
  1263. #[cfg(any(
  1264. target_os = "linux",
  1265. target_os = "dragonfly",
  1266. target_os = "freebsd",
  1267. target_os = "netbsd",
  1268. target_os = "openbsd"
  1269. ))]
  1270. if let (Ok(gtk_window), Ok(gtk_box)) = (window.gtk_window(), window.default_vbox()) {
  1271. let _ = menu_
  1272. .inner()
  1273. .init_for_gtk_window(&gtk_window, Some(&gtk_box));
  1274. }
  1275. })?;
  1276. self.menu_lock().replace(WindowMenu {
  1277. is_app_wide: false,
  1278. menu,
  1279. });
  1280. Ok(prev_menu)
  1281. }
  1282. /// Removes the window menu and returns it.
  1283. ///
  1284. /// ## Platform-specific:
  1285. ///
  1286. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  1287. /// window, if you need to remove it, use [`AppHandle::remove_menu`] instead.
  1288. pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
  1289. let current_menu = self.menu_lock().as_ref().map(|m| m.menu.clone());
  1290. // remove from the window
  1291. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1292. if let Some(menu) = current_menu {
  1293. let window = self.clone();
  1294. self.run_on_main_thread(move || {
  1295. #[cfg(windows)]
  1296. if let Ok(hwnd) = window.hwnd() {
  1297. let _ = menu.inner().remove_for_hwnd(hwnd.0);
  1298. }
  1299. #[cfg(any(
  1300. target_os = "linux",
  1301. target_os = "dragonfly",
  1302. target_os = "freebsd",
  1303. target_os = "netbsd",
  1304. target_os = "openbsd"
  1305. ))]
  1306. if let Ok(gtk_window) = window.gtk_window() {
  1307. let _ = menu.inner().remove_for_gtk_window(&gtk_window);
  1308. }
  1309. })?;
  1310. }
  1311. let prev_menu = self.menu_lock().take().map(|m| m.menu);
  1312. self
  1313. .manager
  1314. .remove_menu_from_stash_by_id(prev_menu.as_ref().map(|m| m.id()));
  1315. Ok(prev_menu)
  1316. }
  1317. /// Hides the window menu.
  1318. pub fn hide_menu(&self) -> crate::Result<()> {
  1319. // remove from the window
  1320. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1321. if let Some(window_menu) = &*self.menu_lock() {
  1322. let window = self.clone();
  1323. let menu_ = window_menu.menu.clone();
  1324. self.run_on_main_thread(move || {
  1325. #[cfg(windows)]
  1326. if let Ok(hwnd) = window.hwnd() {
  1327. let _ = menu_.inner().hide_for_hwnd(hwnd.0);
  1328. }
  1329. #[cfg(any(
  1330. target_os = "linux",
  1331. target_os = "dragonfly",
  1332. target_os = "freebsd",
  1333. target_os = "netbsd",
  1334. target_os = "openbsd"
  1335. ))]
  1336. if let Ok(gtk_window) = window.gtk_window() {
  1337. let _ = menu_.inner().hide_for_gtk_window(&gtk_window);
  1338. }
  1339. })?;
  1340. }
  1341. Ok(())
  1342. }
  1343. /// Shows the window menu.
  1344. pub fn show_menu(&self) -> crate::Result<()> {
  1345. // remove from the window
  1346. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1347. if let Some(window_menu) = &*self.menu_lock() {
  1348. let window = self.clone();
  1349. let menu_ = window_menu.menu.clone();
  1350. self.run_on_main_thread(move || {
  1351. #[cfg(windows)]
  1352. if let Ok(hwnd) = window.hwnd() {
  1353. let _ = menu_.inner().show_for_hwnd(hwnd.0);
  1354. }
  1355. #[cfg(any(
  1356. target_os = "linux",
  1357. target_os = "dragonfly",
  1358. target_os = "freebsd",
  1359. target_os = "netbsd",
  1360. target_os = "openbsd"
  1361. ))]
  1362. if let Ok(gtk_window) = window.gtk_window() {
  1363. let _ = menu_.inner().show_for_gtk_window(&gtk_window);
  1364. }
  1365. })?;
  1366. }
  1367. Ok(())
  1368. }
  1369. /// Shows the window menu.
  1370. pub fn is_menu_visible(&self) -> crate::Result<bool> {
  1371. // remove from the window
  1372. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1373. if let Some(window_menu) = &*self.menu_lock() {
  1374. let (tx, rx) = std::sync::mpsc::channel();
  1375. let window = self.clone();
  1376. let menu_ = window_menu.menu.clone();
  1377. self.run_on_main_thread(move || {
  1378. #[cfg(windows)]
  1379. if let Ok(hwnd) = window.hwnd() {
  1380. let _ = tx.send(menu_.inner().is_visible_on_hwnd(hwnd.0));
  1381. }
  1382. #[cfg(any(
  1383. target_os = "linux",
  1384. target_os = "dragonfly",
  1385. target_os = "freebsd",
  1386. target_os = "netbsd",
  1387. target_os = "openbsd"
  1388. ))]
  1389. if let Ok(gtk_window) = window.gtk_window() {
  1390. let _ = tx.send(menu_.inner().is_visible_on_gtk_window(&gtk_window));
  1391. }
  1392. })?;
  1393. return Ok(rx.recv().unwrap_or(false));
  1394. }
  1395. Ok(false)
  1396. }
  1397. /// Shows the specified menu as a context menu at the cursor position.
  1398. pub fn popup_menu<M: ContextMenu>(&self, menu: &M) -> crate::Result<()> {
  1399. menu.popup(self.clone())
  1400. }
  1401. /// Shows the specified menu as a context menu at the specified position.
  1402. ///
  1403. /// The position is relative to the window's top-left corner.
  1404. pub fn popup_menu_at<M: ContextMenu, P: Into<Position>>(
  1405. &self,
  1406. menu: &M,
  1407. position: P,
  1408. ) -> crate::Result<()> {
  1409. menu.popup_at(self.clone(), position)
  1410. }
  1411. }
  1412. /// Window getters.
  1413. impl<R: Runtime> Window<R> {
  1414. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  1415. pub fn scale_factor(&self) -> crate::Result<f64> {
  1416. self.window.dispatcher.scale_factor().map_err(Into::into)
  1417. }
  1418. /// 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.
  1419. pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1420. self.window.dispatcher.inner_position().map_err(Into::into)
  1421. }
  1422. /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
  1423. pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1424. self.window.dispatcher.outer_position().map_err(Into::into)
  1425. }
  1426. /// Returns the physical size of the window's client area.
  1427. ///
  1428. /// The client area is the content of the window, excluding the title bar and borders.
  1429. pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1430. self.window.dispatcher.inner_size().map_err(Into::into)
  1431. }
  1432. /// Returns the physical size of the entire window.
  1433. ///
  1434. /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
  1435. pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1436. self.window.dispatcher.outer_size().map_err(Into::into)
  1437. }
  1438. /// Gets the window's current fullscreen state.
  1439. pub fn is_fullscreen(&self) -> crate::Result<bool> {
  1440. self.window.dispatcher.is_fullscreen().map_err(Into::into)
  1441. }
  1442. /// Gets the window's current minimized state.
  1443. pub fn is_minimized(&self) -> crate::Result<bool> {
  1444. self.window.dispatcher.is_minimized().map_err(Into::into)
  1445. }
  1446. /// Gets the window's current maximized state.
  1447. pub fn is_maximized(&self) -> crate::Result<bool> {
  1448. self.window.dispatcher.is_maximized().map_err(Into::into)
  1449. }
  1450. /// Gets the window's current focus state.
  1451. pub fn is_focused(&self) -> crate::Result<bool> {
  1452. self.window.dispatcher.is_focused().map_err(Into::into)
  1453. }
  1454. /// Gets the window’s current decoration state.
  1455. pub fn is_decorated(&self) -> crate::Result<bool> {
  1456. self.window.dispatcher.is_decorated().map_err(Into::into)
  1457. }
  1458. /// Gets the window’s current resizable state.
  1459. pub fn is_resizable(&self) -> crate::Result<bool> {
  1460. self.window.dispatcher.is_resizable().map_err(Into::into)
  1461. }
  1462. /// Gets the window’s native maximize button state
  1463. ///
  1464. /// ## Platform-specific
  1465. ///
  1466. /// - **Linux / iOS / Android:** Unsupported.
  1467. pub fn is_maximizable(&self) -> crate::Result<bool> {
  1468. self.window.dispatcher.is_maximizable().map_err(Into::into)
  1469. }
  1470. /// Gets the window’s native minimize button state
  1471. ///
  1472. /// ## Platform-specific
  1473. ///
  1474. /// - **Linux / iOS / Android:** Unsupported.
  1475. pub fn is_minimizable(&self) -> crate::Result<bool> {
  1476. self.window.dispatcher.is_minimizable().map_err(Into::into)
  1477. }
  1478. /// Gets the window’s native close button state
  1479. ///
  1480. /// ## Platform-specific
  1481. ///
  1482. /// - **Linux / iOS / Android:** Unsupported.
  1483. pub fn is_closable(&self) -> crate::Result<bool> {
  1484. self.window.dispatcher.is_closable().map_err(Into::into)
  1485. }
  1486. /// Gets the window's current visibility state.
  1487. pub fn is_visible(&self) -> crate::Result<bool> {
  1488. self.window.dispatcher.is_visible().map_err(Into::into)
  1489. }
  1490. /// Gets the window's current title.
  1491. pub fn title(&self) -> crate::Result<String> {
  1492. self.window.dispatcher.title().map_err(Into::into)
  1493. }
  1494. /// Returns the monitor on which the window currently resides.
  1495. ///
  1496. /// Returns None if current monitor can't be detected.
  1497. pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
  1498. self
  1499. .window
  1500. .dispatcher
  1501. .current_monitor()
  1502. .map(|m| m.map(Into::into))
  1503. .map_err(Into::into)
  1504. }
  1505. /// Returns the primary monitor of the system.
  1506. ///
  1507. /// Returns None if it can't identify any monitor as a primary one.
  1508. pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
  1509. self
  1510. .window
  1511. .dispatcher
  1512. .primary_monitor()
  1513. .map(|m| m.map(Into::into))
  1514. .map_err(Into::into)
  1515. }
  1516. /// Returns the list of all the monitors available on the system.
  1517. pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
  1518. self
  1519. .window
  1520. .dispatcher
  1521. .available_monitors()
  1522. .map(|m| m.into_iter().map(Into::into).collect())
  1523. .map_err(Into::into)
  1524. }
  1525. /// Returns the native handle that is used by this window.
  1526. #[cfg(target_os = "macos")]
  1527. pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> {
  1528. self
  1529. .window
  1530. .dispatcher
  1531. .raw_window_handle()
  1532. .map_err(Into::into)
  1533. .and_then(|handle| {
  1534. if let raw_window_handle::RawWindowHandle::AppKit(h) = handle {
  1535. Ok(h.ns_window)
  1536. } else {
  1537. Err(crate::Error::InvalidWindowHandle)
  1538. }
  1539. })
  1540. }
  1541. /// Returns the pointer to the content view of this window.
  1542. #[cfg(target_os = "macos")]
  1543. pub fn ns_view(&self) -> crate::Result<*mut std::ffi::c_void> {
  1544. self
  1545. .window
  1546. .dispatcher
  1547. .raw_window_handle()
  1548. .map_err(Into::into)
  1549. .and_then(|handle| {
  1550. if let raw_window_handle::RawWindowHandle::AppKit(h) = handle {
  1551. Ok(h.ns_view)
  1552. } else {
  1553. Err(crate::Error::InvalidWindowHandle)
  1554. }
  1555. })
  1556. }
  1557. /// Returns the native handle that is used by this window.
  1558. #[cfg(windows)]
  1559. pub fn hwnd(&self) -> crate::Result<HWND> {
  1560. self
  1561. .window
  1562. .dispatcher
  1563. .raw_window_handle()
  1564. .map_err(Into::into)
  1565. .and_then(|handle| {
  1566. if let raw_window_handle::RawWindowHandle::Win32(h) = handle {
  1567. Ok(HWND(h.hwnd as _))
  1568. } else {
  1569. Err(crate::Error::InvalidWindowHandle)
  1570. }
  1571. })
  1572. }
  1573. /// Returns the `ApplicationWindow` from gtk crate that is used by this window.
  1574. ///
  1575. /// Note that this type can only be used on the main thread.
  1576. #[cfg(any(
  1577. target_os = "linux",
  1578. target_os = "dragonfly",
  1579. target_os = "freebsd",
  1580. target_os = "netbsd",
  1581. target_os = "openbsd"
  1582. ))]
  1583. pub fn gtk_window(&self) -> crate::Result<gtk::ApplicationWindow> {
  1584. self.window.dispatcher.gtk_window().map_err(Into::into)
  1585. }
  1586. /// Returns the vertical [`gtk::Box`] that is added by default as the sole child of this window.
  1587. ///
  1588. /// Note that this type can only be used on the main thread.
  1589. #[cfg(any(
  1590. target_os = "linux",
  1591. target_os = "dragonfly",
  1592. target_os = "freebsd",
  1593. target_os = "netbsd",
  1594. target_os = "openbsd"
  1595. ))]
  1596. pub fn default_vbox(&self) -> crate::Result<gtk::Box> {
  1597. self.window.dispatcher.default_vbox().map_err(Into::into)
  1598. }
  1599. /// Returns the current window theme.
  1600. ///
  1601. /// ## Platform-specific
  1602. ///
  1603. /// - **macOS**: Only supported on macOS 10.14+.
  1604. pub fn theme(&self) -> crate::Result<Theme> {
  1605. self.window.dispatcher.theme().map_err(Into::into)
  1606. }
  1607. }
  1608. /// Desktop window setters and actions.
  1609. #[cfg(desktop)]
  1610. impl<R: Runtime> Window<R> {
  1611. /// Centers the window.
  1612. pub fn center(&self) -> crate::Result<()> {
  1613. self.window.dispatcher.center().map_err(Into::into)
  1614. }
  1615. /// Requests user attention to the window, this has no effect if the application
  1616. /// is already focused. How requesting for user attention manifests is platform dependent,
  1617. /// see `UserAttentionType` for details.
  1618. ///
  1619. /// Providing `None` will unset the request for user attention. Unsetting the request for
  1620. /// user attention might not be done automatically by the WM when the window receives input.
  1621. ///
  1622. /// ## Platform-specific
  1623. ///
  1624. /// - **macOS:** `None` has no effect.
  1625. /// - **Linux:** Urgency levels have the same effect.
  1626. pub fn request_user_attention(
  1627. &self,
  1628. request_type: Option<UserAttentionType>,
  1629. ) -> crate::Result<()> {
  1630. self
  1631. .window
  1632. .dispatcher
  1633. .request_user_attention(request_type)
  1634. .map_err(Into::into)
  1635. }
  1636. /// Opens the dialog to prints the contents of the webview.
  1637. /// Currently only supported on macOS on `wry`.
  1638. /// `window.print()` works on all platforms.
  1639. pub fn print(&self) -> crate::Result<()> {
  1640. self.window.dispatcher.print().map_err(Into::into)
  1641. }
  1642. /// Determines if this window should be resizable.
  1643. /// When resizable is set to false, native window's maximize button is automatically disabled.
  1644. pub fn set_resizable(&self, resizable: bool) -> crate::Result<()> {
  1645. self
  1646. .window
  1647. .dispatcher
  1648. .set_resizable(resizable)
  1649. .map_err(Into::into)
  1650. }
  1651. /// Determines if this window's native maximize button should be enabled.
  1652. /// If resizable is set to false, this setting is ignored.
  1653. ///
  1654. /// ## Platform-specific
  1655. ///
  1656. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  1657. /// - **Linux / iOS / Android:** Unsupported.
  1658. pub fn set_maximizable(&self, maximizable: bool) -> crate::Result<()> {
  1659. self
  1660. .window
  1661. .dispatcher
  1662. .set_maximizable(maximizable)
  1663. .map_err(Into::into)
  1664. }
  1665. /// Determines if this window's native minize button should be enabled.
  1666. ///
  1667. /// ## Platform-specific
  1668. ///
  1669. /// - **Linux / iOS / Android:** Unsupported.
  1670. pub fn set_minimizable(&self, minimizable: bool) -> crate::Result<()> {
  1671. self
  1672. .window
  1673. .dispatcher
  1674. .set_minimizable(minimizable)
  1675. .map_err(Into::into)
  1676. }
  1677. /// Determines if this window's native close button should be enabled.
  1678. ///
  1679. /// ## Platform-specific
  1680. ///
  1681. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  1682. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  1683. /// - **iOS / Android:** Unsupported.
  1684. pub fn set_closable(&self, closable: bool) -> crate::Result<()> {
  1685. self
  1686. .window
  1687. .dispatcher
  1688. .set_closable(closable)
  1689. .map_err(Into::into)
  1690. }
  1691. /// Set this window's title.
  1692. pub fn set_title(&self, title: &str) -> crate::Result<()> {
  1693. self
  1694. .window
  1695. .dispatcher
  1696. .set_title(title.to_string())
  1697. .map_err(Into::into)
  1698. }
  1699. /// Maximizes this window.
  1700. pub fn maximize(&self) -> crate::Result<()> {
  1701. self.window.dispatcher.maximize().map_err(Into::into)
  1702. }
  1703. /// Un-maximizes this window.
  1704. pub fn unmaximize(&self) -> crate::Result<()> {
  1705. self.window.dispatcher.unmaximize().map_err(Into::into)
  1706. }
  1707. /// Minimizes this window.
  1708. pub fn minimize(&self) -> crate::Result<()> {
  1709. self.window.dispatcher.minimize().map_err(Into::into)
  1710. }
  1711. /// Un-minimizes this window.
  1712. pub fn unminimize(&self) -> crate::Result<()> {
  1713. self.window.dispatcher.unminimize().map_err(Into::into)
  1714. }
  1715. /// Show this window.
  1716. pub fn show(&self) -> crate::Result<()> {
  1717. self.window.dispatcher.show().map_err(Into::into)
  1718. }
  1719. /// Hide this window.
  1720. pub fn hide(&self) -> crate::Result<()> {
  1721. self.window.dispatcher.hide().map_err(Into::into)
  1722. }
  1723. /// Closes this window.
  1724. /// # Panics
  1725. ///
  1726. /// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
  1727. /// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
  1728. ///
  1729. /// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
  1730. pub fn close(&self) -> crate::Result<()> {
  1731. self.window.dispatcher.close().map_err(Into::into)
  1732. }
  1733. /// Determines if this window should be [decorated].
  1734. ///
  1735. /// [decorated]: https://en.wikipedia.org/wiki/Window_(computing)#Window_decoration
  1736. pub fn set_decorations(&self, decorations: bool) -> crate::Result<()> {
  1737. self
  1738. .window
  1739. .dispatcher
  1740. .set_decorations(decorations)
  1741. .map_err(Into::into)
  1742. }
  1743. /// Determines if this window should have shadow.
  1744. ///
  1745. /// ## Platform-specific
  1746. ///
  1747. /// - **Windows:**
  1748. /// - `false` has no effect on decorated window, shadow are always ON.
  1749. /// - `true` will make ndecorated window have a 1px white border,
  1750. /// and on Windows 11, it will have a rounded corners.
  1751. /// - **Linux:** Unsupported.
  1752. pub fn set_shadow(&self, enable: bool) -> crate::Result<()> {
  1753. self
  1754. .window
  1755. .dispatcher
  1756. .set_shadow(enable)
  1757. .map_err(Into::into)
  1758. }
  1759. /// Sets window effects, pass [`None`] to clear any effects applied if possible.
  1760. ///
  1761. /// Requires the window to be transparent.
  1762. ///
  1763. /// See [`EffectsBuilder`] for a convenient builder for [`WindowEffectsConfig`].
  1764. ///
  1765. ///
  1766. /// ```rust,no_run
  1767. /// use tauri::{Manager, window::{Color, Effect, EffectState, EffectsBuilder}};
  1768. /// tauri::Builder::default()
  1769. /// .setup(|app| {
  1770. /// let window = app.get_window("main").unwrap();
  1771. /// window.set_effects(
  1772. /// EffectsBuilder::new()
  1773. /// .effect(Effect::Popover)
  1774. /// .state(EffectState::Active)
  1775. /// .radius(5.)
  1776. /// .color(Color(0, 0, 0, 255))
  1777. /// .build(),
  1778. /// )?;
  1779. /// Ok(())
  1780. /// });
  1781. /// ```
  1782. ///
  1783. /// ## Platform-specific:
  1784. ///
  1785. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  1786. /// - **Linux**: Unsupported
  1787. pub fn set_effects<E: Into<Option<WindowEffectsConfig>>>(&self, effects: E) -> crate::Result<()> {
  1788. let effects = effects.into();
  1789. let window = self.clone();
  1790. self.run_on_main_thread(move || {
  1791. let _ = crate::vibrancy::set_window_effects(&window, effects);
  1792. })
  1793. }
  1794. /// Determines if this window should always be below other windows.
  1795. pub fn set_always_on_bottom(&self, always_on_bottom: bool) -> crate::Result<()> {
  1796. self
  1797. .window
  1798. .dispatcher
  1799. .set_always_on_bottom(always_on_bottom)
  1800. .map_err(Into::into)
  1801. }
  1802. /// Determines if this window should always be on top of other windows.
  1803. pub fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> {
  1804. self
  1805. .window
  1806. .dispatcher
  1807. .set_always_on_top(always_on_top)
  1808. .map_err(Into::into)
  1809. }
  1810. /// Sets whether the window should be visible on all workspaces or virtual desktops.
  1811. pub fn set_visible_on_all_workspaces(
  1812. &self,
  1813. visible_on_all_workspaces: bool,
  1814. ) -> crate::Result<()> {
  1815. self
  1816. .window
  1817. .dispatcher
  1818. .set_visible_on_all_workspaces(visible_on_all_workspaces)
  1819. .map_err(Into::into)
  1820. }
  1821. /// Prevents the window contents from being captured by other apps.
  1822. pub fn set_content_protected(&self, protected: bool) -> crate::Result<()> {
  1823. self
  1824. .window
  1825. .dispatcher
  1826. .set_content_protected(protected)
  1827. .map_err(Into::into)
  1828. }
  1829. /// Resizes this window.
  1830. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
  1831. self
  1832. .window
  1833. .dispatcher
  1834. .set_size(size.into())
  1835. .map_err(Into::into)
  1836. }
  1837. /// Sets this window's minimum size.
  1838. pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1839. self
  1840. .window
  1841. .dispatcher
  1842. .set_min_size(size.map(|s| s.into()))
  1843. .map_err(Into::into)
  1844. }
  1845. /// Sets this window's maximum size.
  1846. pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1847. self
  1848. .window
  1849. .dispatcher
  1850. .set_max_size(size.map(|s| s.into()))
  1851. .map_err(Into::into)
  1852. }
  1853. /// Sets this window's position.
  1854. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1855. self
  1856. .window
  1857. .dispatcher
  1858. .set_position(position.into())
  1859. .map_err(Into::into)
  1860. }
  1861. /// Determines if this window should be fullscreen.
  1862. pub fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
  1863. self
  1864. .window
  1865. .dispatcher
  1866. .set_fullscreen(fullscreen)
  1867. .map_err(Into::into)
  1868. }
  1869. /// Bring the window to front and focus.
  1870. pub fn set_focus(&self) -> crate::Result<()> {
  1871. self.window.dispatcher.set_focus().map_err(Into::into)
  1872. }
  1873. /// Sets this window' icon.
  1874. pub fn set_icon(&self, icon: Icon) -> crate::Result<()> {
  1875. self
  1876. .window
  1877. .dispatcher
  1878. .set_icon(icon.try_into()?)
  1879. .map_err(Into::into)
  1880. }
  1881. /// Whether to hide the window icon from the taskbar or not.
  1882. ///
  1883. /// ## Platform-specific
  1884. ///
  1885. /// - **macOS:** Unsupported.
  1886. pub fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> {
  1887. self
  1888. .window
  1889. .dispatcher
  1890. .set_skip_taskbar(skip)
  1891. .map_err(Into::into)
  1892. }
  1893. /// Grabs the cursor, preventing it from leaving the window.
  1894. ///
  1895. /// There's no guarantee that the cursor will be hidden. You should
  1896. /// hide it by yourself if you want so.
  1897. ///
  1898. /// ## Platform-specific
  1899. ///
  1900. /// - **Linux:** Unsupported.
  1901. /// - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
  1902. pub fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
  1903. self
  1904. .window
  1905. .dispatcher
  1906. .set_cursor_grab(grab)
  1907. .map_err(Into::into)
  1908. }
  1909. /// Modifies the cursor's visibility.
  1910. ///
  1911. /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
  1912. ///
  1913. /// ## Platform-specific
  1914. ///
  1915. /// - **Windows:** The cursor is only hidden within the confines of the window.
  1916. /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
  1917. /// outside of the window.
  1918. pub fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
  1919. self
  1920. .window
  1921. .dispatcher
  1922. .set_cursor_visible(visible)
  1923. .map_err(Into::into)
  1924. }
  1925. /// Modifies the cursor icon of the window.
  1926. pub fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
  1927. self
  1928. .window
  1929. .dispatcher
  1930. .set_cursor_icon(icon)
  1931. .map_err(Into::into)
  1932. }
  1933. /// Changes the position of the cursor in window coordinates.
  1934. pub fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1935. self
  1936. .window
  1937. .dispatcher
  1938. .set_cursor_position(position)
  1939. .map_err(Into::into)
  1940. }
  1941. /// Ignores the window cursor events.
  1942. pub fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
  1943. self
  1944. .window
  1945. .dispatcher
  1946. .set_ignore_cursor_events(ignore)
  1947. .map_err(Into::into)
  1948. }
  1949. /// Starts dragging the window.
  1950. pub fn start_dragging(&self) -> crate::Result<()> {
  1951. self.window.dispatcher.start_dragging().map_err(Into::into)
  1952. }
  1953. /// Sets the taskbar progress state.
  1954. ///
  1955. /// ## Platform-specific
  1956. ///
  1957. /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window.
  1958. /// - **Linux**: Only supported desktop environments with `libunity` (e.g. GNOME).
  1959. /// - **iOS / Android:** Unsupported.
  1960. pub fn set_progress_bar(
  1961. &self,
  1962. progress_state: crate::utils::ProgressBarState,
  1963. ) -> crate::Result<()> {
  1964. self
  1965. .window
  1966. .dispatcher
  1967. .set_progress_bar(progress_state)
  1968. .map_err(Into::into)
  1969. }
  1970. }
  1971. /// Webview APIs.
  1972. impl<R: Runtime> Window<R> {
  1973. /// Returns the current url of the webview.
  1974. // TODO: in v2, change this type to Result
  1975. pub fn url(&self) -> Url {
  1976. self.window.dispatcher.url().unwrap()
  1977. }
  1978. /// Navigates the webview to the defined url.
  1979. pub fn navigate(&mut self, url: Url) {
  1980. self.window.dispatcher.navigate(url).unwrap();
  1981. }
  1982. fn is_local_url(&self, current_url: &Url) -> bool {
  1983. self.manager.get_url().make_relative(current_url).is_some()
  1984. || {
  1985. let protocol_url = self.manager.protocol_url();
  1986. current_url.scheme() == protocol_url.scheme()
  1987. && current_url.domain() == protocol_url.domain()
  1988. }
  1989. || (cfg!(dev) && current_url.domain() == Some("tauri.localhost"))
  1990. }
  1991. /// Handles this window receiving an [`InvokeRequest`].
  1992. pub fn on_message(self, request: InvokeRequest, responder: Box<OwnedInvokeResponder<R>>) {
  1993. let manager = self.manager.clone();
  1994. let current_url = self.url();
  1995. let is_local = self.is_local_url(&current_url);
  1996. let mut scope_not_found_error_message =
  1997. ipc_scope_not_found_error_message(&self.window.label, current_url.as_str());
  1998. let scope = if is_local {
  1999. None
  2000. } else {
  2001. match self.ipc_scope().remote_access_for(&self, &current_url) {
  2002. Ok(scope) => Some(scope),
  2003. Err(e) => {
  2004. if e.matches_window {
  2005. scope_not_found_error_message = ipc_scope_domain_error_message(current_url.as_str());
  2006. } else if e.matches_domain {
  2007. scope_not_found_error_message = ipc_scope_window_error_message(&self.window.label);
  2008. }
  2009. None
  2010. }
  2011. }
  2012. };
  2013. let custom_responder = self.manager.invoke_responder();
  2014. let resolver = InvokeResolver::new(
  2015. self.clone(),
  2016. Arc::new(Mutex::new(Some(Box::new(
  2017. #[allow(unused_variables)]
  2018. move |window: Window<R>, cmd, response, callback, error| {
  2019. if let Some(responder) = &custom_responder {
  2020. (responder)(&window, &cmd, &response, callback, error);
  2021. }
  2022. responder(window, cmd, response, callback, error);
  2023. },
  2024. )))),
  2025. request.cmd.clone(),
  2026. request.callback,
  2027. request.error,
  2028. );
  2029. #[cfg(mobile)]
  2030. let app_handle = self.app_handle.clone();
  2031. let message = InvokeMessage::new(
  2032. self,
  2033. manager.state(),
  2034. request.cmd.to_string(),
  2035. request.body,
  2036. request.headers,
  2037. );
  2038. let mut invoke = Invoke {
  2039. message,
  2040. resolver: resolver.clone(),
  2041. };
  2042. if !is_local && scope.is_none() {
  2043. invoke.resolver.reject(scope_not_found_error_message);
  2044. } else if request.cmd.starts_with("plugin:") {
  2045. let command = invoke.message.command.replace("plugin:", "");
  2046. let mut tokens = command.split('|');
  2047. // safe to unwrap: split always has a least one item
  2048. let plugin = tokens.next().unwrap();
  2049. invoke.message.command = tokens
  2050. .next()
  2051. .map(|c| c.to_string())
  2052. .unwrap_or_else(String::new);
  2053. if !(is_local
  2054. || plugin == crate::ipc::channel::CHANNEL_PLUGIN_NAME
  2055. || scope
  2056. .map(|s| s.plugins().contains(&plugin.into()))
  2057. .unwrap_or(true))
  2058. {
  2059. invoke.resolver.reject(IPC_SCOPE_DOES_NOT_ALLOW);
  2060. return;
  2061. }
  2062. let command = invoke.message.command.clone();
  2063. #[cfg(mobile)]
  2064. let message = invoke.message.clone();
  2065. #[allow(unused_mut)]
  2066. let mut handled = manager.extend_api(plugin, invoke);
  2067. #[cfg(mobile)]
  2068. {
  2069. if !handled {
  2070. handled = true;
  2071. fn load_channels<R: Runtime>(payload: &serde_json::Value, window: &Window<R>) {
  2072. if let serde_json::Value::Object(map) = payload {
  2073. for v in map.values() {
  2074. if let serde_json::Value::String(s) = v {
  2075. if s.starts_with(crate::ipc::channel::IPC_PAYLOAD_PREFIX) {
  2076. crate::ipc::Channel::load_from_ipc(window.clone(), s);
  2077. }
  2078. }
  2079. }
  2080. }
  2081. }
  2082. let payload = message.payload.into_json();
  2083. // initialize channels
  2084. load_channels(&payload, &message.window);
  2085. let resolver_ = resolver.clone();
  2086. if let Err(e) = crate::plugin::mobile::run_command(
  2087. plugin,
  2088. &app_handle,
  2089. message.command,
  2090. payload,
  2091. move |response| match response {
  2092. Ok(r) => resolver_.resolve(r),
  2093. Err(e) => resolver_.reject(e),
  2094. },
  2095. ) {
  2096. resolver.reject(e.to_string());
  2097. return;
  2098. }
  2099. }
  2100. }
  2101. if !handled {
  2102. resolver.reject(format!("Command {command} not found"));
  2103. }
  2104. } else {
  2105. let command = invoke.message.command.clone();
  2106. let handled = manager.run_invoke_handler(invoke);
  2107. if !handled {
  2108. resolver.reject(format!("Command {command} not found"));
  2109. }
  2110. }
  2111. }
  2112. /// Evaluates JavaScript on this window.
  2113. pub fn eval(&self, js: &str) -> crate::Result<()> {
  2114. self.window.dispatcher.eval_script(js).map_err(Into::into)
  2115. }
  2116. /// Register a JS event listener and return its identifier.
  2117. pub(crate) fn listen_js(
  2118. &self,
  2119. window_label: Option<String>,
  2120. event: String,
  2121. handler: CallbackFn,
  2122. ) -> crate::Result<EventId> {
  2123. let event_id = self.manager.listeners().next_event_id();
  2124. self.eval(&crate::event::listen_js(
  2125. self.manager().listeners().listeners_object_name(),
  2126. &format!("'{}'", event),
  2127. event_id,
  2128. window_label.as_deref(),
  2129. &format!("window['_{}']", handler.0),
  2130. ))?;
  2131. self
  2132. .js_event_listeners
  2133. .lock()
  2134. .unwrap()
  2135. .entry(JsEventListenerKey {
  2136. window_label,
  2137. event,
  2138. })
  2139. .or_default()
  2140. .insert(event_id);
  2141. Ok(event_id)
  2142. }
  2143. /// Unregister a JS event listener.
  2144. pub(crate) fn unlisten_js(&self, event: &str, id: EventId) -> crate::Result<()> {
  2145. self.eval(&crate::event::unlisten_js(
  2146. self.manager().listeners().listeners_object_name(),
  2147. event,
  2148. id,
  2149. ))?;
  2150. let mut empty = None;
  2151. let mut js_listeners = self.js_event_listeners.lock().unwrap();
  2152. let iter = js_listeners.iter_mut();
  2153. for (key, ids) in iter {
  2154. if ids.contains(&id) {
  2155. ids.remove(&id);
  2156. if ids.is_empty() {
  2157. empty.replace(key.clone());
  2158. }
  2159. break;
  2160. }
  2161. }
  2162. if let Some(key) = empty {
  2163. js_listeners.remove(&key);
  2164. }
  2165. Ok(())
  2166. }
  2167. pub(crate) fn emit_js(&self, emit_args: &EmitArgs) -> crate::Result<()> {
  2168. self.eval(&crate::event::emit_js(
  2169. self.manager().listeners().function_name(),
  2170. emit_args,
  2171. )?)?;
  2172. Ok(())
  2173. }
  2174. /// Whether this window registered a listener to an event from the given window and event name.
  2175. pub(crate) fn has_js_listener(&self, window_label: Option<String>, event: &str) -> bool {
  2176. self
  2177. .js_event_listeners
  2178. .lock()
  2179. .unwrap()
  2180. .contains_key(&JsEventListenerKey {
  2181. window_label,
  2182. event: event.into(),
  2183. })
  2184. }
  2185. /// Opens the developer tools window (Web Inspector).
  2186. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  2187. ///
  2188. /// ## Platform-specific
  2189. ///
  2190. /// - **macOS:** Only supported on macOS 10.15+.
  2191. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  2192. ///
  2193. /// # Examples
  2194. ///
  2195. /// ```rust,no_run
  2196. /// use tauri::Manager;
  2197. /// tauri::Builder::default()
  2198. /// .setup(|app| {
  2199. /// #[cfg(debug_assertions)]
  2200. /// app.get_window("main").unwrap().open_devtools();
  2201. /// Ok(())
  2202. /// });
  2203. /// ```
  2204. #[cfg(any(debug_assertions, feature = "devtools"))]
  2205. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  2206. pub fn open_devtools(&self) {
  2207. self.window.dispatcher.open_devtools();
  2208. }
  2209. /// Closes the developer tools window (Web Inspector).
  2210. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  2211. ///
  2212. /// ## Platform-specific
  2213. ///
  2214. /// - **macOS:** Only supported on macOS 10.15+.
  2215. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  2216. /// - **Windows:** Unsupported.
  2217. ///
  2218. /// # Examples
  2219. ///
  2220. /// ```rust,no_run
  2221. /// use tauri::Manager;
  2222. /// tauri::Builder::default()
  2223. /// .setup(|app| {
  2224. /// #[cfg(debug_assertions)]
  2225. /// {
  2226. /// let window = app.get_window("main").unwrap();
  2227. /// window.open_devtools();
  2228. /// std::thread::spawn(move || {
  2229. /// std::thread::sleep(std::time::Duration::from_secs(10));
  2230. /// window.close_devtools();
  2231. /// });
  2232. /// }
  2233. /// Ok(())
  2234. /// });
  2235. /// ```
  2236. #[cfg(any(debug_assertions, feature = "devtools"))]
  2237. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  2238. pub fn close_devtools(&self) {
  2239. self.window.dispatcher.close_devtools();
  2240. }
  2241. /// Checks if the developer tools window (Web Inspector) is opened.
  2242. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  2243. ///
  2244. /// ## Platform-specific
  2245. ///
  2246. /// - **macOS:** Only supported on macOS 10.15+.
  2247. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  2248. /// - **Windows:** Unsupported.
  2249. ///
  2250. /// # Examples
  2251. ///
  2252. /// ```rust,no_run
  2253. /// use tauri::Manager;
  2254. /// tauri::Builder::default()
  2255. /// .setup(|app| {
  2256. /// #[cfg(debug_assertions)]
  2257. /// {
  2258. /// let window = app.get_window("main").unwrap();
  2259. /// if !window.is_devtools_open() {
  2260. /// window.open_devtools();
  2261. /// }
  2262. /// }
  2263. /// Ok(())
  2264. /// });
  2265. /// ```
  2266. #[cfg(any(debug_assertions, feature = "devtools"))]
  2267. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  2268. pub fn is_devtools_open(&self) -> bool {
  2269. self
  2270. .window
  2271. .dispatcher
  2272. .is_devtools_open()
  2273. .unwrap_or_default()
  2274. }
  2275. }
  2276. /// Event system APIs.
  2277. impl<R: Runtime> Window<R> {
  2278. /// Listen to an event on this window.
  2279. ///
  2280. /// # Examples
  2281. /// ```
  2282. /// use tauri::Manager;
  2283. ///
  2284. /// tauri::Builder::default()
  2285. /// .setup(|app| {
  2286. /// let window = app.get_window("main").unwrap();
  2287. /// window.listen("component-loaded", move |event| {
  2288. /// println!("window just loaded a component");
  2289. /// });
  2290. ///
  2291. /// Ok(())
  2292. /// });
  2293. /// ```
  2294. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
  2295. where
  2296. F: Fn(Event) + Send + 'static,
  2297. {
  2298. self
  2299. .manager
  2300. .listen(event.into(), Some(self.clone()), handler)
  2301. }
  2302. /// Unlisten to an event on this window.
  2303. ///
  2304. /// # Examples
  2305. /// ```
  2306. /// use tauri::Manager;
  2307. ///
  2308. /// tauri::Builder::default()
  2309. /// .setup(|app| {
  2310. /// let window = app.get_window("main").unwrap();
  2311. /// let window_ = window.clone();
  2312. /// let handler = window.listen("component-loaded", move |event| {
  2313. /// println!("window just loaded a component");
  2314. ///
  2315. /// // we no longer need to listen to the event
  2316. /// // we also could have used `window.once` instead
  2317. /// window_.unlisten(event.id());
  2318. /// });
  2319. ///
  2320. /// // stop listening to the event when you do not need it anymore
  2321. /// window.unlisten(handler);
  2322. ///
  2323. ///
  2324. /// Ok(())
  2325. /// });
  2326. /// ```
  2327. pub fn unlisten(&self, id: EventId) {
  2328. self.manager.unlisten(id)
  2329. }
  2330. /// Listen to an event on this window only once.
  2331. ///
  2332. /// See [`Self::listen`] for more information.
  2333. pub fn once<F>(&self, event: impl Into<String>, handler: F)
  2334. where
  2335. F: FnOnce(Event) + Send + 'static,
  2336. {
  2337. let label = self.window.label.clone();
  2338. self.manager.once(event.into(), Some(label), handler)
  2339. }
  2340. }
  2341. /// The [`WindowEffectsConfig`] object builder
  2342. #[derive(Default)]
  2343. pub struct EffectsBuilder(WindowEffectsConfig);
  2344. impl EffectsBuilder {
  2345. /// Create a new [`WindowEffectsConfig`] builder
  2346. pub fn new() -> Self {
  2347. Self(WindowEffectsConfig::default())
  2348. }
  2349. /// Adds effect to the [`WindowEffectsConfig`] `effects` field
  2350. pub fn effect(mut self, effect: Effect) -> Self {
  2351. self.0.effects.push(effect);
  2352. self
  2353. }
  2354. /// Adds effects to the [`WindowEffectsConfig`] `effects` field
  2355. pub fn effects<I: IntoIterator<Item = Effect>>(mut self, effects: I) -> Self {
  2356. self.0.effects.extend(effects);
  2357. self
  2358. }
  2359. /// Clears the [`WindowEffectsConfig`] `effects` field
  2360. pub fn clear_effects(mut self) -> Self {
  2361. self.0.effects.clear();
  2362. self
  2363. }
  2364. /// Sets `state` field for the [`WindowEffectsConfig`] **macOS Only**
  2365. pub fn state(mut self, state: EffectState) -> Self {
  2366. self.0.state = Some(state);
  2367. self
  2368. }
  2369. /// Sets `radius` field fo the [`WindowEffectsConfig`] **macOS Only**
  2370. pub fn radius(mut self, radius: f64) -> Self {
  2371. self.0.radius = Some(radius);
  2372. self
  2373. }
  2374. /// Sets `color` field fo the [`WindowEffectsConfig`] **Windows Only**
  2375. pub fn color(mut self, color: Color) -> Self {
  2376. self.0.color = Some(color);
  2377. self
  2378. }
  2379. /// Builds a [`WindowEffectsConfig`]
  2380. pub fn build(self) -> WindowEffectsConfig {
  2381. self.0
  2382. }
  2383. }
  2384. impl From<WindowEffectsConfig> for EffectsBuilder {
  2385. fn from(value: WindowEffectsConfig) -> Self {
  2386. Self(value)
  2387. }
  2388. }
  2389. pub(crate) const IPC_SCOPE_DOES_NOT_ALLOW: &str = "Not allowed by the scope";
  2390. pub(crate) fn ipc_scope_not_found_error_message(label: &str, url: &str) -> String {
  2391. format!("Scope not defined for window `{label}` and URL `{url}`. See https://tauri.app/v1/api/config/#securityconfig.dangerousremotedomainipcaccess and https://docs.rs/tauri/1/tauri/scope/struct.IpcScope.html#method.configure_remote_access")
  2392. }
  2393. pub(crate) fn ipc_scope_window_error_message(label: &str) -> String {
  2394. format!("Scope not defined for window `{}`. See https://tauri.app/v1/api/config/#securityconfig.dangerousremotedomainipcaccess and https://docs.rs/tauri/1/tauri/scope/struct.IpcScope.html#method.configure_remote_access", label)
  2395. }
  2396. pub(crate) fn ipc_scope_domain_error_message(url: &str) -> String {
  2397. format!("Scope not defined for URL `{url}`. See https://tauri.app/v1/api/config/#securityconfig.dangerousremotedomainipcaccess and https://docs.rs/tauri/1/tauri/scope/struct.IpcScope.html#method.configure_remote_access")
  2398. }
  2399. #[cfg(test)]
  2400. mod tests {
  2401. #[test]
  2402. fn window_is_send_sync() {
  2403. crate::test_utils::assert_send::<super::Window>();
  2404. crate::test_utils::assert_sync::<super::Window>();
  2405. }
  2406. }