mod.rs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140
  1. // Copyright 2019-2024 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 tauri_runtime::{
  7. dpi::{PhysicalPosition, PhysicalSize},
  8. webview::PendingWebview,
  9. };
  10. pub use tauri_utils::{config::Color, WindowEffect as Effect, WindowEffectState as EffectState};
  11. #[cfg(desktop)]
  12. pub use crate::runtime::ProgressBarStatus;
  13. use crate::{
  14. app::AppHandle,
  15. event::{Event, EventId, EventTarget},
  16. ipc::{CommandArg, CommandItem, InvokeError},
  17. manager::{webview::WebviewLabelDef, AppManager},
  18. runtime::{
  19. monitor::Monitor as RuntimeMonitor,
  20. window::{DetachedWindow, PendingWindow, WindowBuilder as _},
  21. RuntimeHandle, WindowDispatch,
  22. },
  23. sealed::{ManagerBase, RuntimeOrDispatch},
  24. utils::config::{WindowConfig, WindowEffectsConfig},
  25. webview::WebviewBuilder,
  26. EventLoopMessage, Manager, ResourceTable, Runtime, Theme, Webview, WindowEvent,
  27. };
  28. #[cfg(desktop)]
  29. use crate::{
  30. image::Image,
  31. menu::{ContextMenu, Menu, MenuId},
  32. runtime::{
  33. dpi::{Position, Size},
  34. UserAttentionType,
  35. },
  36. CursorIcon,
  37. };
  38. use serde::Serialize;
  39. #[cfg(windows)]
  40. use windows::Win32::Foundation::HWND;
  41. use tauri_macros::default_runtime;
  42. use std::{
  43. fmt,
  44. hash::{Hash, Hasher},
  45. sync::{Arc, Mutex, MutexGuard},
  46. };
  47. /// Monitor descriptor.
  48. #[derive(Debug, Clone, Serialize)]
  49. #[serde(rename_all = "camelCase")]
  50. pub struct Monitor {
  51. pub(crate) name: Option<String>,
  52. pub(crate) size: PhysicalSize<u32>,
  53. pub(crate) position: PhysicalPosition<i32>,
  54. pub(crate) scale_factor: f64,
  55. }
  56. impl From<RuntimeMonitor> for Monitor {
  57. fn from(monitor: RuntimeMonitor) -> Self {
  58. Self {
  59. name: monitor.name,
  60. size: monitor.size,
  61. position: monitor.position,
  62. scale_factor: monitor.scale_factor,
  63. }
  64. }
  65. }
  66. impl Monitor {
  67. /// Returns a human-readable name of the monitor.
  68. /// Returns None if the monitor doesn't exist anymore.
  69. pub fn name(&self) -> Option<&String> {
  70. self.name.as_ref()
  71. }
  72. /// Returns the monitor's resolution.
  73. pub fn size(&self) -> &PhysicalSize<u32> {
  74. &self.size
  75. }
  76. /// Returns the top-left corner position of the monitor relative to the larger full screen area.
  77. pub fn position(&self) -> &PhysicalPosition<i32> {
  78. &self.position
  79. }
  80. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  81. pub fn scale_factor(&self) -> f64 {
  82. self.scale_factor
  83. }
  84. }
  85. macro_rules! unstable_struct {
  86. (#[doc = $doc:expr] $($tokens:tt)*) => {
  87. #[cfg(feature = "unstable")]
  88. #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
  89. #[doc = $doc]
  90. pub $($tokens)*
  91. #[cfg(not(feature = "unstable"))]
  92. pub(crate) $($tokens)*
  93. }
  94. }
  95. unstable_struct!(
  96. #[doc = "A builder for a window managed by Tauri."]
  97. struct WindowBuilder<'a, R: Runtime, M: Manager<R>> {
  98. manager: &'a M,
  99. pub(crate) label: String,
  100. pub(crate) window_builder:
  101. <R::WindowDispatcher as WindowDispatch<EventLoopMessage>>::WindowBuilder,
  102. #[cfg(desktop)]
  103. pub(crate) menu: Option<Menu<R>>,
  104. #[cfg(desktop)]
  105. on_menu_event: Option<crate::app::GlobalMenuEventListener<Window<R>>>,
  106. window_effects: Option<WindowEffectsConfig>,
  107. }
  108. );
  109. impl<'a, R: Runtime, M: Manager<R>> fmt::Debug for WindowBuilder<'a, R, M> {
  110. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  111. f.debug_struct("WindowBuilder")
  112. .field("label", &self.label)
  113. .field("window_builder", &self.window_builder)
  114. .finish()
  115. }
  116. }
  117. #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
  118. impl<'a, R: Runtime, M: Manager<R>> WindowBuilder<'a, R, M> {
  119. /// Initializes a window builder with the given window label.
  120. ///
  121. /// # Known issues
  122. ///
  123. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  124. /// You should use `async` commands when creating windows.
  125. ///
  126. /// # Examples
  127. ///
  128. /// - Create a window in the setup hook:
  129. ///
  130. #[cfg_attr(
  131. feature = "unstable",
  132. doc = r####"
  133. ```
  134. tauri::Builder::default()
  135. .setup(|app| {
  136. let window = tauri::window::WindowBuilder::new(app, "label")
  137. .build()?;
  138. Ok(())
  139. });
  140. ```
  141. "####
  142. )]
  143. /// - Create a window in a separate thread:
  144. ///
  145. #[cfg_attr(
  146. feature = "unstable",
  147. doc = r####"
  148. ```
  149. tauri::Builder::default()
  150. .setup(|app| {
  151. let handle = app.handle().clone();
  152. std::thread::spawn(move || {
  153. let window = tauri::window::WindowBuilder::new(&handle, "label")
  154. .build()
  155. .unwrap();
  156. });
  157. Ok(())
  158. });
  159. ```
  160. "####
  161. )]
  162. ///
  163. /// - Create a window in a command:
  164. ///
  165. #[cfg_attr(
  166. feature = "unstable",
  167. doc = r####"
  168. ```
  169. #[tauri::command]
  170. async fn create_window(app: tauri::AppHandle) {
  171. let window = tauri::window::WindowBuilder::new(&app, "label")
  172. .build()
  173. .unwrap();
  174. }
  175. ```
  176. "####
  177. )]
  178. ///
  179. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  180. pub fn new<L: Into<String>>(manager: &'a M, label: L) -> Self {
  181. Self {
  182. manager,
  183. label: label.into(),
  184. window_builder: <R::WindowDispatcher as WindowDispatch<EventLoopMessage>>::WindowBuilder::new(
  185. ),
  186. #[cfg(desktop)]
  187. menu: None,
  188. #[cfg(desktop)]
  189. on_menu_event: None,
  190. window_effects: None,
  191. }
  192. }
  193. /// Initializes a window builder from a [`WindowConfig`] from tauri.conf.json.
  194. /// Keep in mind that you can't create 2 windows with the same `label` so make sure
  195. /// that the initial window was closed or change the label of the new [`WindowBuilder`].
  196. ///
  197. /// # Known issues
  198. ///
  199. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  200. /// You should use `async` commands when creating windows.
  201. ///
  202. /// # Examples
  203. ///
  204. /// - Create a window in a command:
  205. ///
  206. #[cfg_attr(
  207. feature = "unstable",
  208. doc = r####"
  209. ```
  210. #[tauri::command]
  211. async fn reopen_window(app: tauri::AppHandle) {
  212. let window = tauri::window::WindowBuilder::from_config(&app, &app.config().app.windows.get(0).unwrap().clone())
  213. .unwrap()
  214. .build()
  215. .unwrap();
  216. }
  217. ```
  218. "####
  219. )]
  220. ///
  221. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  222. pub fn from_config(manager: &'a M, config: &WindowConfig) -> crate::Result<Self> {
  223. #[cfg_attr(not(unstable), allow(unused_mut))]
  224. let mut builder = Self {
  225. manager,
  226. label: config.label.clone(),
  227. window_effects: config.window_effects.clone(),
  228. window_builder:
  229. <R::WindowDispatcher as WindowDispatch<EventLoopMessage>>::WindowBuilder::with_config(
  230. config,
  231. ),
  232. #[cfg(desktop)]
  233. menu: None,
  234. #[cfg(desktop)]
  235. on_menu_event: None,
  236. };
  237. #[cfg(desktop)]
  238. if let Some(parent) = &config.parent {
  239. let window = manager
  240. .manager()
  241. .get_window(parent)
  242. .ok_or(crate::Error::WindowNotFound)?;
  243. builder = builder.parent(&window)?;
  244. }
  245. Ok(builder)
  246. }
  247. /// Registers a global menu event listener.
  248. ///
  249. /// Note that this handler is called for any menu event,
  250. /// whether it is coming from this window, another window or from the tray icon menu.
  251. ///
  252. /// Also note that this handler will not be called if
  253. /// the window used to register it was closed.
  254. ///
  255. /// # Examples
  256. #[cfg_attr(
  257. feature = "unstable",
  258. doc = r####"
  259. ```
  260. use tauri::menu::{Menu, Submenu, MenuItem};
  261. tauri::Builder::default()
  262. .setup(|app| {
  263. let handle = app.handle();
  264. let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
  265. let menu = Menu::with_items(handle, &[
  266. &Submenu::with_items(handle, "File", true, &[
  267. &save_menu_item,
  268. ])?,
  269. ])?;
  270. let window = tauri::window::WindowBuilder::new(app, "editor")
  271. .menu(menu)
  272. .on_menu_event(move |window, event| {
  273. if event.id == save_menu_item.id() {
  274. // save menu item
  275. }
  276. })
  277. .build()
  278. .unwrap();
  279. ///
  280. Ok(())
  281. });
  282. ```"####
  283. )]
  284. #[cfg(desktop)]
  285. pub fn on_menu_event<F: Fn(&Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
  286. mut self,
  287. f: F,
  288. ) -> Self {
  289. self.on_menu_event.replace(Box::new(f));
  290. self
  291. }
  292. /// Creates this window with a webview with it.
  293. #[cfg_attr(
  294. feature = "tracing",
  295. tracing::instrument(name = "webview::create", skip_all)
  296. )]
  297. pub(crate) fn with_webview(
  298. self,
  299. webview: WebviewBuilder<R>,
  300. ) -> crate::Result<(Window<R>, Webview<R>)> {
  301. let window_labels = self
  302. .manager
  303. .manager()
  304. .window
  305. .labels()
  306. .into_iter()
  307. .collect::<Vec<_>>();
  308. let webview_labels = self
  309. .manager
  310. .manager()
  311. .webview
  312. .webviews_lock()
  313. .values()
  314. .map(|w| WebviewLabelDef {
  315. window_label: w.window().label().to_string(),
  316. label: w.label().to_string(),
  317. })
  318. .collect::<Vec<_>>();
  319. self.with_webview_internal(webview, &window_labels, &webview_labels)
  320. }
  321. pub(crate) fn with_webview_internal(
  322. self,
  323. webview: WebviewBuilder<R>,
  324. window_labels: &[String],
  325. webview_labels: &[WebviewLabelDef],
  326. ) -> crate::Result<(Window<R>, Webview<R>)> {
  327. let pending_webview =
  328. webview.into_pending_webview(self.manager, &self.label, window_labels, webview_labels)?;
  329. let window = self.build_internal(Some(pending_webview))?;
  330. let webview = window.webviews().first().unwrap().clone();
  331. Ok((window, webview))
  332. }
  333. /// Creates a new window.
  334. pub fn build(self) -> crate::Result<Window<R>> {
  335. self.build_internal(None)
  336. }
  337. /// Creates a new window with an optional webview.
  338. fn build_internal(
  339. self,
  340. webview: Option<PendingWebview<EventLoopMessage, R>>,
  341. ) -> crate::Result<Window<R>> {
  342. let mut pending = PendingWindow::new(self.window_builder.clone(), self.label.clone())?;
  343. if let Some(webview) = webview {
  344. pending.set_webview(webview);
  345. }
  346. let app_manager = self.manager.manager();
  347. let pending = app_manager.window.prepare_window(pending)?;
  348. #[cfg(desktop)]
  349. let window_menu = {
  350. let is_app_wide = self.menu.is_none();
  351. self
  352. .menu
  353. .or_else(|| self.manager.app_handle().menu())
  354. .map(|menu| WindowMenu { is_app_wide, menu })
  355. };
  356. #[cfg(desktop)]
  357. let handler = app_manager
  358. .menu
  359. .prepare_window_menu_creation_handler(window_menu.as_ref());
  360. #[cfg(not(desktop))]
  361. #[allow(clippy::type_complexity)]
  362. let handler: Option<Box<dyn Fn(tauri_runtime::window::RawWindow<'_>) + Send>> = None;
  363. let window = match &mut self.manager.runtime() {
  364. RuntimeOrDispatch::Runtime(runtime) => runtime.create_window(pending, handler),
  365. RuntimeOrDispatch::RuntimeHandle(handle) => handle.create_window(pending, handler),
  366. RuntimeOrDispatch::Dispatch(dispatcher) => dispatcher.create_window(pending, handler),
  367. }
  368. .map(|detached_window| {
  369. let window = app_manager.window.attach_window(
  370. self.manager.app_handle().clone(),
  371. detached_window.clone(),
  372. #[cfg(desktop)]
  373. window_menu,
  374. );
  375. if let Some(webview) = detached_window.webview {
  376. app_manager.webview.attach_webview(window.clone(), webview);
  377. }
  378. window
  379. })?;
  380. #[cfg(desktop)]
  381. if let Some(handler) = self.on_menu_event {
  382. window.on_menu_event(handler);
  383. }
  384. if let Some(effects) = self.window_effects {
  385. crate::vibrancy::set_window_effects(&window, Some(effects))?;
  386. }
  387. let app_manager = self.manager.manager_owned();
  388. let window_label = window.label().to_string();
  389. // run on the main thread to fix a deadlock on webview.eval if the tracing feature is enabled
  390. let _ = window.run_on_main_thread(move || {
  391. let _ = app_manager.webview.eval_script_all(format!(
  392. "window.__TAURI_INTERNALS__.metadata.windows = {window_labels_array}.map(function (label) {{ return {{ label: label }} }})",
  393. window_labels_array = serde_json::to_string(&app_manager.window.labels()).unwrap(),
  394. ));
  395. let _ = app_manager.emit(
  396. "tauri://window-created",
  397. Some(crate::webview::CreatedEvent {
  398. label: window_label,
  399. }),
  400. );
  401. });
  402. Ok(window)
  403. }
  404. }
  405. /// Desktop APIs.
  406. #[cfg(desktop)]
  407. #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
  408. impl<'a, R: Runtime, M: Manager<R>> WindowBuilder<'a, R, M> {
  409. /// Sets the menu for the window.
  410. #[must_use]
  411. pub fn menu(mut self, menu: Menu<R>) -> Self {
  412. self.menu.replace(menu);
  413. self
  414. }
  415. /// Show window in the center of the screen.
  416. #[must_use]
  417. pub fn center(mut self) -> Self {
  418. self.window_builder = self.window_builder.center();
  419. self
  420. }
  421. /// The initial position of the window's.
  422. #[must_use]
  423. pub fn position(mut self, x: f64, y: f64) -> Self {
  424. self.window_builder = self.window_builder.position(x, y);
  425. self
  426. }
  427. /// Window size.
  428. #[must_use]
  429. pub fn inner_size(mut self, width: f64, height: f64) -> Self {
  430. self.window_builder = self.window_builder.inner_size(width, height);
  431. self
  432. }
  433. /// Window min inner size.
  434. #[must_use]
  435. pub fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
  436. self.window_builder = self.window_builder.min_inner_size(min_width, min_height);
  437. self
  438. }
  439. /// Window max inner size.
  440. #[must_use]
  441. pub fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
  442. self.window_builder = self.window_builder.max_inner_size(max_width, max_height);
  443. self
  444. }
  445. /// Whether the window is resizable or not.
  446. /// When resizable is set to false, native window's maximize button is automatically disabled.
  447. #[must_use]
  448. pub fn resizable(mut self, resizable: bool) -> Self {
  449. self.window_builder = self.window_builder.resizable(resizable);
  450. self
  451. }
  452. /// Whether the window's native maximize button is enabled or not.
  453. /// If resizable is set to false, this setting is ignored.
  454. ///
  455. /// ## Platform-specific
  456. ///
  457. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  458. /// - **Linux / iOS / Android:** Unsupported.
  459. #[must_use]
  460. pub fn maximizable(mut self, maximizable: bool) -> Self {
  461. self.window_builder = self.window_builder.maximizable(maximizable);
  462. self
  463. }
  464. /// Whether the window's native minimize button is enabled or not.
  465. ///
  466. /// ## Platform-specific
  467. ///
  468. /// - **Linux / iOS / Android:** Unsupported.
  469. #[must_use]
  470. pub fn minimizable(mut self, minimizable: bool) -> Self {
  471. self.window_builder = self.window_builder.minimizable(minimizable);
  472. self
  473. }
  474. /// Whether the window's native close button is enabled or not.
  475. ///
  476. /// ## Platform-specific
  477. ///
  478. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  479. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  480. /// - **iOS / Android:** Unsupported.
  481. #[must_use]
  482. pub fn closable(mut self, closable: bool) -> Self {
  483. self.window_builder = self.window_builder.closable(closable);
  484. self
  485. }
  486. /// The title of the window in the title bar.
  487. #[must_use]
  488. pub fn title<S: Into<String>>(mut self, title: S) -> Self {
  489. self.window_builder = self.window_builder.title(title);
  490. self
  491. }
  492. /// Whether to start the window in fullscreen or not.
  493. #[must_use]
  494. pub fn fullscreen(mut self, fullscreen: bool) -> Self {
  495. self.window_builder = self.window_builder.fullscreen(fullscreen);
  496. self
  497. }
  498. /// Sets the window to be initially focused.
  499. #[must_use]
  500. #[deprecated(
  501. since = "1.2.0",
  502. note = "The window is automatically focused by default. This function Will be removed in 2.0.0. Use `focused` instead."
  503. )]
  504. pub fn focus(mut self) -> Self {
  505. self.window_builder = self.window_builder.focused(true);
  506. self
  507. }
  508. /// Whether the window will be initially focused or not.
  509. #[must_use]
  510. pub fn focused(mut self, focused: bool) -> Self {
  511. self.window_builder = self.window_builder.focused(focused);
  512. self
  513. }
  514. /// Whether the window should be maximized upon creation.
  515. #[must_use]
  516. pub fn maximized(mut self, maximized: bool) -> Self {
  517. self.window_builder = self.window_builder.maximized(maximized);
  518. self
  519. }
  520. /// Whether the window should be immediately visible upon creation.
  521. #[must_use]
  522. pub fn visible(mut self, visible: bool) -> Self {
  523. self.window_builder = self.window_builder.visible(visible);
  524. self
  525. }
  526. /// Forces a theme or uses the system settings if None was provided.
  527. ///
  528. /// ## Platform-specific
  529. ///
  530. /// - **macOS**: Only supported on macOS 10.14+.
  531. #[must_use]
  532. pub fn theme(mut self, theme: Option<Theme>) -> Self {
  533. self.window_builder = self.window_builder.theme(theme);
  534. self
  535. }
  536. /// Whether the window should be transparent. If this is true, writing colors
  537. /// with alpha values different than `1.0` will produce a transparent window.
  538. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  539. #[cfg_attr(
  540. docsrs,
  541. doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
  542. )]
  543. #[must_use]
  544. pub fn transparent(mut self, transparent: bool) -> Self {
  545. self.window_builder = self.window_builder.transparent(transparent);
  546. self
  547. }
  548. /// Whether the window should have borders and bars.
  549. #[must_use]
  550. pub fn decorations(mut self, decorations: bool) -> Self {
  551. self.window_builder = self.window_builder.decorations(decorations);
  552. self
  553. }
  554. /// Whether the window should always be below other windows.
  555. #[must_use]
  556. pub fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
  557. self.window_builder = self.window_builder.always_on_bottom(always_on_bottom);
  558. self
  559. }
  560. /// Whether the window should always be on top of other windows.
  561. #[must_use]
  562. pub fn always_on_top(mut self, always_on_top: bool) -> Self {
  563. self.window_builder = self.window_builder.always_on_top(always_on_top);
  564. self
  565. }
  566. /// Whether the window will be visible on all workspaces or virtual desktops.
  567. ///
  568. /// ## Platform-specific
  569. ///
  570. /// - **Windows / iOS / Android:** Unsupported.
  571. #[must_use]
  572. pub fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
  573. self.window_builder = self
  574. .window_builder
  575. .visible_on_all_workspaces(visible_on_all_workspaces);
  576. self
  577. }
  578. /// Prevents the window contents from being captured by other apps.
  579. #[must_use]
  580. pub fn content_protected(mut self, protected: bool) -> Self {
  581. self.window_builder = self.window_builder.content_protected(protected);
  582. self
  583. }
  584. /// Sets the window icon.
  585. pub fn icon(mut self, icon: Image<'a>) -> crate::Result<Self> {
  586. self.window_builder = self.window_builder.icon(icon.into())?;
  587. Ok(self)
  588. }
  589. /// Sets whether or not the window icon should be hidden from the taskbar.
  590. ///
  591. /// ## Platform-specific
  592. ///
  593. /// - **macOS**: Unsupported.
  594. #[must_use]
  595. pub fn skip_taskbar(mut self, skip: bool) -> Self {
  596. self.window_builder = self.window_builder.skip_taskbar(skip);
  597. self
  598. }
  599. /// Sets whether or not the window has shadow.
  600. ///
  601. /// ## Platform-specific
  602. ///
  603. /// - **Windows:**
  604. /// - `false` has no effect on decorated window, shadows are always ON.
  605. /// - `true` will make undecorated window have a 1px white border,
  606. /// and on Windows 11, it will have a rounded corners.
  607. /// - **Linux:** Unsupported.
  608. #[must_use]
  609. pub fn shadow(mut self, enable: bool) -> Self {
  610. self.window_builder = self.window_builder.shadow(enable);
  611. self
  612. }
  613. /// Sets a parent to the window to be created.
  614. ///
  615. /// ## Platform-specific
  616. ///
  617. /// - **Windows**: This sets the passed parent as an owner window to the window to be created.
  618. /// From [MSDN owned windows docs](https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows):
  619. /// - An owned window is always above its owner in the z-order.
  620. /// - The system automatically destroys an owned window when its owner is destroyed.
  621. /// - An owned window is hidden when its owner is minimized.
  622. /// - **Linux**: This makes the new window transient for parent, see <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  623. /// - **macOS**: This adds the window as a child of parent, see <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
  624. pub fn parent(mut self, parent: &Window<R>) -> crate::Result<Self> {
  625. #[cfg(windows)]
  626. {
  627. self.window_builder = self.window_builder.owner(parent.hwnd()?);
  628. }
  629. #[cfg(any(
  630. target_os = "linux",
  631. target_os = "dragonfly",
  632. target_os = "freebsd",
  633. target_os = "netbsd",
  634. target_os = "openbsd"
  635. ))]
  636. {
  637. self.window_builder = self.window_builder.transient_for(&parent.gtk_window()?);
  638. }
  639. #[cfg(target_os = "macos")]
  640. {
  641. self.window_builder = self.window_builder.parent(parent.ns_window()?);
  642. }
  643. Ok(self)
  644. }
  645. /// Set an owner to the window to be created.
  646. ///
  647. /// From MSDN:
  648. /// - An owned window is always above its owner in the z-order.
  649. /// - The system automatically destroys an owned window when its owner is destroyed.
  650. /// - An owned window is hidden when its owner is minimized.
  651. ///
  652. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
  653. #[cfg(windows)]
  654. pub fn owner(mut self, owner: &Window<R>) -> crate::Result<Self> {
  655. self.window_builder = self.window_builder.owner(owner.hwnd()?);
  656. Ok(self)
  657. }
  658. /// Set an owner to the window to be created.
  659. ///
  660. /// From MSDN:
  661. /// - An owned window is always above its owner in the z-order.
  662. /// - The system automatically destroys an owned window when its owner is destroyed.
  663. /// - An owned window is hidden when its owner is minimized.
  664. ///
  665. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
  666. ///
  667. /// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
  668. #[cfg(windows)]
  669. #[must_use]
  670. pub fn owner_raw(mut self, owner: HWND) -> Self {
  671. self.window_builder = self.window_builder.owner(owner);
  672. self
  673. }
  674. /// Sets a parent to the window to be created.
  675. ///
  676. /// A child window has the WS_CHILD style and is confined to the client area of its parent window.
  677. ///
  678. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
  679. ///
  680. /// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
  681. #[cfg(windows)]
  682. #[must_use]
  683. pub fn parent_raw(mut self, parent: HWND) -> Self {
  684. self.window_builder = self.window_builder.parent(parent);
  685. self
  686. }
  687. /// Sets a parent to the window to be created.
  688. ///
  689. /// See <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
  690. ///
  691. /// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
  692. #[cfg(target_os = "macos")]
  693. #[must_use]
  694. pub fn parent_raw(mut self, parent: *mut std::ffi::c_void) -> Self {
  695. self.window_builder = self.window_builder.parent(parent);
  696. self
  697. }
  698. /// Sets the window to be created transient for parent.
  699. ///
  700. /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  701. ///
  702. /// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
  703. #[cfg(any(
  704. target_os = "linux",
  705. target_os = "dragonfly",
  706. target_os = "freebsd",
  707. target_os = "netbsd",
  708. target_os = "openbsd"
  709. ))]
  710. pub fn transient_for(mut self, parent: &Window<R>) -> crate::Result<Self> {
  711. self.window_builder = self.window_builder.transient_for(&parent.gtk_window()?);
  712. Ok(self)
  713. }
  714. /// Sets the window to be created transient for parent.
  715. ///
  716. /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  717. ///
  718. /// **Note:** This is a low level API. See [`Self::parent`] and [`Self::transient_for`] for higher level wrappers for Tauri windows.
  719. #[cfg(any(
  720. target_os = "linux",
  721. target_os = "dragonfly",
  722. target_os = "freebsd",
  723. target_os = "netbsd",
  724. target_os = "openbsd"
  725. ))]
  726. #[must_use]
  727. pub fn transient_for_raw(mut self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self {
  728. self.window_builder = self.window_builder.transient_for(parent);
  729. self
  730. }
  731. /// Enables or disables drag and drop support.
  732. #[cfg(windows)]
  733. #[must_use]
  734. pub fn drag_and_drop(mut self, enabled: bool) -> Self {
  735. self.window_builder = self.window_builder.drag_and_drop(enabled);
  736. self
  737. }
  738. /// Sets the [`crate::TitleBarStyle`].
  739. #[cfg(target_os = "macos")]
  740. #[must_use]
  741. pub fn title_bar_style(mut self, style: crate::TitleBarStyle) -> Self {
  742. self.window_builder = self.window_builder.title_bar_style(style);
  743. self
  744. }
  745. /// Hide the window title.
  746. #[cfg(target_os = "macos")]
  747. #[must_use]
  748. pub fn hidden_title(mut self, hidden: bool) -> Self {
  749. self.window_builder = self.window_builder.hidden_title(hidden);
  750. self
  751. }
  752. /// Defines the window [tabbing identifier] for macOS.
  753. ///
  754. /// Windows with matching tabbing identifiers will be grouped together.
  755. /// If the tabbing identifier is not set, automatic tabbing will be disabled.
  756. ///
  757. /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
  758. #[cfg(target_os = "macos")]
  759. #[must_use]
  760. pub fn tabbing_identifier(mut self, identifier: &str) -> Self {
  761. self.window_builder = self.window_builder.tabbing_identifier(identifier);
  762. self
  763. }
  764. /// Sets window effects.
  765. ///
  766. /// Requires the window to be transparent.
  767. ///
  768. /// ## Platform-specific:
  769. ///
  770. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  771. /// - **Linux**: Unsupported
  772. pub fn effects(mut self, effects: WindowEffectsConfig) -> Self {
  773. self.window_effects.replace(effects);
  774. self
  775. }
  776. }
  777. /// A wrapper struct to hold the window menu state
  778. /// and whether it is global per-app or specific to this window.
  779. #[cfg(desktop)]
  780. pub(crate) struct WindowMenu<R: Runtime> {
  781. pub(crate) is_app_wide: bool,
  782. pub(crate) menu: Menu<R>,
  783. }
  784. // TODO: expand these docs since this is a pretty important type
  785. /// A window managed by Tauri.
  786. ///
  787. /// This type also implements [`Manager`] which allows you to manage other windows attached to
  788. /// the same application.
  789. #[default_runtime(crate::Wry, wry)]
  790. pub struct Window<R: Runtime> {
  791. /// The window created by the runtime.
  792. pub(crate) window: DetachedWindow<EventLoopMessage, R>,
  793. /// The manager to associate this window with.
  794. pub(crate) manager: Arc<AppManager<R>>,
  795. pub(crate) app_handle: AppHandle<R>,
  796. // The menu set for this window
  797. #[cfg(desktop)]
  798. pub(crate) menu: Arc<Mutex<Option<WindowMenu<R>>>>,
  799. pub(crate) resources_table: Arc<Mutex<ResourceTable>>,
  800. }
  801. impl<R: Runtime> std::fmt::Debug for Window<R> {
  802. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  803. f.debug_struct("Window")
  804. .field("window", &self.window)
  805. .field("manager", &self.manager)
  806. .field("app_handle", &self.app_handle)
  807. .finish()
  808. }
  809. }
  810. impl<R: Runtime> raw_window_handle::HasWindowHandle for Window<R> {
  811. fn window_handle(
  812. &self,
  813. ) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
  814. self.window.dispatcher.window_handle()
  815. }
  816. }
  817. impl<R: Runtime> raw_window_handle::HasDisplayHandle for Window<R> {
  818. fn display_handle(
  819. &self,
  820. ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
  821. self.app_handle.display_handle()
  822. }
  823. }
  824. impl<R: Runtime> Clone for Window<R> {
  825. fn clone(&self) -> Self {
  826. Self {
  827. window: self.window.clone(),
  828. manager: self.manager.clone(),
  829. app_handle: self.app_handle.clone(),
  830. #[cfg(desktop)]
  831. menu: self.menu.clone(),
  832. resources_table: self.resources_table.clone(),
  833. }
  834. }
  835. }
  836. impl<R: Runtime> Hash for Window<R> {
  837. /// Only use the [`Window`]'s label to represent its hash.
  838. fn hash<H: Hasher>(&self, state: &mut H) {
  839. self.window.label.hash(state)
  840. }
  841. }
  842. impl<R: Runtime> Eq for Window<R> {}
  843. impl<R: Runtime> PartialEq for Window<R> {
  844. /// Only use the [`Window`]'s label to compare equality.
  845. fn eq(&self, other: &Self) -> bool {
  846. self.window.label.eq(&other.window.label)
  847. }
  848. }
  849. impl<R: Runtime> Manager<R> for Window<R> {
  850. fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
  851. self
  852. .resources_table
  853. .lock()
  854. .expect("poisoned window resources table")
  855. }
  856. }
  857. impl<R: Runtime> ManagerBase<R> for Window<R> {
  858. fn manager(&self) -> &AppManager<R> {
  859. &self.manager
  860. }
  861. fn manager_owned(&self) -> Arc<AppManager<R>> {
  862. self.manager.clone()
  863. }
  864. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  865. RuntimeOrDispatch::Dispatch(self.window.dispatcher.clone())
  866. }
  867. fn managed_app_handle(&self) -> &AppHandle<R> {
  868. &self.app_handle
  869. }
  870. }
  871. impl<'de, R: Runtime> CommandArg<'de, R> for Window<R> {
  872. /// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
  873. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  874. Ok(command.message.webview().window().clone())
  875. }
  876. }
  877. /// Base window functions.
  878. impl<R: Runtime> Window<R> {
  879. /// Create a new window that is attached to the manager.
  880. pub(crate) fn new(
  881. manager: Arc<AppManager<R>>,
  882. window: DetachedWindow<EventLoopMessage, R>,
  883. app_handle: AppHandle<R>,
  884. #[cfg(desktop)] menu: Option<WindowMenu<R>>,
  885. ) -> Self {
  886. Self {
  887. window,
  888. manager,
  889. app_handle,
  890. #[cfg(desktop)]
  891. menu: Arc::new(std::sync::Mutex::new(menu)),
  892. resources_table: Default::default(),
  893. }
  894. }
  895. /// Initializes a window builder with the given window label.
  896. ///
  897. /// Data URLs are only supported with the `webview-data-url` feature flag.
  898. #[cfg(feature = "unstable")]
  899. #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
  900. pub fn builder<M: Manager<R>, L: Into<String>>(manager: &M, label: L) -> WindowBuilder<'_, R, M> {
  901. WindowBuilder::new(manager, label.into())
  902. }
  903. /// Adds a new webview as a child of this window.
  904. #[cfg(any(test, all(desktop, feature = "unstable")))]
  905. #[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "unstable"))))]
  906. pub fn add_child<P: Into<Position>, S: Into<Size>>(
  907. &self,
  908. webview_builder: WebviewBuilder<R>,
  909. position: P,
  910. size: S,
  911. ) -> crate::Result<Webview<R>> {
  912. use std::sync::mpsc::channel;
  913. let (tx, rx) = channel();
  914. let position = position.into();
  915. let size = size.into();
  916. let window_ = self.clone();
  917. self.run_on_main_thread(move || {
  918. let res = webview_builder.build(window_, position, size);
  919. tx.send(res.map_err(Into::into)).unwrap();
  920. })?;
  921. rx.recv().unwrap()
  922. }
  923. /// List of webviews associated with this window.
  924. pub fn webviews(&self) -> Vec<Webview<R>> {
  925. self
  926. .manager
  927. .webview
  928. .webviews_lock()
  929. .values()
  930. .filter(|w| w.window_label() == self.label())
  931. .cloned()
  932. .collect()
  933. }
  934. pub(crate) fn is_webview_window(&self) -> bool {
  935. self.webviews().iter().all(|w| w.label() == self.label())
  936. }
  937. /// Runs the given closure on the main thread.
  938. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  939. self
  940. .window
  941. .dispatcher
  942. .run_on_main_thread(f)
  943. .map_err(Into::into)
  944. }
  945. /// The label of this window.
  946. pub fn label(&self) -> &str {
  947. &self.window.label
  948. }
  949. /// Registers a window event listener.
  950. pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) {
  951. self
  952. .window
  953. .dispatcher
  954. .on_window_event(move |event| f(&event.clone().into()));
  955. }
  956. }
  957. /// Menu APIs
  958. #[cfg(desktop)]
  959. impl<R: Runtime> Window<R> {
  960. /// Registers a global menu event listener.
  961. ///
  962. /// Note that this handler is called for any menu event,
  963. /// whether it is coming from this window, another window or from the tray icon menu.
  964. ///
  965. /// Also note that this handler will not be called if
  966. /// the window used to register it was closed.
  967. ///
  968. /// # Examples
  969. #[cfg_attr(
  970. feature = "unstable",
  971. doc = r####"
  972. ```
  973. use tauri::menu::{Menu, Submenu, MenuItem};
  974. tauri::Builder::default()
  975. .setup(|app| {
  976. let handle = app.handle();
  977. let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
  978. let menu = Menu::with_items(handle, &[
  979. &Submenu::with_items(handle, "File", true, &[
  980. &save_menu_item,
  981. ])?,
  982. ])?;
  983. let window = tauri::window::WindowBuilder::new(app, "editor")
  984. .menu(menu)
  985. .build()
  986. .unwrap();
  987. window.on_menu_event(move |window, event| {
  988. if event.id == save_menu_item.id() {
  989. // save menu item
  990. }
  991. });
  992. Ok(())
  993. });
  994. ```
  995. "####
  996. )]
  997. pub fn on_menu_event<F: Fn(&Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
  998. &self,
  999. f: F,
  1000. ) {
  1001. self
  1002. .manager
  1003. .menu
  1004. .event_listeners
  1005. .lock()
  1006. .unwrap()
  1007. .insert(self.label().to_string(), Box::new(f));
  1008. }
  1009. pub(crate) fn menu_lock(&self) -> std::sync::MutexGuard<'_, Option<WindowMenu<R>>> {
  1010. self.menu.lock().expect("poisoned window")
  1011. }
  1012. #[cfg_attr(target_os = "macos", allow(dead_code))]
  1013. pub(crate) fn has_app_wide_menu(&self) -> bool {
  1014. self
  1015. .menu_lock()
  1016. .as_ref()
  1017. .map(|m| m.is_app_wide)
  1018. .unwrap_or(false)
  1019. }
  1020. #[cfg_attr(target_os = "macos", allow(dead_code))]
  1021. pub(crate) fn is_menu_in_use<I: PartialEq<MenuId>>(&self, id: &I) -> bool {
  1022. self
  1023. .menu_lock()
  1024. .as_ref()
  1025. .map(|m| id.eq(m.menu.id()))
  1026. .unwrap_or(false)
  1027. }
  1028. /// Returns this window menu .
  1029. pub fn menu(&self) -> Option<Menu<R>> {
  1030. self.menu_lock().as_ref().map(|m| m.menu.clone())
  1031. }
  1032. /// Sets the window menu and returns the previous one.
  1033. ///
  1034. /// ## Platform-specific:
  1035. ///
  1036. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  1037. /// window, if you need to set it, use [`AppHandle::set_menu`] instead.
  1038. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1039. pub fn set_menu(&self, menu: Menu<R>) -> crate::Result<Option<Menu<R>>> {
  1040. let prev_menu = self.remove_menu()?;
  1041. self.manager.menu.insert_menu_into_stash(&menu);
  1042. let window = self.clone();
  1043. let menu_ = menu.clone();
  1044. self.run_on_main_thread(move || {
  1045. #[cfg(windows)]
  1046. if let Ok(hwnd) = window.hwnd() {
  1047. let _ = menu_.inner().init_for_hwnd(hwnd.0);
  1048. }
  1049. #[cfg(any(
  1050. target_os = "linux",
  1051. target_os = "dragonfly",
  1052. target_os = "freebsd",
  1053. target_os = "netbsd",
  1054. target_os = "openbsd"
  1055. ))]
  1056. if let (Ok(gtk_window), Ok(gtk_box)) = (window.gtk_window(), window.default_vbox()) {
  1057. let _ = menu_
  1058. .inner()
  1059. .init_for_gtk_window(&gtk_window, Some(&gtk_box));
  1060. }
  1061. })?;
  1062. self.menu_lock().replace(WindowMenu {
  1063. is_app_wide: false,
  1064. menu,
  1065. });
  1066. Ok(prev_menu)
  1067. }
  1068. /// Removes the window menu and returns it.
  1069. ///
  1070. /// ## Platform-specific:
  1071. ///
  1072. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  1073. /// window, if you need to remove it, use [`AppHandle::remove_menu`] instead.
  1074. pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
  1075. let prev_menu = self.menu_lock().take().map(|m| m.menu);
  1076. // remove from the window
  1077. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1078. if let Some(menu) = &prev_menu {
  1079. let window = self.clone();
  1080. let menu = menu.clone();
  1081. self.run_on_main_thread(move || {
  1082. #[cfg(windows)]
  1083. if let Ok(hwnd) = window.hwnd() {
  1084. let _ = menu.inner().remove_for_hwnd(hwnd.0);
  1085. }
  1086. #[cfg(any(
  1087. target_os = "linux",
  1088. target_os = "dragonfly",
  1089. target_os = "freebsd",
  1090. target_os = "netbsd",
  1091. target_os = "openbsd"
  1092. ))]
  1093. if let Ok(gtk_window) = window.gtk_window() {
  1094. let _ = menu.inner().remove_for_gtk_window(&gtk_window);
  1095. }
  1096. })?;
  1097. }
  1098. self
  1099. .manager
  1100. .remove_menu_from_stash_by_id(prev_menu.as_ref().map(|m| m.id()));
  1101. Ok(prev_menu)
  1102. }
  1103. /// Hides the window menu.
  1104. pub fn hide_menu(&self) -> crate::Result<()> {
  1105. // remove from the window
  1106. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1107. if let Some(window_menu) = &*self.menu_lock() {
  1108. let window = self.clone();
  1109. let menu_ = window_menu.menu.clone();
  1110. self.run_on_main_thread(move || {
  1111. #[cfg(windows)]
  1112. if let Ok(hwnd) = window.hwnd() {
  1113. let _ = menu_.inner().hide_for_hwnd(hwnd.0);
  1114. }
  1115. #[cfg(any(
  1116. target_os = "linux",
  1117. target_os = "dragonfly",
  1118. target_os = "freebsd",
  1119. target_os = "netbsd",
  1120. target_os = "openbsd"
  1121. ))]
  1122. if let Ok(gtk_window) = window.gtk_window() {
  1123. let _ = menu_.inner().hide_for_gtk_window(&gtk_window);
  1124. }
  1125. })?;
  1126. }
  1127. Ok(())
  1128. }
  1129. /// Shows the window menu.
  1130. pub fn show_menu(&self) -> crate::Result<()> {
  1131. // remove from the window
  1132. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1133. if let Some(window_menu) = &*self.menu_lock() {
  1134. let window = self.clone();
  1135. let menu_ = window_menu.menu.clone();
  1136. self.run_on_main_thread(move || {
  1137. #[cfg(windows)]
  1138. if let Ok(hwnd) = window.hwnd() {
  1139. let _ = menu_.inner().show_for_hwnd(hwnd.0);
  1140. }
  1141. #[cfg(any(
  1142. target_os = "linux",
  1143. target_os = "dragonfly",
  1144. target_os = "freebsd",
  1145. target_os = "netbsd",
  1146. target_os = "openbsd"
  1147. ))]
  1148. if let Ok(gtk_window) = window.gtk_window() {
  1149. let _ = menu_.inner().show_for_gtk_window(&gtk_window);
  1150. }
  1151. })?;
  1152. }
  1153. Ok(())
  1154. }
  1155. /// Shows the window menu.
  1156. pub fn is_menu_visible(&self) -> crate::Result<bool> {
  1157. // remove from the window
  1158. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1159. if let Some(window_menu) = &*self.menu_lock() {
  1160. let (tx, rx) = std::sync::mpsc::channel();
  1161. let window = self.clone();
  1162. let menu_ = window_menu.menu.clone();
  1163. self.run_on_main_thread(move || {
  1164. #[cfg(windows)]
  1165. if let Ok(hwnd) = window.hwnd() {
  1166. let _ = tx.send(menu_.inner().is_visible_on_hwnd(hwnd.0));
  1167. }
  1168. #[cfg(any(
  1169. target_os = "linux",
  1170. target_os = "dragonfly",
  1171. target_os = "freebsd",
  1172. target_os = "netbsd",
  1173. target_os = "openbsd"
  1174. ))]
  1175. if let Ok(gtk_window) = window.gtk_window() {
  1176. let _ = tx.send(menu_.inner().is_visible_on_gtk_window(&gtk_window));
  1177. }
  1178. })?;
  1179. return Ok(rx.recv().unwrap_or(false));
  1180. }
  1181. Ok(false)
  1182. }
  1183. /// Shows the specified menu as a context menu at the cursor position.
  1184. pub fn popup_menu<M: ContextMenu>(&self, menu: &M) -> crate::Result<()> {
  1185. menu.popup(self.clone())
  1186. }
  1187. /// Shows the specified menu as a context menu at the specified position.
  1188. ///
  1189. /// The position is relative to the window's top-left corner.
  1190. pub fn popup_menu_at<M: ContextMenu, P: Into<Position>>(
  1191. &self,
  1192. menu: &M,
  1193. position: P,
  1194. ) -> crate::Result<()> {
  1195. menu.popup_at(self.clone(), position)
  1196. }
  1197. }
  1198. /// Window getters.
  1199. impl<R: Runtime> Window<R> {
  1200. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  1201. pub fn scale_factor(&self) -> crate::Result<f64> {
  1202. self.window.dispatcher.scale_factor().map_err(Into::into)
  1203. }
  1204. /// 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.
  1205. pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1206. self.window.dispatcher.inner_position().map_err(Into::into)
  1207. }
  1208. /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
  1209. pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1210. self.window.dispatcher.outer_position().map_err(Into::into)
  1211. }
  1212. /// Returns the physical size of the window's client area.
  1213. ///
  1214. /// The client area is the content of the window, excluding the title bar and borders.
  1215. pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1216. self.window.dispatcher.inner_size().map_err(Into::into)
  1217. }
  1218. /// Returns the physical size of the entire window.
  1219. ///
  1220. /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
  1221. pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1222. self.window.dispatcher.outer_size().map_err(Into::into)
  1223. }
  1224. /// Gets the window's current fullscreen state.
  1225. pub fn is_fullscreen(&self) -> crate::Result<bool> {
  1226. self.window.dispatcher.is_fullscreen().map_err(Into::into)
  1227. }
  1228. /// Gets the window's current minimized state.
  1229. pub fn is_minimized(&self) -> crate::Result<bool> {
  1230. self.window.dispatcher.is_minimized().map_err(Into::into)
  1231. }
  1232. /// Gets the window's current maximized state.
  1233. pub fn is_maximized(&self) -> crate::Result<bool> {
  1234. self.window.dispatcher.is_maximized().map_err(Into::into)
  1235. }
  1236. /// Gets the window's current focus state.
  1237. pub fn is_focused(&self) -> crate::Result<bool> {
  1238. self.window.dispatcher.is_focused().map_err(Into::into)
  1239. }
  1240. /// Gets the window’s current decoration state.
  1241. pub fn is_decorated(&self) -> crate::Result<bool> {
  1242. self.window.dispatcher.is_decorated().map_err(Into::into)
  1243. }
  1244. /// Gets the window’s current resizable state.
  1245. pub fn is_resizable(&self) -> crate::Result<bool> {
  1246. self.window.dispatcher.is_resizable().map_err(Into::into)
  1247. }
  1248. /// Gets the window’s native maximize button state
  1249. ///
  1250. /// ## Platform-specific
  1251. ///
  1252. /// - **Linux / iOS / Android:** Unsupported.
  1253. pub fn is_maximizable(&self) -> crate::Result<bool> {
  1254. self.window.dispatcher.is_maximizable().map_err(Into::into)
  1255. }
  1256. /// Gets the window’s native minimize button state
  1257. ///
  1258. /// ## Platform-specific
  1259. ///
  1260. /// - **Linux / iOS / Android:** Unsupported.
  1261. pub fn is_minimizable(&self) -> crate::Result<bool> {
  1262. self.window.dispatcher.is_minimizable().map_err(Into::into)
  1263. }
  1264. /// Gets the window’s native close button state
  1265. ///
  1266. /// ## Platform-specific
  1267. ///
  1268. /// - **Linux / iOS / Android:** Unsupported.
  1269. pub fn is_closable(&self) -> crate::Result<bool> {
  1270. self.window.dispatcher.is_closable().map_err(Into::into)
  1271. }
  1272. /// Gets the window's current visibility state.
  1273. pub fn is_visible(&self) -> crate::Result<bool> {
  1274. self.window.dispatcher.is_visible().map_err(Into::into)
  1275. }
  1276. /// Gets the window's current title.
  1277. pub fn title(&self) -> crate::Result<String> {
  1278. self.window.dispatcher.title().map_err(Into::into)
  1279. }
  1280. /// Returns the monitor on which the window currently resides.
  1281. ///
  1282. /// Returns None if current monitor can't be detected.
  1283. pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
  1284. self
  1285. .window
  1286. .dispatcher
  1287. .current_monitor()
  1288. .map(|m| m.map(Into::into))
  1289. .map_err(Into::into)
  1290. }
  1291. /// Returns the primary monitor of the system.
  1292. ///
  1293. /// Returns None if it can't identify any monitor as a primary one.
  1294. pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
  1295. self
  1296. .window
  1297. .dispatcher
  1298. .primary_monitor()
  1299. .map(|m| m.map(Into::into))
  1300. .map_err(Into::into)
  1301. }
  1302. /// Returns the list of all the monitors available on the system.
  1303. pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
  1304. self
  1305. .window
  1306. .dispatcher
  1307. .available_monitors()
  1308. .map(|m| m.into_iter().map(Into::into).collect())
  1309. .map_err(Into::into)
  1310. }
  1311. /// Returns the native handle that is used by this window.
  1312. #[cfg(target_os = "macos")]
  1313. pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> {
  1314. self
  1315. .window
  1316. .dispatcher
  1317. .window_handle()
  1318. .map_err(Into::into)
  1319. .and_then(|handle| {
  1320. if let raw_window_handle::RawWindowHandle::AppKit(h) = handle.as_raw() {
  1321. Ok(unsafe {
  1322. use objc::*;
  1323. let ns_window: cocoa::base::id =
  1324. objc::msg_send![h.ns_view.as_ptr() as cocoa::base::id, window];
  1325. ns_window as *mut _
  1326. })
  1327. } else {
  1328. Err(crate::Error::InvalidWindowHandle)
  1329. }
  1330. })
  1331. }
  1332. /// Returns the pointer to the content view of this window.
  1333. #[cfg(target_os = "macos")]
  1334. pub fn ns_view(&self) -> crate::Result<*mut std::ffi::c_void> {
  1335. self
  1336. .window
  1337. .dispatcher
  1338. .window_handle()
  1339. .map_err(Into::into)
  1340. .and_then(|handle| {
  1341. if let raw_window_handle::RawWindowHandle::AppKit(h) = handle.as_raw() {
  1342. Ok(h.ns_view.as_ptr())
  1343. } else {
  1344. Err(crate::Error::InvalidWindowHandle)
  1345. }
  1346. })
  1347. }
  1348. /// Returns the native handle that is used by this window.
  1349. #[cfg(windows)]
  1350. pub fn hwnd(&self) -> crate::Result<HWND> {
  1351. self
  1352. .window
  1353. .dispatcher
  1354. .window_handle()
  1355. .map_err(Into::into)
  1356. .and_then(|handle| {
  1357. if let raw_window_handle::RawWindowHandle::Win32(h) = handle.as_raw() {
  1358. Ok(HWND(h.hwnd.get()))
  1359. } else {
  1360. Err(crate::Error::InvalidWindowHandle)
  1361. }
  1362. })
  1363. }
  1364. /// Returns the `ApplicationWindow` from gtk crate that is used by this window.
  1365. ///
  1366. /// Note that this type can only be used on the main thread.
  1367. #[cfg(any(
  1368. target_os = "linux",
  1369. target_os = "dragonfly",
  1370. target_os = "freebsd",
  1371. target_os = "netbsd",
  1372. target_os = "openbsd"
  1373. ))]
  1374. pub fn gtk_window(&self) -> crate::Result<gtk::ApplicationWindow> {
  1375. self.window.dispatcher.gtk_window().map_err(Into::into)
  1376. }
  1377. /// Returns the vertical [`gtk::Box`] that is added by default as the sole child of this window.
  1378. ///
  1379. /// Note that this type can only be used on the main thread.
  1380. #[cfg(any(
  1381. target_os = "linux",
  1382. target_os = "dragonfly",
  1383. target_os = "freebsd",
  1384. target_os = "netbsd",
  1385. target_os = "openbsd"
  1386. ))]
  1387. pub fn default_vbox(&self) -> crate::Result<gtk::Box> {
  1388. self.window.dispatcher.default_vbox().map_err(Into::into)
  1389. }
  1390. /// Returns the current window theme.
  1391. ///
  1392. /// ## Platform-specific
  1393. ///
  1394. /// - **macOS**: Only supported on macOS 10.14+.
  1395. pub fn theme(&self) -> crate::Result<Theme> {
  1396. self.window.dispatcher.theme().map_err(Into::into)
  1397. }
  1398. }
  1399. /// Desktop window setters and actions.
  1400. #[cfg(desktop)]
  1401. impl<R: Runtime> Window<R> {
  1402. /// Centers the window.
  1403. pub fn center(&self) -> crate::Result<()> {
  1404. self.window.dispatcher.center().map_err(Into::into)
  1405. }
  1406. /// Requests user attention to the window, this has no effect if the application
  1407. /// is already focused. How requesting for user attention manifests is platform dependent,
  1408. /// see `UserAttentionType` for details.
  1409. ///
  1410. /// Providing `None` will unset the request for user attention. Unsetting the request for
  1411. /// user attention might not be done automatically by the WM when the window receives input.
  1412. ///
  1413. /// ## Platform-specific
  1414. ///
  1415. /// - **macOS:** `None` has no effect.
  1416. /// - **Linux:** Urgency levels have the same effect.
  1417. pub fn request_user_attention(
  1418. &self,
  1419. request_type: Option<UserAttentionType>,
  1420. ) -> crate::Result<()> {
  1421. self
  1422. .window
  1423. .dispatcher
  1424. .request_user_attention(request_type)
  1425. .map_err(Into::into)
  1426. }
  1427. /// Determines if this window should be resizable.
  1428. /// When resizable is set to false, native window's maximize button is automatically disabled.
  1429. pub fn set_resizable(&self, resizable: bool) -> crate::Result<()> {
  1430. self
  1431. .window
  1432. .dispatcher
  1433. .set_resizable(resizable)
  1434. .map_err(Into::into)
  1435. }
  1436. /// Determines if this window's native maximize button should be enabled.
  1437. /// If resizable is set to false, this setting is ignored.
  1438. ///
  1439. /// ## Platform-specific
  1440. ///
  1441. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  1442. /// - **Linux / iOS / Android:** Unsupported.
  1443. pub fn set_maximizable(&self, maximizable: bool) -> crate::Result<()> {
  1444. self
  1445. .window
  1446. .dispatcher
  1447. .set_maximizable(maximizable)
  1448. .map_err(Into::into)
  1449. }
  1450. /// Determines if this window's native minimize button should be enabled.
  1451. ///
  1452. /// ## Platform-specific
  1453. ///
  1454. /// - **Linux / iOS / Android:** Unsupported.
  1455. pub fn set_minimizable(&self, minimizable: bool) -> crate::Result<()> {
  1456. self
  1457. .window
  1458. .dispatcher
  1459. .set_minimizable(minimizable)
  1460. .map_err(Into::into)
  1461. }
  1462. /// Determines if this window's native close button should be enabled.
  1463. ///
  1464. /// ## Platform-specific
  1465. ///
  1466. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  1467. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  1468. /// - **iOS / Android:** Unsupported.
  1469. pub fn set_closable(&self, closable: bool) -> crate::Result<()> {
  1470. self
  1471. .window
  1472. .dispatcher
  1473. .set_closable(closable)
  1474. .map_err(Into::into)
  1475. }
  1476. /// Set this window's title.
  1477. pub fn set_title(&self, title: &str) -> crate::Result<()> {
  1478. self
  1479. .window
  1480. .dispatcher
  1481. .set_title(title.to_string())
  1482. .map_err(Into::into)
  1483. }
  1484. /// Maximizes this window.
  1485. pub fn maximize(&self) -> crate::Result<()> {
  1486. self.window.dispatcher.maximize().map_err(Into::into)
  1487. }
  1488. /// Un-maximizes this window.
  1489. pub fn unmaximize(&self) -> crate::Result<()> {
  1490. self.window.dispatcher.unmaximize().map_err(Into::into)
  1491. }
  1492. /// Minimizes this window.
  1493. pub fn minimize(&self) -> crate::Result<()> {
  1494. self.window.dispatcher.minimize().map_err(Into::into)
  1495. }
  1496. /// Un-minimizes this window.
  1497. pub fn unminimize(&self) -> crate::Result<()> {
  1498. self.window.dispatcher.unminimize().map_err(Into::into)
  1499. }
  1500. /// Show this window.
  1501. pub fn show(&self) -> crate::Result<()> {
  1502. self.window.dispatcher.show().map_err(Into::into)
  1503. }
  1504. /// Hide this window.
  1505. pub fn hide(&self) -> crate::Result<()> {
  1506. self.window.dispatcher.hide().map_err(Into::into)
  1507. }
  1508. /// Closes this window. It emits [`crate::RunEvent::CloseRequested`] first like a user-initiated close request so you can intercept it.
  1509. pub fn close(&self) -> crate::Result<()> {
  1510. self.window.dispatcher.close().map_err(Into::into)
  1511. }
  1512. /// Destroys this window. Similar to [`Self::close`] but does not emit any events and force close the window instead.
  1513. pub fn destroy(&self) -> crate::Result<()> {
  1514. self.window.dispatcher.destroy().map_err(Into::into)
  1515. }
  1516. /// Determines if this window should be [decorated].
  1517. ///
  1518. /// [decorated]: https://en.wikipedia.org/wiki/Window_(computing)#Window_decoration
  1519. pub fn set_decorations(&self, decorations: bool) -> crate::Result<()> {
  1520. self
  1521. .window
  1522. .dispatcher
  1523. .set_decorations(decorations)
  1524. .map_err(Into::into)
  1525. }
  1526. /// Determines if this window should have shadow.
  1527. ///
  1528. /// ## Platform-specific
  1529. ///
  1530. /// - **Windows:**
  1531. /// - `false` has no effect on decorated window, shadow are always ON.
  1532. /// - `true` will make undecorated window have a 1px white border,
  1533. /// and on Windows 11, it will have a rounded corners.
  1534. /// - **Linux:** Unsupported.
  1535. pub fn set_shadow(&self, enable: bool) -> crate::Result<()> {
  1536. self
  1537. .window
  1538. .dispatcher
  1539. .set_shadow(enable)
  1540. .map_err(Into::into)
  1541. }
  1542. /// Sets window effects, pass [`None`] to clear any effects applied if possible.
  1543. ///
  1544. /// Requires the window to be transparent.
  1545. ///
  1546. /// See [`EffectsBuilder`] for a convenient builder for [`WindowEffectsConfig`].
  1547. ///
  1548. #[cfg_attr(
  1549. feature = "unstable",
  1550. doc = r####"
  1551. ```rust,no_run
  1552. use tauri::{Manager, window::{Color, Effect, EffectState, EffectsBuilder}};
  1553. tauri::Builder::default()
  1554. .setup(|app| {
  1555. let window = app.get_window("main").unwrap();
  1556. window.set_effects(
  1557. EffectsBuilder::new()
  1558. .effect(Effect::Popover)
  1559. .state(EffectState::Active)
  1560. .radius(5.)
  1561. .color(Color(0, 0, 0, 255))
  1562. .build(),
  1563. )?;
  1564. Ok(())
  1565. });
  1566. ```
  1567. "####
  1568. )]
  1569. ///
  1570. /// ## Platform-specific:
  1571. ///
  1572. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  1573. /// - **Linux**: Unsupported
  1574. pub fn set_effects<E: Into<Option<WindowEffectsConfig>>>(&self, effects: E) -> crate::Result<()> {
  1575. let effects = effects.into();
  1576. let window = self.clone();
  1577. self.run_on_main_thread(move || {
  1578. let _ = crate::vibrancy::set_window_effects(&window, effects);
  1579. })
  1580. }
  1581. /// Determines if this window should always be below other windows.
  1582. pub fn set_always_on_bottom(&self, always_on_bottom: bool) -> crate::Result<()> {
  1583. self
  1584. .window
  1585. .dispatcher
  1586. .set_always_on_bottom(always_on_bottom)
  1587. .map_err(Into::into)
  1588. }
  1589. /// Determines if this window should always be on top of other windows.
  1590. pub fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> {
  1591. self
  1592. .window
  1593. .dispatcher
  1594. .set_always_on_top(always_on_top)
  1595. .map_err(Into::into)
  1596. }
  1597. /// Sets whether the window should be visible on all workspaces or virtual desktops.
  1598. ///
  1599. /// ## Platform-specific
  1600. ///
  1601. /// - **Windows / iOS / Android:** Unsupported.
  1602. pub fn set_visible_on_all_workspaces(
  1603. &self,
  1604. visible_on_all_workspaces: bool,
  1605. ) -> crate::Result<()> {
  1606. self
  1607. .window
  1608. .dispatcher
  1609. .set_visible_on_all_workspaces(visible_on_all_workspaces)
  1610. .map_err(Into::into)
  1611. }
  1612. /// Prevents the window contents from being captured by other apps.
  1613. pub fn set_content_protected(&self, protected: bool) -> crate::Result<()> {
  1614. self
  1615. .window
  1616. .dispatcher
  1617. .set_content_protected(protected)
  1618. .map_err(Into::into)
  1619. }
  1620. /// Resizes this window.
  1621. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
  1622. self
  1623. .window
  1624. .dispatcher
  1625. .set_size(size.into())
  1626. .map_err(Into::into)
  1627. }
  1628. /// Sets this window's minimum size.
  1629. pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1630. self
  1631. .window
  1632. .dispatcher
  1633. .set_min_size(size.map(|s| s.into()))
  1634. .map_err(Into::into)
  1635. }
  1636. /// Sets this window's maximum size.
  1637. pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1638. self
  1639. .window
  1640. .dispatcher
  1641. .set_max_size(size.map(|s| s.into()))
  1642. .map_err(Into::into)
  1643. }
  1644. /// Sets this window's position.
  1645. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1646. self
  1647. .window
  1648. .dispatcher
  1649. .set_position(position.into())
  1650. .map_err(Into::into)
  1651. }
  1652. /// Determines if this window should be fullscreen.
  1653. pub fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
  1654. self
  1655. .window
  1656. .dispatcher
  1657. .set_fullscreen(fullscreen)
  1658. .map_err(Into::into)
  1659. }
  1660. /// Bring the window to front and focus.
  1661. pub fn set_focus(&self) -> crate::Result<()> {
  1662. self.window.dispatcher.set_focus().map_err(Into::into)
  1663. }
  1664. /// Sets this window' icon.
  1665. pub fn set_icon(&self, icon: Image<'_>) -> crate::Result<()> {
  1666. self
  1667. .window
  1668. .dispatcher
  1669. .set_icon(icon.into())
  1670. .map_err(Into::into)
  1671. }
  1672. /// Whether to hide the window icon from the taskbar or not.
  1673. ///
  1674. /// ## Platform-specific
  1675. ///
  1676. /// - **macOS:** Unsupported.
  1677. pub fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> {
  1678. self
  1679. .window
  1680. .dispatcher
  1681. .set_skip_taskbar(skip)
  1682. .map_err(Into::into)
  1683. }
  1684. /// Grabs the cursor, preventing it from leaving the window.
  1685. ///
  1686. /// There's no guarantee that the cursor will be hidden. You should
  1687. /// hide it by yourself if you want so.
  1688. ///
  1689. /// ## Platform-specific
  1690. ///
  1691. /// - **Linux:** Unsupported.
  1692. /// - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
  1693. pub fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
  1694. self
  1695. .window
  1696. .dispatcher
  1697. .set_cursor_grab(grab)
  1698. .map_err(Into::into)
  1699. }
  1700. /// Modifies the cursor's visibility.
  1701. ///
  1702. /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
  1703. ///
  1704. /// ## Platform-specific
  1705. ///
  1706. /// - **Windows:** The cursor is only hidden within the confines of the window.
  1707. /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
  1708. /// outside of the window.
  1709. pub fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
  1710. self
  1711. .window
  1712. .dispatcher
  1713. .set_cursor_visible(visible)
  1714. .map_err(Into::into)
  1715. }
  1716. /// Modifies the cursor icon of the window.
  1717. pub fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
  1718. self
  1719. .window
  1720. .dispatcher
  1721. .set_cursor_icon(icon)
  1722. .map_err(Into::into)
  1723. }
  1724. /// Changes the position of the cursor in window coordinates.
  1725. pub fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1726. self
  1727. .window
  1728. .dispatcher
  1729. .set_cursor_position(position)
  1730. .map_err(Into::into)
  1731. }
  1732. /// Ignores the window cursor events.
  1733. pub fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
  1734. self
  1735. .window
  1736. .dispatcher
  1737. .set_ignore_cursor_events(ignore)
  1738. .map_err(Into::into)
  1739. }
  1740. /// Starts dragging the window.
  1741. pub fn start_dragging(&self) -> crate::Result<()> {
  1742. self.window.dispatcher.start_dragging().map_err(Into::into)
  1743. }
  1744. /// Starts resize-dragging the window.
  1745. pub fn start_resize_dragging(
  1746. &self,
  1747. direction: tauri_runtime::ResizeDirection,
  1748. ) -> crate::Result<()> {
  1749. self
  1750. .window
  1751. .dispatcher
  1752. .start_resize_dragging(direction)
  1753. .map_err(Into::into)
  1754. }
  1755. /// Sets the taskbar progress state.
  1756. ///
  1757. /// ## Platform-specific
  1758. ///
  1759. /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window.
  1760. /// - **Linux**: Only supported desktop environments with `libunity` (e.g. GNOME).
  1761. /// - **iOS / Android:** Unsupported.
  1762. pub fn set_progress_bar(&self, progress_state: ProgressBarState) -> crate::Result<()> {
  1763. self
  1764. .window
  1765. .dispatcher
  1766. .set_progress_bar(crate::runtime::ProgressBarState {
  1767. status: progress_state.status,
  1768. progress: progress_state.progress,
  1769. desktop_filename: Some(format!(
  1770. "{}.desktop",
  1771. heck::AsKebabCase(
  1772. self
  1773. .config()
  1774. .product_name
  1775. .as_deref()
  1776. .unwrap_or_else(|| self.package_info().crate_name)
  1777. )
  1778. )),
  1779. })
  1780. .map_err(Into::into)
  1781. }
  1782. }
  1783. /// Progress bar state.
  1784. #[cfg(desktop)]
  1785. #[cfg_attr(
  1786. docsrs,
  1787. doc(cfg(any(target_os = "macos", target_os = "linux", windows)))
  1788. )]
  1789. #[derive(serde::Deserialize)]
  1790. pub struct ProgressBarState {
  1791. /// The progress bar status.
  1792. pub status: Option<ProgressBarStatus>,
  1793. /// The progress bar progress. This can be a value ranging from `0` to `100`
  1794. pub progress: Option<u64>,
  1795. }
  1796. /// Event system APIs.
  1797. impl<R: Runtime> Window<R> {
  1798. /// Listen to an event on this window.
  1799. ///
  1800. /// # Examples
  1801. #[cfg_attr(
  1802. feature = "unstable",
  1803. doc = r####"
  1804. ```
  1805. use tauri::Manager;
  1806. tauri::Builder::default()
  1807. .setup(|app| {
  1808. let window = app.get_window("main").unwrap();
  1809. window.listen("component-loaded", move |event| {
  1810. println!("window just loaded a component");
  1811. });
  1812. Ok(())
  1813. });
  1814. ```
  1815. "####
  1816. )]
  1817. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1818. where
  1819. F: Fn(Event) + Send + 'static,
  1820. {
  1821. self.manager.listen(
  1822. event.into(),
  1823. EventTarget::Window {
  1824. label: self.label().to_string(),
  1825. },
  1826. handler,
  1827. )
  1828. }
  1829. /// Unlisten to an event on this window.
  1830. ///
  1831. /// # Examples
  1832. #[cfg_attr(
  1833. feature = "unstable",
  1834. doc = r####"
  1835. ```
  1836. use tauri::Manager;
  1837. tauri::Builder::default()
  1838. .setup(|app| {
  1839. let window = app.get_window("main").unwrap();
  1840. let window_ = window.clone();
  1841. let handler = window.listen("component-loaded", move |event| {
  1842. println!("window just loaded a component");
  1843. // we no longer need to listen to the event
  1844. // we also could have used `window.once` instead
  1845. window_.unlisten(event.id());
  1846. });
  1847. // stop listening to the event when you do not need it anymore
  1848. window.unlisten(handler);
  1849. Ok(())
  1850. });
  1851. ```
  1852. "####
  1853. )]
  1854. pub fn unlisten(&self, id: EventId) {
  1855. self.manager.unlisten(id)
  1856. }
  1857. /// Listen to an event on this window only once.
  1858. ///
  1859. /// See [`Self::listen`] for more information.
  1860. pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1861. where
  1862. F: FnOnce(Event) + Send + 'static,
  1863. {
  1864. self.manager.once(
  1865. event.into(),
  1866. EventTarget::Window {
  1867. label: self.label().to_string(),
  1868. },
  1869. handler,
  1870. )
  1871. }
  1872. }
  1873. /// The [`WindowEffectsConfig`] object builder
  1874. #[derive(Default)]
  1875. pub struct EffectsBuilder(WindowEffectsConfig);
  1876. impl EffectsBuilder {
  1877. /// Create a new [`WindowEffectsConfig`] builder
  1878. pub fn new() -> Self {
  1879. Self(WindowEffectsConfig::default())
  1880. }
  1881. /// Adds effect to the [`WindowEffectsConfig`] `effects` field
  1882. pub fn effect(mut self, effect: Effect) -> Self {
  1883. self.0.effects.push(effect);
  1884. self
  1885. }
  1886. /// Adds effects to the [`WindowEffectsConfig`] `effects` field
  1887. pub fn effects<I: IntoIterator<Item = Effect>>(mut self, effects: I) -> Self {
  1888. self.0.effects.extend(effects);
  1889. self
  1890. }
  1891. /// Clears the [`WindowEffectsConfig`] `effects` field
  1892. pub fn clear_effects(mut self) -> Self {
  1893. self.0.effects.clear();
  1894. self
  1895. }
  1896. /// Sets `state` field for the [`WindowEffectsConfig`] **macOS Only**
  1897. pub fn state(mut self, state: EffectState) -> Self {
  1898. self.0.state = Some(state);
  1899. self
  1900. }
  1901. /// Sets `radius` field fo the [`WindowEffectsConfig`] **macOS Only**
  1902. pub fn radius(mut self, radius: f64) -> Self {
  1903. self.0.radius = Some(radius);
  1904. self
  1905. }
  1906. /// Sets `color` field fo the [`WindowEffectsConfig`] **Windows Only**
  1907. pub fn color(mut self, color: Color) -> Self {
  1908. self.0.color = Some(color);
  1909. self
  1910. }
  1911. /// Builds a [`WindowEffectsConfig`]
  1912. pub fn build(self) -> WindowEffectsConfig {
  1913. self.0
  1914. }
  1915. }
  1916. impl From<WindowEffectsConfig> for EffectsBuilder {
  1917. fn from(value: WindowEffectsConfig) -> Self {
  1918. Self(value)
  1919. }
  1920. }
  1921. #[cfg(test)]
  1922. mod tests {
  1923. #[test]
  1924. fn window_is_send_sync() {
  1925. crate::test_utils::assert_send::<super::Window>();
  1926. crate::test_utils::assert_sync::<super::Window>();
  1927. }
  1928. }