mod.rs 60 KB

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