mod.rs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  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(windows), 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(), self.window_builder.get_theme());
  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())
  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 theme = window
  1048. .theme()
  1049. .map(crate::menu::map_to_menu_theme)
  1050. .unwrap_or(muda::MenuTheme::Auto);
  1051. let _ = menu_.inner().init_for_hwnd_with_theme(hwnd.0, theme);
  1052. }
  1053. #[cfg(any(
  1054. target_os = "linux",
  1055. target_os = "dragonfly",
  1056. target_os = "freebsd",
  1057. target_os = "netbsd",
  1058. target_os = "openbsd"
  1059. ))]
  1060. if let (Ok(gtk_window), Ok(gtk_box)) = (window.gtk_window(), window.default_vbox()) {
  1061. let _ = menu_
  1062. .inner()
  1063. .init_for_gtk_window(&gtk_window, Some(&gtk_box));
  1064. }
  1065. })?;
  1066. self.menu_lock().replace(WindowMenu {
  1067. is_app_wide: false,
  1068. menu,
  1069. });
  1070. Ok(prev_menu)
  1071. }
  1072. /// Removes the window menu and returns it.
  1073. ///
  1074. /// ## Platform-specific:
  1075. ///
  1076. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  1077. /// window, if you need to remove it, use [`AppHandle::remove_menu`] instead.
  1078. pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
  1079. let prev_menu = self.menu_lock().take().map(|m| m.menu);
  1080. // remove from the window
  1081. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1082. if let Some(menu) = &prev_menu {
  1083. let window = self.clone();
  1084. let menu = menu.clone();
  1085. self.run_on_main_thread(move || {
  1086. #[cfg(windows)]
  1087. if let Ok(hwnd) = window.hwnd() {
  1088. let _ = menu.inner().remove_for_hwnd(hwnd.0);
  1089. }
  1090. #[cfg(any(
  1091. target_os = "linux",
  1092. target_os = "dragonfly",
  1093. target_os = "freebsd",
  1094. target_os = "netbsd",
  1095. target_os = "openbsd"
  1096. ))]
  1097. if let Ok(gtk_window) = window.gtk_window() {
  1098. let _ = menu.inner().remove_for_gtk_window(&gtk_window);
  1099. }
  1100. })?;
  1101. }
  1102. self
  1103. .manager
  1104. .remove_menu_from_stash_by_id(prev_menu.as_ref().map(|m| m.id()));
  1105. Ok(prev_menu)
  1106. }
  1107. /// Hides the window menu.
  1108. pub fn hide_menu(&self) -> crate::Result<()> {
  1109. // remove from the window
  1110. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1111. if let Some(window_menu) = &*self.menu_lock() {
  1112. let window = self.clone();
  1113. let menu_ = window_menu.menu.clone();
  1114. self.run_on_main_thread(move || {
  1115. #[cfg(windows)]
  1116. if let Ok(hwnd) = window.hwnd() {
  1117. let _ = menu_.inner().hide_for_hwnd(hwnd.0);
  1118. }
  1119. #[cfg(any(
  1120. target_os = "linux",
  1121. target_os = "dragonfly",
  1122. target_os = "freebsd",
  1123. target_os = "netbsd",
  1124. target_os = "openbsd"
  1125. ))]
  1126. if let Ok(gtk_window) = window.gtk_window() {
  1127. let _ = menu_.inner().hide_for_gtk_window(&gtk_window);
  1128. }
  1129. })?;
  1130. }
  1131. Ok(())
  1132. }
  1133. /// Shows the window menu.
  1134. pub fn show_menu(&self) -> crate::Result<()> {
  1135. // remove from the window
  1136. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1137. if let Some(window_menu) = &*self.menu_lock() {
  1138. let window = self.clone();
  1139. let menu_ = window_menu.menu.clone();
  1140. self.run_on_main_thread(move || {
  1141. #[cfg(windows)]
  1142. if let Ok(hwnd) = window.hwnd() {
  1143. let _ = menu_.inner().show_for_hwnd(hwnd.0);
  1144. }
  1145. #[cfg(any(
  1146. target_os = "linux",
  1147. target_os = "dragonfly",
  1148. target_os = "freebsd",
  1149. target_os = "netbsd",
  1150. target_os = "openbsd"
  1151. ))]
  1152. if let Ok(gtk_window) = window.gtk_window() {
  1153. let _ = menu_.inner().show_for_gtk_window(&gtk_window);
  1154. }
  1155. })?;
  1156. }
  1157. Ok(())
  1158. }
  1159. /// Shows the window menu.
  1160. pub fn is_menu_visible(&self) -> crate::Result<bool> {
  1161. // remove from the window
  1162. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1163. if let Some(window_menu) = &*self.menu_lock() {
  1164. let (tx, rx) = std::sync::mpsc::channel();
  1165. let window = self.clone();
  1166. let menu_ = window_menu.menu.clone();
  1167. self.run_on_main_thread(move || {
  1168. #[cfg(windows)]
  1169. if let Ok(hwnd) = window.hwnd() {
  1170. let _ = tx.send(menu_.inner().is_visible_on_hwnd(hwnd.0));
  1171. }
  1172. #[cfg(any(
  1173. target_os = "linux",
  1174. target_os = "dragonfly",
  1175. target_os = "freebsd",
  1176. target_os = "netbsd",
  1177. target_os = "openbsd"
  1178. ))]
  1179. if let Ok(gtk_window) = window.gtk_window() {
  1180. let _ = tx.send(menu_.inner().is_visible_on_gtk_window(&gtk_window));
  1181. }
  1182. })?;
  1183. return Ok(rx.recv().unwrap_or(false));
  1184. }
  1185. Ok(false)
  1186. }
  1187. /// Shows the specified menu as a context menu at the cursor position.
  1188. pub fn popup_menu<M: ContextMenu>(&self, menu: &M) -> crate::Result<()> {
  1189. menu.popup(self.clone())
  1190. }
  1191. /// Shows the specified menu as a context menu at the specified position.
  1192. ///
  1193. /// The position is relative to the window's top-left corner.
  1194. pub fn popup_menu_at<M: ContextMenu, P: Into<Position>>(
  1195. &self,
  1196. menu: &M,
  1197. position: P,
  1198. ) -> crate::Result<()> {
  1199. menu.popup_at(self.clone(), position)
  1200. }
  1201. }
  1202. /// Window getters.
  1203. impl<R: Runtime> Window<R> {
  1204. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  1205. pub fn scale_factor(&self) -> crate::Result<f64> {
  1206. self.window.dispatcher.scale_factor().map_err(Into::into)
  1207. }
  1208. /// 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.
  1209. pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1210. self.window.dispatcher.inner_position().map_err(Into::into)
  1211. }
  1212. /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
  1213. pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1214. self.window.dispatcher.outer_position().map_err(Into::into)
  1215. }
  1216. /// Returns the physical size of the window's client area.
  1217. ///
  1218. /// The client area is the content of the window, excluding the title bar and borders.
  1219. pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1220. self.window.dispatcher.inner_size().map_err(Into::into)
  1221. }
  1222. /// Returns the physical size of the entire window.
  1223. ///
  1224. /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
  1225. pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1226. self.window.dispatcher.outer_size().map_err(Into::into)
  1227. }
  1228. /// Gets the window's current fullscreen state.
  1229. pub fn is_fullscreen(&self) -> crate::Result<bool> {
  1230. self.window.dispatcher.is_fullscreen().map_err(Into::into)
  1231. }
  1232. /// Gets the window's current minimized state.
  1233. pub fn is_minimized(&self) -> crate::Result<bool> {
  1234. self.window.dispatcher.is_minimized().map_err(Into::into)
  1235. }
  1236. /// Gets the window's current maximized state.
  1237. pub fn is_maximized(&self) -> crate::Result<bool> {
  1238. self.window.dispatcher.is_maximized().map_err(Into::into)
  1239. }
  1240. /// Gets the window's current focus state.
  1241. pub fn is_focused(&self) -> crate::Result<bool> {
  1242. self.window.dispatcher.is_focused().map_err(Into::into)
  1243. }
  1244. /// Gets the window's current decoration state.
  1245. pub fn is_decorated(&self) -> crate::Result<bool> {
  1246. self.window.dispatcher.is_decorated().map_err(Into::into)
  1247. }
  1248. /// Gets the window's current resizable state.
  1249. pub fn is_resizable(&self) -> crate::Result<bool> {
  1250. self.window.dispatcher.is_resizable().map_err(Into::into)
  1251. }
  1252. /// Gets the window's native maximize button state
  1253. ///
  1254. /// ## Platform-specific
  1255. ///
  1256. /// - **Linux / iOS / Android:** Unsupported.
  1257. pub fn is_maximizable(&self) -> crate::Result<bool> {
  1258. self.window.dispatcher.is_maximizable().map_err(Into::into)
  1259. }
  1260. /// Gets the window's native minimize button state
  1261. ///
  1262. /// ## Platform-specific
  1263. ///
  1264. /// - **Linux / iOS / Android:** Unsupported.
  1265. pub fn is_minimizable(&self) -> crate::Result<bool> {
  1266. self.window.dispatcher.is_minimizable().map_err(Into::into)
  1267. }
  1268. /// Gets the window's native close button state
  1269. ///
  1270. /// ## Platform-specific
  1271. ///
  1272. /// - **Linux / iOS / Android:** Unsupported.
  1273. pub fn is_closable(&self) -> crate::Result<bool> {
  1274. self.window.dispatcher.is_closable().map_err(Into::into)
  1275. }
  1276. /// Gets the window's current visibility state.
  1277. pub fn is_visible(&self) -> crate::Result<bool> {
  1278. self.window.dispatcher.is_visible().map_err(Into::into)
  1279. }
  1280. /// Gets the window's current title.
  1281. pub fn title(&self) -> crate::Result<String> {
  1282. self.window.dispatcher.title().map_err(Into::into)
  1283. }
  1284. /// Returns the monitor on which the window currently resides.
  1285. ///
  1286. /// Returns None if current monitor can't be detected.
  1287. pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
  1288. self
  1289. .window
  1290. .dispatcher
  1291. .current_monitor()
  1292. .map(|m| m.map(Into::into))
  1293. .map_err(Into::into)
  1294. }
  1295. /// Returns the monitor that contains the given point.
  1296. pub fn monitor_from_point(&self, x: f64, y: f64) -> crate::Result<Option<Monitor>> {
  1297. self
  1298. .window
  1299. .dispatcher
  1300. .monitor_from_point(x, y)
  1301. .map(|m| m.map(Into::into))
  1302. .map_err(Into::into)
  1303. }
  1304. /// Returns the primary monitor of the system.
  1305. ///
  1306. /// Returns None if it can't identify any monitor as a primary one.
  1307. pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
  1308. self
  1309. .window
  1310. .dispatcher
  1311. .primary_monitor()
  1312. .map(|m| m.map(Into::into))
  1313. .map_err(Into::into)
  1314. }
  1315. /// Returns the list of all the monitors available on the system.
  1316. pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
  1317. self
  1318. .window
  1319. .dispatcher
  1320. .available_monitors()
  1321. .map(|m| m.into_iter().map(Into::into).collect())
  1322. .map_err(Into::into)
  1323. }
  1324. /// Returns the native handle that is used by this window.
  1325. #[cfg(target_os = "macos")]
  1326. pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> {
  1327. self
  1328. .window
  1329. .dispatcher
  1330. .window_handle()
  1331. .map_err(Into::into)
  1332. .and_then(|handle| {
  1333. if let raw_window_handle::RawWindowHandle::AppKit(h) = handle.as_raw() {
  1334. Ok(unsafe {
  1335. use objc::*;
  1336. let ns_window: cocoa::base::id =
  1337. objc::msg_send![h.ns_view.as_ptr() as cocoa::base::id, window];
  1338. ns_window as *mut _
  1339. })
  1340. } else {
  1341. Err(crate::Error::InvalidWindowHandle)
  1342. }
  1343. })
  1344. }
  1345. /// Returns the pointer to the content view of this window.
  1346. #[cfg(target_os = "macos")]
  1347. pub fn ns_view(&self) -> crate::Result<*mut std::ffi::c_void> {
  1348. self
  1349. .window
  1350. .dispatcher
  1351. .window_handle()
  1352. .map_err(Into::into)
  1353. .and_then(|handle| {
  1354. if let raw_window_handle::RawWindowHandle::AppKit(h) = handle.as_raw() {
  1355. Ok(h.ns_view.as_ptr())
  1356. } else {
  1357. Err(crate::Error::InvalidWindowHandle)
  1358. }
  1359. })
  1360. }
  1361. /// Returns the native handle that is used by this window.
  1362. #[cfg(windows)]
  1363. pub fn hwnd(&self) -> crate::Result<HWND> {
  1364. self
  1365. .window
  1366. .dispatcher
  1367. .window_handle()
  1368. .map_err(Into::into)
  1369. .and_then(|handle| {
  1370. if let raw_window_handle::RawWindowHandle::Win32(h) = handle.as_raw() {
  1371. Ok(HWND(h.hwnd.get()))
  1372. } else {
  1373. Err(crate::Error::InvalidWindowHandle)
  1374. }
  1375. })
  1376. }
  1377. /// Returns the `ApplicationWindow` from gtk crate that is used by 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 gtk_window(&self) -> crate::Result<gtk::ApplicationWindow> {
  1388. self.window.dispatcher.gtk_window().map_err(Into::into)
  1389. }
  1390. /// Returns the vertical [`gtk::Box`] that is added by default as the sole child of this window.
  1391. ///
  1392. /// Note that this type can only be used on the main thread.
  1393. #[cfg(any(
  1394. target_os = "linux",
  1395. target_os = "dragonfly",
  1396. target_os = "freebsd",
  1397. target_os = "netbsd",
  1398. target_os = "openbsd"
  1399. ))]
  1400. pub fn default_vbox(&self) -> crate::Result<gtk::Box> {
  1401. self.window.dispatcher.default_vbox().map_err(Into::into)
  1402. }
  1403. /// Returns the current window theme.
  1404. ///
  1405. /// ## Platform-specific
  1406. ///
  1407. /// - **macOS**: Only supported on macOS 10.14+.
  1408. pub fn theme(&self) -> crate::Result<Theme> {
  1409. self.window.dispatcher.theme().map_err(Into::into)
  1410. }
  1411. }
  1412. /// Desktop window getters.
  1413. #[cfg(desktop)]
  1414. impl<R: Runtime> Window<R> {
  1415. /// Get the cursor position relative to the top-left hand corner of the desktop.
  1416. ///
  1417. /// Note that the top-left hand corner of the desktop is not necessarily the same as the screen.
  1418. /// If the user uses a desktop with multiple monitors,
  1419. /// the top-left hand corner of the desktop is the top-left hand corner of the main monitor on Windows and macOS
  1420. /// or the top-left of the leftmost monitor on X11.
  1421. ///
  1422. /// The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region.
  1423. pub fn cursor_position(&self) -> crate::Result<PhysicalPosition<f64>> {
  1424. self.app_handle.cursor_position()
  1425. }
  1426. }
  1427. /// Desktop window setters and actions.
  1428. #[cfg(desktop)]
  1429. impl<R: Runtime> Window<R> {
  1430. /// Centers the window.
  1431. pub fn center(&self) -> crate::Result<()> {
  1432. self.window.dispatcher.center().map_err(Into::into)
  1433. }
  1434. /// Requests user attention to the window, this has no effect if the application
  1435. /// is already focused. How requesting for user attention manifests is platform dependent,
  1436. /// see `UserAttentionType` for details.
  1437. ///
  1438. /// Providing `None` will unset the request for user attention. Unsetting the request for
  1439. /// user attention might not be done automatically by the WM when the window receives input.
  1440. ///
  1441. /// ## Platform-specific
  1442. ///
  1443. /// - **macOS:** `None` has no effect.
  1444. /// - **Linux:** Urgency levels have the same effect.
  1445. pub fn request_user_attention(
  1446. &self,
  1447. request_type: Option<UserAttentionType>,
  1448. ) -> crate::Result<()> {
  1449. self
  1450. .window
  1451. .dispatcher
  1452. .request_user_attention(request_type)
  1453. .map_err(Into::into)
  1454. }
  1455. /// Determines if this window should be resizable.
  1456. /// When resizable is set to false, native window's maximize button is automatically disabled.
  1457. pub fn set_resizable(&self, resizable: bool) -> crate::Result<()> {
  1458. self
  1459. .window
  1460. .dispatcher
  1461. .set_resizable(resizable)
  1462. .map_err(Into::into)
  1463. }
  1464. /// Determines if this window's native maximize button should be enabled.
  1465. /// If resizable is set to false, this setting is ignored.
  1466. ///
  1467. /// ## Platform-specific
  1468. ///
  1469. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  1470. /// - **Linux / iOS / Android:** Unsupported.
  1471. pub fn set_maximizable(&self, maximizable: bool) -> crate::Result<()> {
  1472. self
  1473. .window
  1474. .dispatcher
  1475. .set_maximizable(maximizable)
  1476. .map_err(Into::into)
  1477. }
  1478. /// Determines if this window's native minimize button should be enabled.
  1479. ///
  1480. /// ## Platform-specific
  1481. ///
  1482. /// - **Linux / iOS / Android:** Unsupported.
  1483. pub fn set_minimizable(&self, minimizable: bool) -> crate::Result<()> {
  1484. self
  1485. .window
  1486. .dispatcher
  1487. .set_minimizable(minimizable)
  1488. .map_err(Into::into)
  1489. }
  1490. /// Determines if this window's native close button should be enabled.
  1491. ///
  1492. /// ## Platform-specific
  1493. ///
  1494. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  1495. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  1496. /// - **iOS / Android:** Unsupported.
  1497. pub fn set_closable(&self, closable: bool) -> crate::Result<()> {
  1498. self
  1499. .window
  1500. .dispatcher
  1501. .set_closable(closable)
  1502. .map_err(Into::into)
  1503. }
  1504. /// Set this window's title.
  1505. pub fn set_title(&self, title: &str) -> crate::Result<()> {
  1506. self
  1507. .window
  1508. .dispatcher
  1509. .set_title(title.to_string())
  1510. .map_err(Into::into)
  1511. }
  1512. /// Maximizes this window.
  1513. pub fn maximize(&self) -> crate::Result<()> {
  1514. self.window.dispatcher.maximize().map_err(Into::into)
  1515. }
  1516. /// Un-maximizes this window.
  1517. pub fn unmaximize(&self) -> crate::Result<()> {
  1518. self.window.dispatcher.unmaximize().map_err(Into::into)
  1519. }
  1520. /// Minimizes this window.
  1521. pub fn minimize(&self) -> crate::Result<()> {
  1522. self.window.dispatcher.minimize().map_err(Into::into)
  1523. }
  1524. /// Un-minimizes this window.
  1525. pub fn unminimize(&self) -> crate::Result<()> {
  1526. self.window.dispatcher.unminimize().map_err(Into::into)
  1527. }
  1528. /// Show this window.
  1529. pub fn show(&self) -> crate::Result<()> {
  1530. self.window.dispatcher.show().map_err(Into::into)
  1531. }
  1532. /// Hide this window.
  1533. pub fn hide(&self) -> crate::Result<()> {
  1534. self.window.dispatcher.hide().map_err(Into::into)
  1535. }
  1536. /// Closes this window. It emits [`crate::RunEvent::CloseRequested`] first like a user-initiated close request so you can intercept it.
  1537. pub fn close(&self) -> crate::Result<()> {
  1538. self.window.dispatcher.close().map_err(Into::into)
  1539. }
  1540. /// Destroys this window. Similar to [`Self::close`] but does not emit any events and force close the window instead.
  1541. pub fn destroy(&self) -> crate::Result<()> {
  1542. self.window.dispatcher.destroy().map_err(Into::into)
  1543. }
  1544. /// Determines if this window should be [decorated].
  1545. ///
  1546. /// [decorated]: https://en.wikipedia.org/wiki/Window_(computing)#Window_decoration
  1547. pub fn set_decorations(&self, decorations: bool) -> crate::Result<()> {
  1548. self
  1549. .window
  1550. .dispatcher
  1551. .set_decorations(decorations)
  1552. .map_err(Into::into)
  1553. }
  1554. /// Determines if this window should have shadow.
  1555. ///
  1556. /// ## Platform-specific
  1557. ///
  1558. /// - **Windows:**
  1559. /// - `false` has no effect on decorated window, shadow are always ON.
  1560. /// - `true` will make undecorated window have a 1px white border,
  1561. /// and on Windows 11, it will have a rounded corners.
  1562. /// - **Linux:** Unsupported.
  1563. pub fn set_shadow(&self, enable: bool) -> crate::Result<()> {
  1564. self
  1565. .window
  1566. .dispatcher
  1567. .set_shadow(enable)
  1568. .map_err(Into::into)
  1569. }
  1570. /// Sets window effects, pass [`None`] to clear any effects applied if possible.
  1571. ///
  1572. /// Requires the window to be transparent.
  1573. ///
  1574. /// See [`EffectsBuilder`] for a convenient builder for [`WindowEffectsConfig`].
  1575. ///
  1576. #[cfg_attr(
  1577. feature = "unstable",
  1578. doc = r####"
  1579. ```rust,no_run
  1580. use tauri::{Manager, window::{Color, Effect, EffectState, EffectsBuilder}};
  1581. tauri::Builder::default()
  1582. .setup(|app| {
  1583. let window = app.get_window("main").unwrap();
  1584. window.set_effects(
  1585. EffectsBuilder::new()
  1586. .effect(Effect::Popover)
  1587. .state(EffectState::Active)
  1588. .radius(5.)
  1589. .color(Color(0, 0, 0, 255))
  1590. .build(),
  1591. )?;
  1592. Ok(())
  1593. });
  1594. ```
  1595. "####
  1596. )]
  1597. ///
  1598. /// ## Platform-specific:
  1599. ///
  1600. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  1601. /// - **Linux**: Unsupported
  1602. pub fn set_effects<E: Into<Option<WindowEffectsConfig>>>(&self, effects: E) -> crate::Result<()> {
  1603. let effects = effects.into();
  1604. let window = self.clone();
  1605. self.run_on_main_thread(move || {
  1606. let _ = crate::vibrancy::set_window_effects(&window, effects);
  1607. })
  1608. }
  1609. /// Determines if this window should always be below other windows.
  1610. pub fn set_always_on_bottom(&self, always_on_bottom: bool) -> crate::Result<()> {
  1611. self
  1612. .window
  1613. .dispatcher
  1614. .set_always_on_bottom(always_on_bottom)
  1615. .map_err(Into::into)
  1616. }
  1617. /// Determines if this window should always be on top of other windows.
  1618. pub fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> {
  1619. self
  1620. .window
  1621. .dispatcher
  1622. .set_always_on_top(always_on_top)
  1623. .map_err(Into::into)
  1624. }
  1625. /// Sets whether the window should be visible on all workspaces or virtual desktops.
  1626. ///
  1627. /// ## Platform-specific
  1628. ///
  1629. /// - **Windows / iOS / Android:** Unsupported.
  1630. pub fn set_visible_on_all_workspaces(
  1631. &self,
  1632. visible_on_all_workspaces: bool,
  1633. ) -> crate::Result<()> {
  1634. self
  1635. .window
  1636. .dispatcher
  1637. .set_visible_on_all_workspaces(visible_on_all_workspaces)
  1638. .map_err(Into::into)
  1639. }
  1640. /// Prevents the window contents from being captured by other apps.
  1641. pub fn set_content_protected(&self, protected: bool) -> crate::Result<()> {
  1642. self
  1643. .window
  1644. .dispatcher
  1645. .set_content_protected(protected)
  1646. .map_err(Into::into)
  1647. }
  1648. /// Resizes this window.
  1649. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
  1650. self
  1651. .window
  1652. .dispatcher
  1653. .set_size(size.into())
  1654. .map_err(Into::into)
  1655. }
  1656. /// Sets this window's minimum inner size.
  1657. pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1658. self
  1659. .window
  1660. .dispatcher
  1661. .set_min_size(size.map(|s| s.into()))
  1662. .map_err(Into::into)
  1663. }
  1664. /// Sets this window's maximum inner size.
  1665. pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1666. self
  1667. .window
  1668. .dispatcher
  1669. .set_max_size(size.map(|s| s.into()))
  1670. .map_err(Into::into)
  1671. }
  1672. /// Sets this window's position.
  1673. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1674. self
  1675. .window
  1676. .dispatcher
  1677. .set_position(position.into())
  1678. .map_err(Into::into)
  1679. }
  1680. /// Determines if this window should be fullscreen.
  1681. pub fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
  1682. self
  1683. .window
  1684. .dispatcher
  1685. .set_fullscreen(fullscreen)
  1686. .map_err(Into::into)
  1687. }
  1688. /// Bring the window to front and focus.
  1689. pub fn set_focus(&self) -> crate::Result<()> {
  1690. self.window.dispatcher.set_focus().map_err(Into::into)
  1691. }
  1692. /// Sets this window' icon.
  1693. pub fn set_icon(&self, icon: Image<'_>) -> crate::Result<()> {
  1694. self
  1695. .window
  1696. .dispatcher
  1697. .set_icon(icon.into())
  1698. .map_err(Into::into)
  1699. }
  1700. /// Whether to hide the window icon from the taskbar or not.
  1701. ///
  1702. /// ## Platform-specific
  1703. ///
  1704. /// - **macOS:** Unsupported.
  1705. pub fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> {
  1706. self
  1707. .window
  1708. .dispatcher
  1709. .set_skip_taskbar(skip)
  1710. .map_err(Into::into)
  1711. }
  1712. /// Grabs the cursor, preventing it from leaving the window.
  1713. ///
  1714. /// There's no guarantee that the cursor will be hidden. You should
  1715. /// hide it by yourself if you want so.
  1716. ///
  1717. /// ## Platform-specific
  1718. ///
  1719. /// - **Linux:** Unsupported.
  1720. /// - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
  1721. pub fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
  1722. self
  1723. .window
  1724. .dispatcher
  1725. .set_cursor_grab(grab)
  1726. .map_err(Into::into)
  1727. }
  1728. /// Modifies the cursor's visibility.
  1729. ///
  1730. /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
  1731. ///
  1732. /// ## Platform-specific
  1733. ///
  1734. /// - **Windows:** The cursor is only hidden within the confines of the window.
  1735. /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
  1736. /// outside of the window.
  1737. pub fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
  1738. self
  1739. .window
  1740. .dispatcher
  1741. .set_cursor_visible(visible)
  1742. .map_err(Into::into)
  1743. }
  1744. /// Modifies the cursor icon of the window.
  1745. pub fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
  1746. self
  1747. .window
  1748. .dispatcher
  1749. .set_cursor_icon(icon)
  1750. .map_err(Into::into)
  1751. }
  1752. /// Changes the position of the cursor in window coordinates.
  1753. pub fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1754. self
  1755. .window
  1756. .dispatcher
  1757. .set_cursor_position(position)
  1758. .map_err(Into::into)
  1759. }
  1760. /// Ignores the window cursor events.
  1761. pub fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
  1762. self
  1763. .window
  1764. .dispatcher
  1765. .set_ignore_cursor_events(ignore)
  1766. .map_err(Into::into)
  1767. }
  1768. /// Starts dragging the window.
  1769. pub fn start_dragging(&self) -> crate::Result<()> {
  1770. self.window.dispatcher.start_dragging().map_err(Into::into)
  1771. }
  1772. /// Starts resize-dragging the window.
  1773. pub fn start_resize_dragging(
  1774. &self,
  1775. direction: tauri_runtime::ResizeDirection,
  1776. ) -> crate::Result<()> {
  1777. self
  1778. .window
  1779. .dispatcher
  1780. .start_resize_dragging(direction)
  1781. .map_err(Into::into)
  1782. }
  1783. /// Sets the taskbar progress state.
  1784. ///
  1785. /// ## Platform-specific
  1786. ///
  1787. /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window.
  1788. /// - **Linux**: Only supported desktop environments with `libunity` (e.g. GNOME).
  1789. /// - **iOS / Android:** Unsupported.
  1790. pub fn set_progress_bar(&self, progress_state: ProgressBarState) -> crate::Result<()> {
  1791. self
  1792. .window
  1793. .dispatcher
  1794. .set_progress_bar(crate::runtime::ProgressBarState {
  1795. status: progress_state.status,
  1796. progress: progress_state.progress,
  1797. desktop_filename: Some(format!("{}.desktop", self.package_info().crate_name)),
  1798. })
  1799. .map_err(Into::into)
  1800. }
  1801. /// Sets the title bar style. **macOS only**.
  1802. pub fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> crate::Result<()> {
  1803. self
  1804. .window
  1805. .dispatcher
  1806. .set_title_bar_style(style)
  1807. .map_err(Into::into)
  1808. }
  1809. }
  1810. /// Progress bar state.
  1811. #[cfg(desktop)]
  1812. #[cfg_attr(
  1813. docsrs,
  1814. doc(cfg(any(target_os = "macos", target_os = "linux", windows)))
  1815. )]
  1816. #[derive(serde::Deserialize)]
  1817. pub struct ProgressBarState {
  1818. /// The progress bar status.
  1819. pub status: Option<ProgressBarStatus>,
  1820. /// The progress bar progress. This can be a value ranging from `0` to `100`
  1821. pub progress: Option<u64>,
  1822. }
  1823. /// Event system APIs.
  1824. impl<R: Runtime> Window<R> {
  1825. /// Listen to an event on this window.
  1826. ///
  1827. /// # Examples
  1828. #[cfg_attr(
  1829. feature = "unstable",
  1830. doc = r####"
  1831. ```
  1832. use tauri::Manager;
  1833. tauri::Builder::default()
  1834. .setup(|app| {
  1835. let window = app.get_window("main").unwrap();
  1836. window.listen("component-loaded", move |event| {
  1837. println!("window just loaded a component");
  1838. });
  1839. Ok(())
  1840. });
  1841. ```
  1842. "####
  1843. )]
  1844. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1845. where
  1846. F: Fn(Event) + Send + 'static,
  1847. {
  1848. self.manager.listen(
  1849. event.into(),
  1850. EventTarget::Window {
  1851. label: self.label().to_string(),
  1852. },
  1853. handler,
  1854. )
  1855. }
  1856. /// Unlisten to an event on this window.
  1857. ///
  1858. /// # Examples
  1859. #[cfg_attr(
  1860. feature = "unstable",
  1861. doc = r####"
  1862. ```
  1863. use tauri::Manager;
  1864. tauri::Builder::default()
  1865. .setup(|app| {
  1866. let window = app.get_window("main").unwrap();
  1867. let window_ = window.clone();
  1868. let handler = window.listen("component-loaded", move |event| {
  1869. println!("window just loaded a component");
  1870. // we no longer need to listen to the event
  1871. // we also could have used `window.once` instead
  1872. window_.unlisten(event.id());
  1873. });
  1874. // stop listening to the event when you do not need it anymore
  1875. window.unlisten(handler);
  1876. Ok(())
  1877. });
  1878. ```
  1879. "####
  1880. )]
  1881. pub fn unlisten(&self, id: EventId) {
  1882. self.manager.unlisten(id)
  1883. }
  1884. /// Listen to an event on this window only once.
  1885. ///
  1886. /// See [`Self::listen`] for more information.
  1887. pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1888. where
  1889. F: FnOnce(Event) + Send + 'static,
  1890. {
  1891. self.manager.once(
  1892. event.into(),
  1893. EventTarget::Window {
  1894. label: self.label().to_string(),
  1895. },
  1896. handler,
  1897. )
  1898. }
  1899. }
  1900. /// The [`WindowEffectsConfig`] object builder
  1901. #[derive(Default)]
  1902. pub struct EffectsBuilder(WindowEffectsConfig);
  1903. impl EffectsBuilder {
  1904. /// Create a new [`WindowEffectsConfig`] builder
  1905. pub fn new() -> Self {
  1906. Self(WindowEffectsConfig::default())
  1907. }
  1908. /// Adds effect to the [`WindowEffectsConfig`] `effects` field
  1909. pub fn effect(mut self, effect: Effect) -> Self {
  1910. self.0.effects.push(effect);
  1911. self
  1912. }
  1913. /// Adds effects to the [`WindowEffectsConfig`] `effects` field
  1914. pub fn effects<I: IntoIterator<Item = Effect>>(mut self, effects: I) -> Self {
  1915. self.0.effects.extend(effects);
  1916. self
  1917. }
  1918. /// Clears the [`WindowEffectsConfig`] `effects` field
  1919. pub fn clear_effects(mut self) -> Self {
  1920. self.0.effects.clear();
  1921. self
  1922. }
  1923. /// Sets `state` field for the [`WindowEffectsConfig`] **macOS Only**
  1924. pub fn state(mut self, state: EffectState) -> Self {
  1925. self.0.state = Some(state);
  1926. self
  1927. }
  1928. /// Sets `radius` field fo the [`WindowEffectsConfig`] **macOS Only**
  1929. pub fn radius(mut self, radius: f64) -> Self {
  1930. self.0.radius = Some(radius);
  1931. self
  1932. }
  1933. /// Sets `color` field fo the [`WindowEffectsConfig`] **Windows Only**
  1934. pub fn color(mut self, color: Color) -> Self {
  1935. self.0.color = Some(color);
  1936. self
  1937. }
  1938. /// Builds a [`WindowEffectsConfig`]
  1939. pub fn build(self) -> WindowEffectsConfig {
  1940. self.0
  1941. }
  1942. }
  1943. impl From<WindowEffectsConfig> for EffectsBuilder {
  1944. fn from(value: WindowEffectsConfig) -> Self {
  1945. Self(value)
  1946. }
  1947. }
  1948. #[cfg(test)]
  1949. mod tests {
  1950. #[test]
  1951. fn window_is_send_sync() {
  1952. crate::test_utils::assert_send::<super::Window>();
  1953. crate::test_utils::assert_sync::<super::Window>();
  1954. }
  1955. }