mod.rs 80 KB

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