mod.rs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064
  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().tauri.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. #[must_use]
  639. pub fn owner(mut self, owner: &Window<R>) -> crate::Result<Self> {
  640. self.window_builder = self.window_builder.owner(owner.hwnd()?);
  641. Ok(self)
  642. }
  643. /// Set an owner to the window to be created.
  644. ///
  645. /// From MSDN:
  646. /// - An owned window is always above its owner in the z-order.
  647. /// - The system automatically destroys an owned window when its owner is destroyed.
  648. /// - An owned window is hidden when its owner is minimized.
  649. ///
  650. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
  651. ///
  652. /// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
  653. #[cfg(windows)]
  654. #[must_use]
  655. pub fn owner_raw(mut self, owner: HWND) -> Self {
  656. self.window_builder = self.window_builder.owner(owner);
  657. self
  658. }
  659. /// Sets a parent to the window to be created.
  660. ///
  661. /// A child window has the WS_CHILD style and is confined to the client area of its parent window.
  662. ///
  663. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
  664. ///
  665. /// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
  666. #[cfg(windows)]
  667. #[must_use]
  668. pub fn parent_raw(mut self, parent: HWND) -> Self {
  669. self.window_builder = self.window_builder.parent(parent);
  670. self
  671. }
  672. /// Sets a parent to the window to be created.
  673. ///
  674. /// See <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
  675. ///
  676. /// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
  677. #[cfg(target_os = "macos")]
  678. #[must_use]
  679. pub fn parent_raw(mut self, parent: *mut std::ffi::c_void) -> Self {
  680. self.window_builder = self.window_builder.parent(parent);
  681. self
  682. }
  683. /// Sets the window to be created transient for parent.
  684. ///
  685. /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  686. ///
  687. /// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
  688. #[cfg(any(
  689. target_os = "linux",
  690. target_os = "dragonfly",
  691. target_os = "freebsd",
  692. target_os = "netbsd",
  693. target_os = "openbsd"
  694. ))]
  695. pub fn transient_for(mut self, parent: &Window<R>) -> crate::Result<Self> {
  696. self.window_builder = self.window_builder.transient_for(&parent.gtk_window()?);
  697. Ok(self)
  698. }
  699. /// Sets the window to be created transient for parent.
  700. ///
  701. /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  702. ///
  703. /// **Note:** This is a low level API. See [`Self::parent`] and [`Self::transient_for`] for higher level wrappers for Tauri windows.
  704. #[cfg(any(
  705. target_os = "linux",
  706. target_os = "dragonfly",
  707. target_os = "freebsd",
  708. target_os = "netbsd",
  709. target_os = "openbsd"
  710. ))]
  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) 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("webview_window", &self.webview_window)
  793. .finish()
  794. }
  795. }
  796. unsafe impl<R: Runtime> raw_window_handle::HasRawWindowHandle for Window<R> {
  797. fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle {
  798. self.window.dispatcher.raw_window_handle().unwrap()
  799. }
  800. }
  801. impl<R: Runtime> Clone for Window<R> {
  802. fn clone(&self) -> Self {
  803. Self {
  804. window: self.window.clone(),
  805. manager: self.manager.clone(),
  806. app_handle: self.app_handle.clone(),
  807. #[cfg(desktop)]
  808. menu: self.menu.clone(),
  809. webview_window: self.webview_window,
  810. }
  811. }
  812. }
  813. impl<R: Runtime> Hash for Window<R> {
  814. /// Only use the [`Window`]'s label to represent its hash.
  815. fn hash<H: Hasher>(&self, state: &mut H) {
  816. self.window.label.hash(state)
  817. }
  818. }
  819. impl<R: Runtime> Eq for Window<R> {}
  820. impl<R: Runtime> PartialEq for Window<R> {
  821. /// Only use the [`Window`]'s label to compare equality.
  822. fn eq(&self, other: &Self) -> bool {
  823. self.window.label.eq(&other.window.label)
  824. }
  825. }
  826. impl<R: Runtime> Manager<R> for Window<R> {}
  827. impl<R: Runtime> ManagerBase<R> for Window<R> {
  828. fn manager(&self) -> &AppManager<R> {
  829. &self.manager
  830. }
  831. fn manager_owned(&self) -> Arc<AppManager<R>> {
  832. self.manager.clone()
  833. }
  834. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  835. RuntimeOrDispatch::Dispatch(self.window.dispatcher.clone())
  836. }
  837. fn managed_app_handle(&self) -> &AppHandle<R> {
  838. &self.app_handle
  839. }
  840. }
  841. impl<'de, R: Runtime> CommandArg<'de, R> for Window<R> {
  842. /// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
  843. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  844. Ok(command.message.webview().window().clone())
  845. }
  846. }
  847. /// Base window functions.
  848. impl<R: Runtime> Window<R> {
  849. /// Create a new window that is attached to the manager.
  850. pub(crate) fn new(
  851. manager: Arc<AppManager<R>>,
  852. window: DetachedWindow<EventLoopMessage, R>,
  853. app_handle: AppHandle<R>,
  854. #[cfg(desktop)] menu: Option<WindowMenu<R>>,
  855. webview_window: bool,
  856. ) -> Self {
  857. Self {
  858. window,
  859. manager,
  860. app_handle,
  861. #[cfg(desktop)]
  862. menu: Arc::new(std::sync::Mutex::new(menu)),
  863. webview_window,
  864. }
  865. }
  866. /// Initializes a window builder with the given window label.
  867. ///
  868. /// Data URLs are only supported with the `webview-data-url` feature flag.
  869. #[cfg(feature = "unstable")]
  870. #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
  871. pub fn builder<M: Manager<R>, L: Into<String>>(manager: &M, label: L) -> WindowBuilder<'_, R, M> {
  872. WindowBuilder::new(manager, label.into())
  873. }
  874. /// Adds a new webview as a child of this window.
  875. #[cfg(any(test, all(desktop, feature = "unstable")))]
  876. #[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "unstable"))))]
  877. pub fn add_child<P: Into<Position>, S: Into<Size>>(
  878. &self,
  879. webview_builder: WebviewBuilder<R>,
  880. position: P,
  881. size: S,
  882. ) -> crate::Result<Webview<R>> {
  883. webview_builder.build(self.clone(), position.into(), size.into())
  884. }
  885. /// List of webviews associated with this window.
  886. pub fn webviews(&self) -> Vec<Webview<R>> {
  887. self
  888. .manager
  889. .webview
  890. .webviews_lock()
  891. .values()
  892. .filter(|w| w.window() == self)
  893. .cloned()
  894. .collect()
  895. }
  896. /// Runs the given closure on the main thread.
  897. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  898. self
  899. .window
  900. .dispatcher
  901. .run_on_main_thread(f)
  902. .map_err(Into::into)
  903. }
  904. /// The label of this window.
  905. pub fn label(&self) -> &str {
  906. &self.window.label
  907. }
  908. /// Registers a window event listener.
  909. pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) {
  910. self
  911. .window
  912. .dispatcher
  913. .on_window_event(move |event| f(&event.clone().into()));
  914. }
  915. }
  916. /// Menu APIs
  917. #[cfg(desktop)]
  918. impl<R: Runtime> Window<R> {
  919. /// Registers a global menu event listener.
  920. ///
  921. /// Note that this handler is called for any menu event,
  922. /// whether it is coming from this window, another window or from the tray icon menu.
  923. ///
  924. /// Also note that this handler will not be called if
  925. /// the window used to register it was closed.
  926. ///
  927. /// # Examples
  928. #[cfg_attr(
  929. feature = "unstable",
  930. doc = r####"
  931. ```
  932. use tauri::menu::{Menu, Submenu, MenuItem};
  933. tauri::Builder::default()
  934. .setup(|app| {
  935. let handle = app.handle();
  936. let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
  937. let menu = Menu::with_items(handle, &[
  938. &Submenu::with_items(handle, "File", true, &[
  939. &save_menu_item,
  940. ])?,
  941. ])?;
  942. let window = tauri::window::WindowBuilder::new(app, "editor")
  943. .menu(menu)
  944. .build()
  945. .unwrap();
  946. window.on_menu_event(move |window, event| {
  947. if event.id == save_menu_item.id() {
  948. // save menu item
  949. }
  950. });
  951. Ok(())
  952. });
  953. ```
  954. "####
  955. )]
  956. pub fn on_menu_event<F: Fn(&Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
  957. &self,
  958. f: F,
  959. ) {
  960. self
  961. .manager
  962. .menu
  963. .event_listeners
  964. .lock()
  965. .unwrap()
  966. .insert(self.label().to_string(), Box::new(f));
  967. }
  968. pub(crate) fn menu_lock(&self) -> std::sync::MutexGuard<'_, Option<WindowMenu<R>>> {
  969. self.menu.lock().expect("poisoned window")
  970. }
  971. #[cfg_attr(target_os = "macos", allow(dead_code))]
  972. pub(crate) fn has_app_wide_menu(&self) -> bool {
  973. self
  974. .menu_lock()
  975. .as_ref()
  976. .map(|m| m.is_app_wide)
  977. .unwrap_or(false)
  978. }
  979. #[cfg_attr(target_os = "macos", allow(dead_code))]
  980. pub(crate) fn is_menu_in_use<I: PartialEq<MenuId>>(&self, id: &I) -> bool {
  981. self
  982. .menu_lock()
  983. .as_ref()
  984. .map(|m| id.eq(m.menu.id()))
  985. .unwrap_or(false)
  986. }
  987. /// Returns this window menu .
  988. pub fn menu(&self) -> Option<Menu<R>> {
  989. self.menu_lock().as_ref().map(|m| m.menu.clone())
  990. }
  991. /// Sets the window menu and returns the previous one.
  992. ///
  993. /// ## Platform-specific:
  994. ///
  995. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  996. /// window, if you need to set it, use [`AppHandle::set_menu`] instead.
  997. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  998. pub fn set_menu(&self, menu: Menu<R>) -> crate::Result<Option<Menu<R>>> {
  999. let prev_menu = self.remove_menu()?;
  1000. self.manager.menu.insert_menu_into_stash(&menu);
  1001. let window = self.clone();
  1002. let menu_ = menu.clone();
  1003. self.run_on_main_thread(move || {
  1004. #[cfg(windows)]
  1005. if let Ok(hwnd) = window.hwnd() {
  1006. let _ = menu_.inner().init_for_hwnd(hwnd.0);
  1007. }
  1008. #[cfg(any(
  1009. target_os = "linux",
  1010. target_os = "dragonfly",
  1011. target_os = "freebsd",
  1012. target_os = "netbsd",
  1013. target_os = "openbsd"
  1014. ))]
  1015. if let (Ok(gtk_window), Ok(gtk_box)) = (window.gtk_window(), window.default_vbox()) {
  1016. let _ = menu_
  1017. .inner()
  1018. .init_for_gtk_window(&gtk_window, Some(&gtk_box));
  1019. }
  1020. })?;
  1021. self.menu_lock().replace(WindowMenu {
  1022. is_app_wide: false,
  1023. menu,
  1024. });
  1025. Ok(prev_menu)
  1026. }
  1027. /// Removes the window menu and returns it.
  1028. ///
  1029. /// ## Platform-specific:
  1030. ///
  1031. /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
  1032. /// window, if you need to remove it, use [`AppHandle::remove_menu`] instead.
  1033. pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
  1034. let prev_menu = self.menu_lock().take().map(|m| m.menu);
  1035. // remove from the window
  1036. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1037. if let Some(menu) = &prev_menu {
  1038. let window = self.clone();
  1039. let menu = menu.clone();
  1040. self.run_on_main_thread(move || {
  1041. #[cfg(windows)]
  1042. if let Ok(hwnd) = window.hwnd() {
  1043. let _ = menu.inner().remove_for_hwnd(hwnd.0);
  1044. }
  1045. #[cfg(any(
  1046. target_os = "linux",
  1047. target_os = "dragonfly",
  1048. target_os = "freebsd",
  1049. target_os = "netbsd",
  1050. target_os = "openbsd"
  1051. ))]
  1052. if let Ok(gtk_window) = window.gtk_window() {
  1053. let _ = menu.inner().remove_for_gtk_window(&gtk_window);
  1054. }
  1055. })?;
  1056. }
  1057. self
  1058. .manager
  1059. .remove_menu_from_stash_by_id(prev_menu.as_ref().map(|m| m.id()));
  1060. Ok(prev_menu)
  1061. }
  1062. /// Hides the window menu.
  1063. pub fn hide_menu(&self) -> crate::Result<()> {
  1064. // remove from the window
  1065. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1066. if let Some(window_menu) = &*self.menu_lock() {
  1067. let window = self.clone();
  1068. let menu_ = window_menu.menu.clone();
  1069. self.run_on_main_thread(move || {
  1070. #[cfg(windows)]
  1071. if let Ok(hwnd) = window.hwnd() {
  1072. let _ = menu_.inner().hide_for_hwnd(hwnd.0);
  1073. }
  1074. #[cfg(any(
  1075. target_os = "linux",
  1076. target_os = "dragonfly",
  1077. target_os = "freebsd",
  1078. target_os = "netbsd",
  1079. target_os = "openbsd"
  1080. ))]
  1081. if let Ok(gtk_window) = window.gtk_window() {
  1082. let _ = menu_.inner().hide_for_gtk_window(&gtk_window);
  1083. }
  1084. })?;
  1085. }
  1086. Ok(())
  1087. }
  1088. /// Shows the window menu.
  1089. pub fn show_menu(&self) -> crate::Result<()> {
  1090. // remove from the window
  1091. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1092. if let Some(window_menu) = &*self.menu_lock() {
  1093. let window = self.clone();
  1094. let menu_ = window_menu.menu.clone();
  1095. self.run_on_main_thread(move || {
  1096. #[cfg(windows)]
  1097. if let Ok(hwnd) = window.hwnd() {
  1098. let _ = menu_.inner().show_for_hwnd(hwnd.0);
  1099. }
  1100. #[cfg(any(
  1101. target_os = "linux",
  1102. target_os = "dragonfly",
  1103. target_os = "freebsd",
  1104. target_os = "netbsd",
  1105. target_os = "openbsd"
  1106. ))]
  1107. if let Ok(gtk_window) = window.gtk_window() {
  1108. let _ = menu_.inner().show_for_gtk_window(&gtk_window);
  1109. }
  1110. })?;
  1111. }
  1112. Ok(())
  1113. }
  1114. /// Shows the window menu.
  1115. pub fn is_menu_visible(&self) -> crate::Result<bool> {
  1116. // remove from the window
  1117. #[cfg_attr(target_os = "macos", allow(unused_variables))]
  1118. if let Some(window_menu) = &*self.menu_lock() {
  1119. let (tx, rx) = std::sync::mpsc::channel();
  1120. let window = self.clone();
  1121. let menu_ = window_menu.menu.clone();
  1122. self.run_on_main_thread(move || {
  1123. #[cfg(windows)]
  1124. if let Ok(hwnd) = window.hwnd() {
  1125. let _ = tx.send(menu_.inner().is_visible_on_hwnd(hwnd.0));
  1126. }
  1127. #[cfg(any(
  1128. target_os = "linux",
  1129. target_os = "dragonfly",
  1130. target_os = "freebsd",
  1131. target_os = "netbsd",
  1132. target_os = "openbsd"
  1133. ))]
  1134. if let Ok(gtk_window) = window.gtk_window() {
  1135. let _ = tx.send(menu_.inner().is_visible_on_gtk_window(&gtk_window));
  1136. }
  1137. })?;
  1138. return Ok(rx.recv().unwrap_or(false));
  1139. }
  1140. Ok(false)
  1141. }
  1142. /// Shows the specified menu as a context menu at the cursor position.
  1143. pub fn popup_menu<M: ContextMenu>(&self, menu: &M) -> crate::Result<()> {
  1144. menu.popup(self.clone())
  1145. }
  1146. /// Shows the specified menu as a context menu at the specified position.
  1147. ///
  1148. /// The position is relative to the window's top-left corner.
  1149. pub fn popup_menu_at<M: ContextMenu, P: Into<Position>>(
  1150. &self,
  1151. menu: &M,
  1152. position: P,
  1153. ) -> crate::Result<()> {
  1154. menu.popup_at(self.clone(), position)
  1155. }
  1156. }
  1157. /// Window getters.
  1158. impl<R: Runtime> Window<R> {
  1159. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  1160. pub fn scale_factor(&self) -> crate::Result<f64> {
  1161. self.window.dispatcher.scale_factor().map_err(Into::into)
  1162. }
  1163. /// 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.
  1164. pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1165. self.window.dispatcher.inner_position().map_err(Into::into)
  1166. }
  1167. /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
  1168. pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  1169. self.window.dispatcher.outer_position().map_err(Into::into)
  1170. }
  1171. /// Returns the physical size of the window's client area.
  1172. ///
  1173. /// The client area is the content of the window, excluding the title bar and borders.
  1174. pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1175. self.window.dispatcher.inner_size().map_err(Into::into)
  1176. }
  1177. /// Returns the physical size of the entire window.
  1178. ///
  1179. /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
  1180. pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> {
  1181. self.window.dispatcher.outer_size().map_err(Into::into)
  1182. }
  1183. /// Gets the window's current fullscreen state.
  1184. pub fn is_fullscreen(&self) -> crate::Result<bool> {
  1185. self.window.dispatcher.is_fullscreen().map_err(Into::into)
  1186. }
  1187. /// Gets the window's current minimized state.
  1188. pub fn is_minimized(&self) -> crate::Result<bool> {
  1189. self.window.dispatcher.is_minimized().map_err(Into::into)
  1190. }
  1191. /// Gets the window's current maximized state.
  1192. pub fn is_maximized(&self) -> crate::Result<bool> {
  1193. self.window.dispatcher.is_maximized().map_err(Into::into)
  1194. }
  1195. /// Gets the window's current focus state.
  1196. pub fn is_focused(&self) -> crate::Result<bool> {
  1197. self.window.dispatcher.is_focused().map_err(Into::into)
  1198. }
  1199. /// Gets the window’s current decoration state.
  1200. pub fn is_decorated(&self) -> crate::Result<bool> {
  1201. self.window.dispatcher.is_decorated().map_err(Into::into)
  1202. }
  1203. /// Gets the window’s current resizable state.
  1204. pub fn is_resizable(&self) -> crate::Result<bool> {
  1205. self.window.dispatcher.is_resizable().map_err(Into::into)
  1206. }
  1207. /// Gets the window’s native maximize button state
  1208. ///
  1209. /// ## Platform-specific
  1210. ///
  1211. /// - **Linux / iOS / Android:** Unsupported.
  1212. pub fn is_maximizable(&self) -> crate::Result<bool> {
  1213. self.window.dispatcher.is_maximizable().map_err(Into::into)
  1214. }
  1215. /// Gets the window’s native minimize button state
  1216. ///
  1217. /// ## Platform-specific
  1218. ///
  1219. /// - **Linux / iOS / Android:** Unsupported.
  1220. pub fn is_minimizable(&self) -> crate::Result<bool> {
  1221. self.window.dispatcher.is_minimizable().map_err(Into::into)
  1222. }
  1223. /// Gets the window’s native close button state
  1224. ///
  1225. /// ## Platform-specific
  1226. ///
  1227. /// - **Linux / iOS / Android:** Unsupported.
  1228. pub fn is_closable(&self) -> crate::Result<bool> {
  1229. self.window.dispatcher.is_closable().map_err(Into::into)
  1230. }
  1231. /// Gets the window's current visibility state.
  1232. pub fn is_visible(&self) -> crate::Result<bool> {
  1233. self.window.dispatcher.is_visible().map_err(Into::into)
  1234. }
  1235. /// Gets the window's current title.
  1236. pub fn title(&self) -> crate::Result<String> {
  1237. self.window.dispatcher.title().map_err(Into::into)
  1238. }
  1239. /// Returns the monitor on which the window currently resides.
  1240. ///
  1241. /// Returns None if current monitor can't be detected.
  1242. pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
  1243. self
  1244. .window
  1245. .dispatcher
  1246. .current_monitor()
  1247. .map(|m| m.map(Into::into))
  1248. .map_err(Into::into)
  1249. }
  1250. /// Returns the primary monitor of the system.
  1251. ///
  1252. /// Returns None if it can't identify any monitor as a primary one.
  1253. pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
  1254. self
  1255. .window
  1256. .dispatcher
  1257. .primary_monitor()
  1258. .map(|m| m.map(Into::into))
  1259. .map_err(Into::into)
  1260. }
  1261. /// Returns the list of all the monitors available on the system.
  1262. pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
  1263. self
  1264. .window
  1265. .dispatcher
  1266. .available_monitors()
  1267. .map(|m| m.into_iter().map(Into::into).collect())
  1268. .map_err(Into::into)
  1269. }
  1270. /// Returns the native handle that is used by this window.
  1271. #[cfg(target_os = "macos")]
  1272. pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> {
  1273. self
  1274. .window
  1275. .dispatcher
  1276. .raw_window_handle()
  1277. .map_err(Into::into)
  1278. .and_then(|handle| {
  1279. if let raw_window_handle::RawWindowHandle::AppKit(h) = handle {
  1280. Ok(h.ns_window)
  1281. } else {
  1282. Err(crate::Error::InvalidWindowHandle)
  1283. }
  1284. })
  1285. }
  1286. /// Returns the pointer to the content view of this window.
  1287. #[cfg(target_os = "macos")]
  1288. pub fn ns_view(&self) -> crate::Result<*mut std::ffi::c_void> {
  1289. self
  1290. .window
  1291. .dispatcher
  1292. .raw_window_handle()
  1293. .map_err(Into::into)
  1294. .and_then(|handle| {
  1295. if let raw_window_handle::RawWindowHandle::AppKit(h) = handle {
  1296. Ok(h.ns_view)
  1297. } else {
  1298. Err(crate::Error::InvalidWindowHandle)
  1299. }
  1300. })
  1301. }
  1302. /// Returns the native handle that is used by this window.
  1303. #[cfg(windows)]
  1304. pub fn hwnd(&self) -> crate::Result<HWND> {
  1305. self
  1306. .window
  1307. .dispatcher
  1308. .raw_window_handle()
  1309. .map_err(Into::into)
  1310. .and_then(|handle| {
  1311. if let raw_window_handle::RawWindowHandle::Win32(h) = handle {
  1312. Ok(HWND(h.hwnd as _))
  1313. } else {
  1314. Err(crate::Error::InvalidWindowHandle)
  1315. }
  1316. })
  1317. }
  1318. /// Returns the `ApplicationWindow` from gtk crate that is used by this window.
  1319. ///
  1320. /// Note that this type can only be used on the main thread.
  1321. #[cfg(any(
  1322. target_os = "linux",
  1323. target_os = "dragonfly",
  1324. target_os = "freebsd",
  1325. target_os = "netbsd",
  1326. target_os = "openbsd"
  1327. ))]
  1328. pub fn gtk_window(&self) -> crate::Result<gtk::ApplicationWindow> {
  1329. self.window.dispatcher.gtk_window().map_err(Into::into)
  1330. }
  1331. /// Returns the vertical [`gtk::Box`] that is added by default as the sole child of this window.
  1332. ///
  1333. /// Note that this type can only be used on the main thread.
  1334. #[cfg(any(
  1335. target_os = "linux",
  1336. target_os = "dragonfly",
  1337. target_os = "freebsd",
  1338. target_os = "netbsd",
  1339. target_os = "openbsd"
  1340. ))]
  1341. pub fn default_vbox(&self) -> crate::Result<gtk::Box> {
  1342. self.window.dispatcher.default_vbox().map_err(Into::into)
  1343. }
  1344. /// Returns the current window theme.
  1345. ///
  1346. /// ## Platform-specific
  1347. ///
  1348. /// - **macOS**: Only supported on macOS 10.14+.
  1349. pub fn theme(&self) -> crate::Result<Theme> {
  1350. self.window.dispatcher.theme().map_err(Into::into)
  1351. }
  1352. }
  1353. /// Desktop window setters and actions.
  1354. #[cfg(desktop)]
  1355. impl<R: Runtime> Window<R> {
  1356. /// Centers the window.
  1357. pub fn center(&self) -> crate::Result<()> {
  1358. self.window.dispatcher.center().map_err(Into::into)
  1359. }
  1360. /// Requests user attention to the window, this has no effect if the application
  1361. /// is already focused. How requesting for user attention manifests is platform dependent,
  1362. /// see `UserAttentionType` for details.
  1363. ///
  1364. /// Providing `None` will unset the request for user attention. Unsetting the request for
  1365. /// user attention might not be done automatically by the WM when the window receives input.
  1366. ///
  1367. /// ## Platform-specific
  1368. ///
  1369. /// - **macOS:** `None` has no effect.
  1370. /// - **Linux:** Urgency levels have the same effect.
  1371. pub fn request_user_attention(
  1372. &self,
  1373. request_type: Option<UserAttentionType>,
  1374. ) -> crate::Result<()> {
  1375. self
  1376. .window
  1377. .dispatcher
  1378. .request_user_attention(request_type)
  1379. .map_err(Into::into)
  1380. }
  1381. /// Determines if this window should be resizable.
  1382. /// When resizable is set to false, native window's maximize button is automatically disabled.
  1383. pub fn set_resizable(&self, resizable: bool) -> crate::Result<()> {
  1384. self
  1385. .window
  1386. .dispatcher
  1387. .set_resizable(resizable)
  1388. .map_err(Into::into)
  1389. }
  1390. /// Determines if this window's native maximize button should be enabled.
  1391. /// If resizable is set to false, this setting is ignored.
  1392. ///
  1393. /// ## Platform-specific
  1394. ///
  1395. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  1396. /// - **Linux / iOS / Android:** Unsupported.
  1397. pub fn set_maximizable(&self, maximizable: bool) -> crate::Result<()> {
  1398. self
  1399. .window
  1400. .dispatcher
  1401. .set_maximizable(maximizable)
  1402. .map_err(Into::into)
  1403. }
  1404. /// Determines if this window's native minize button should be enabled.
  1405. ///
  1406. /// ## Platform-specific
  1407. ///
  1408. /// - **Linux / iOS / Android:** Unsupported.
  1409. pub fn set_minimizable(&self, minimizable: bool) -> crate::Result<()> {
  1410. self
  1411. .window
  1412. .dispatcher
  1413. .set_minimizable(minimizable)
  1414. .map_err(Into::into)
  1415. }
  1416. /// Determines if this window's native close button should be enabled.
  1417. ///
  1418. /// ## Platform-specific
  1419. ///
  1420. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  1421. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  1422. /// - **iOS / Android:** Unsupported.
  1423. pub fn set_closable(&self, closable: bool) -> crate::Result<()> {
  1424. self
  1425. .window
  1426. .dispatcher
  1427. .set_closable(closable)
  1428. .map_err(Into::into)
  1429. }
  1430. /// Set this window's title.
  1431. pub fn set_title(&self, title: &str) -> crate::Result<()> {
  1432. self
  1433. .window
  1434. .dispatcher
  1435. .set_title(title.to_string())
  1436. .map_err(Into::into)
  1437. }
  1438. /// Maximizes this window.
  1439. pub fn maximize(&self) -> crate::Result<()> {
  1440. self.window.dispatcher.maximize().map_err(Into::into)
  1441. }
  1442. /// Un-maximizes this window.
  1443. pub fn unmaximize(&self) -> crate::Result<()> {
  1444. self.window.dispatcher.unmaximize().map_err(Into::into)
  1445. }
  1446. /// Minimizes this window.
  1447. pub fn minimize(&self) -> crate::Result<()> {
  1448. self.window.dispatcher.minimize().map_err(Into::into)
  1449. }
  1450. /// Un-minimizes this window.
  1451. pub fn unminimize(&self) -> crate::Result<()> {
  1452. self.window.dispatcher.unminimize().map_err(Into::into)
  1453. }
  1454. /// Show this window.
  1455. pub fn show(&self) -> crate::Result<()> {
  1456. self.window.dispatcher.show().map_err(Into::into)
  1457. }
  1458. /// Hide this window.
  1459. pub fn hide(&self) -> crate::Result<()> {
  1460. self.window.dispatcher.hide().map_err(Into::into)
  1461. }
  1462. /// Closes this window. It emits [`crate::RunEvent::CloseRequested`] first like a user-initiated close request so you can intercept it.
  1463. pub fn close(&self) -> crate::Result<()> {
  1464. self.window.dispatcher.close().map_err(Into::into)
  1465. }
  1466. /// Destroys this window. Similar to [`Self::close`] but does not emit any events and force close the window instead.
  1467. pub fn destroy(&self) -> crate::Result<()> {
  1468. self.window.dispatcher.destroy().map_err(Into::into)
  1469. }
  1470. /// Determines if this window should be [decorated].
  1471. ///
  1472. /// [decorated]: https://en.wikipedia.org/wiki/Window_(computing)#Window_decoration
  1473. pub fn set_decorations(&self, decorations: bool) -> crate::Result<()> {
  1474. self
  1475. .window
  1476. .dispatcher
  1477. .set_decorations(decorations)
  1478. .map_err(Into::into)
  1479. }
  1480. /// Determines if this window should have shadow.
  1481. ///
  1482. /// ## Platform-specific
  1483. ///
  1484. /// - **Windows:**
  1485. /// - `false` has no effect on decorated window, shadow are always ON.
  1486. /// - `true` will make ndecorated window have a 1px white border,
  1487. /// and on Windows 11, it will have a rounded corners.
  1488. /// - **Linux:** Unsupported.
  1489. pub fn set_shadow(&self, enable: bool) -> crate::Result<()> {
  1490. self
  1491. .window
  1492. .dispatcher
  1493. .set_shadow(enable)
  1494. .map_err(Into::into)
  1495. }
  1496. /// Sets window effects, pass [`None`] to clear any effects applied if possible.
  1497. ///
  1498. /// Requires the window to be transparent.
  1499. ///
  1500. /// See [`EffectsBuilder`] for a convenient builder for [`WindowEffectsConfig`].
  1501. ///
  1502. #[cfg_attr(
  1503. feature = "unstable",
  1504. doc = r####"
  1505. ```rust,no_run
  1506. use tauri::{Manager, window::{Color, Effect, EffectState, EffectsBuilder}};
  1507. tauri::Builder::default()
  1508. .setup(|app| {
  1509. let window = app.get_window("main").unwrap();
  1510. window.set_effects(
  1511. EffectsBuilder::new()
  1512. .effect(Effect::Popover)
  1513. .state(EffectState::Active)
  1514. .radius(5.)
  1515. .color(Color(0, 0, 0, 255))
  1516. .build(),
  1517. )?;
  1518. Ok(())
  1519. });
  1520. ```
  1521. "####
  1522. )]
  1523. ///
  1524. /// ## Platform-specific:
  1525. ///
  1526. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  1527. /// - **Linux**: Unsupported
  1528. pub fn set_effects<E: Into<Option<WindowEffectsConfig>>>(&self, effects: E) -> crate::Result<()> {
  1529. let effects = effects.into();
  1530. let window = self.clone();
  1531. self.run_on_main_thread(move || {
  1532. let _ = crate::vibrancy::set_window_effects(&window, effects);
  1533. })
  1534. }
  1535. /// Determines if this window should always be below other windows.
  1536. pub fn set_always_on_bottom(&self, always_on_bottom: bool) -> crate::Result<()> {
  1537. self
  1538. .window
  1539. .dispatcher
  1540. .set_always_on_bottom(always_on_bottom)
  1541. .map_err(Into::into)
  1542. }
  1543. /// Determines if this window should always be on top of other windows.
  1544. pub fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> {
  1545. self
  1546. .window
  1547. .dispatcher
  1548. .set_always_on_top(always_on_top)
  1549. .map_err(Into::into)
  1550. }
  1551. /// Sets whether the window should be visible on all workspaces or virtual desktops.
  1552. ///
  1553. /// ## Platform-specific
  1554. ///
  1555. /// - **Windows / iOS / Android:** Unsupported.
  1556. pub fn set_visible_on_all_workspaces(
  1557. &self,
  1558. visible_on_all_workspaces: bool,
  1559. ) -> crate::Result<()> {
  1560. self
  1561. .window
  1562. .dispatcher
  1563. .set_visible_on_all_workspaces(visible_on_all_workspaces)
  1564. .map_err(Into::into)
  1565. }
  1566. /// Prevents the window contents from being captured by other apps.
  1567. pub fn set_content_protected(&self, protected: bool) -> crate::Result<()> {
  1568. self
  1569. .window
  1570. .dispatcher
  1571. .set_content_protected(protected)
  1572. .map_err(Into::into)
  1573. }
  1574. /// Resizes this window.
  1575. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
  1576. self
  1577. .window
  1578. .dispatcher
  1579. .set_size(size.into())
  1580. .map_err(Into::into)
  1581. }
  1582. /// Sets this window's minimum size.
  1583. pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1584. self
  1585. .window
  1586. .dispatcher
  1587. .set_min_size(size.map(|s| s.into()))
  1588. .map_err(Into::into)
  1589. }
  1590. /// Sets this window's maximum size.
  1591. pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  1592. self
  1593. .window
  1594. .dispatcher
  1595. .set_max_size(size.map(|s| s.into()))
  1596. .map_err(Into::into)
  1597. }
  1598. /// Sets this window's position.
  1599. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1600. self
  1601. .window
  1602. .dispatcher
  1603. .set_position(position.into())
  1604. .map_err(Into::into)
  1605. }
  1606. /// Determines if this window should be fullscreen.
  1607. pub fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
  1608. self
  1609. .window
  1610. .dispatcher
  1611. .set_fullscreen(fullscreen)
  1612. .map_err(Into::into)
  1613. }
  1614. /// Bring the window to front and focus.
  1615. pub fn set_focus(&self) -> crate::Result<()> {
  1616. self.window.dispatcher.set_focus().map_err(Into::into)
  1617. }
  1618. /// Sets this window' icon.
  1619. pub fn set_icon(&self, icon: Icon) -> crate::Result<()> {
  1620. self
  1621. .window
  1622. .dispatcher
  1623. .set_icon(icon.try_into()?)
  1624. .map_err(Into::into)
  1625. }
  1626. /// Whether to hide the window icon from the taskbar or not.
  1627. ///
  1628. /// ## Platform-specific
  1629. ///
  1630. /// - **macOS:** Unsupported.
  1631. pub fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> {
  1632. self
  1633. .window
  1634. .dispatcher
  1635. .set_skip_taskbar(skip)
  1636. .map_err(Into::into)
  1637. }
  1638. /// Grabs the cursor, preventing it from leaving the window.
  1639. ///
  1640. /// There's no guarantee that the cursor will be hidden. You should
  1641. /// hide it by yourself if you want so.
  1642. ///
  1643. /// ## Platform-specific
  1644. ///
  1645. /// - **Linux:** Unsupported.
  1646. /// - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
  1647. pub fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
  1648. self
  1649. .window
  1650. .dispatcher
  1651. .set_cursor_grab(grab)
  1652. .map_err(Into::into)
  1653. }
  1654. /// Modifies the cursor's visibility.
  1655. ///
  1656. /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
  1657. ///
  1658. /// ## Platform-specific
  1659. ///
  1660. /// - **Windows:** The cursor is only hidden within the confines of the window.
  1661. /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
  1662. /// outside of the window.
  1663. pub fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
  1664. self
  1665. .window
  1666. .dispatcher
  1667. .set_cursor_visible(visible)
  1668. .map_err(Into::into)
  1669. }
  1670. /// Modifies the cursor icon of the window.
  1671. pub fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
  1672. self
  1673. .window
  1674. .dispatcher
  1675. .set_cursor_icon(icon)
  1676. .map_err(Into::into)
  1677. }
  1678. /// Changes the position of the cursor in window coordinates.
  1679. pub fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1680. self
  1681. .window
  1682. .dispatcher
  1683. .set_cursor_position(position)
  1684. .map_err(Into::into)
  1685. }
  1686. /// Ignores the window cursor events.
  1687. pub fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
  1688. self
  1689. .window
  1690. .dispatcher
  1691. .set_ignore_cursor_events(ignore)
  1692. .map_err(Into::into)
  1693. }
  1694. /// Starts dragging the window.
  1695. pub fn start_dragging(&self) -> crate::Result<()> {
  1696. self.window.dispatcher.start_dragging().map_err(Into::into)
  1697. }
  1698. /// Starts resize-dragging the window.
  1699. pub fn start_resize_dragging(
  1700. &self,
  1701. direction: tauri_runtime::ResizeDirection,
  1702. ) -> crate::Result<()> {
  1703. self
  1704. .window
  1705. .dispatcher
  1706. .start_resize_dragging(direction)
  1707. .map_err(Into::into)
  1708. }
  1709. /// Sets the taskbar progress state.
  1710. ///
  1711. /// ## Platform-specific
  1712. ///
  1713. /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window.
  1714. /// - **Linux**: Only supported desktop environments with `libunity` (e.g. GNOME).
  1715. /// - **iOS / Android:** Unsupported.
  1716. pub fn set_progress_bar(
  1717. &self,
  1718. progress_state: crate::utils::ProgressBarState,
  1719. ) -> crate::Result<()> {
  1720. self
  1721. .window
  1722. .dispatcher
  1723. .set_progress_bar(progress_state)
  1724. .map_err(Into::into)
  1725. }
  1726. }
  1727. /// Event system APIs.
  1728. impl<R: Runtime> Window<R> {
  1729. /// Listen to an event on this window.
  1730. ///
  1731. /// # Examples
  1732. #[cfg_attr(
  1733. feature = "unstable",
  1734. doc = r####"
  1735. ```
  1736. use tauri::Manager;
  1737. tauri::Builder::default()
  1738. .setup(|app| {
  1739. let window = app.get_window("main").unwrap();
  1740. window.listen("component-loaded", move |event| {
  1741. println!("window just loaded a component");
  1742. });
  1743. Ok(())
  1744. });
  1745. ```
  1746. "####
  1747. )]
  1748. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1749. where
  1750. F: Fn(Event) + Send + 'static,
  1751. {
  1752. self.manager.listen(
  1753. event.into(),
  1754. EventTarget::Window {
  1755. label: self.label().to_string(),
  1756. },
  1757. handler,
  1758. )
  1759. }
  1760. /// Unlisten to an event on this window.
  1761. ///
  1762. /// # Examples
  1763. #[cfg_attr(
  1764. feature = "unstable",
  1765. doc = r####"
  1766. ```
  1767. use tauri::Manager;
  1768. tauri::Builder::default()
  1769. .setup(|app| {
  1770. let window = app.get_window("main").unwrap();
  1771. let window_ = window.clone();
  1772. let handler = window.listen("component-loaded", move |event| {
  1773. println!("window just loaded a component");
  1774. // we no longer need to listen to the event
  1775. // we also could have used `window.once` instead
  1776. window_.unlisten(event.id());
  1777. });
  1778. // stop listening to the event when you do not need it anymore
  1779. window.unlisten(handler);
  1780. Ok(())
  1781. });
  1782. ```
  1783. "####
  1784. )]
  1785. pub fn unlisten(&self, id: EventId) {
  1786. self.manager.unlisten(id)
  1787. }
  1788. /// Listen to an event on this window only once.
  1789. ///
  1790. /// See [`Self::listen`] for more information.
  1791. pub fn once<F>(&self, event: impl Into<String>, handler: F)
  1792. where
  1793. F: FnOnce(Event) + Send + 'static,
  1794. {
  1795. self.manager.once(
  1796. event.into(),
  1797. EventTarget::Window {
  1798. label: self.label().to_string(),
  1799. },
  1800. handler,
  1801. )
  1802. }
  1803. }
  1804. /// The [`WindowEffectsConfig`] object builder
  1805. #[derive(Default)]
  1806. pub struct EffectsBuilder(WindowEffectsConfig);
  1807. impl EffectsBuilder {
  1808. /// Create a new [`WindowEffectsConfig`] builder
  1809. pub fn new() -> Self {
  1810. Self(WindowEffectsConfig::default())
  1811. }
  1812. /// Adds effect to the [`WindowEffectsConfig`] `effects` field
  1813. pub fn effect(mut self, effect: Effect) -> Self {
  1814. self.0.effects.push(effect);
  1815. self
  1816. }
  1817. /// Adds effects to the [`WindowEffectsConfig`] `effects` field
  1818. pub fn effects<I: IntoIterator<Item = Effect>>(mut self, effects: I) -> Self {
  1819. self.0.effects.extend(effects);
  1820. self
  1821. }
  1822. /// Clears the [`WindowEffectsConfig`] `effects` field
  1823. pub fn clear_effects(mut self) -> Self {
  1824. self.0.effects.clear();
  1825. self
  1826. }
  1827. /// Sets `state` field for the [`WindowEffectsConfig`] **macOS Only**
  1828. pub fn state(mut self, state: EffectState) -> Self {
  1829. self.0.state = Some(state);
  1830. self
  1831. }
  1832. /// Sets `radius` field fo the [`WindowEffectsConfig`] **macOS Only**
  1833. pub fn radius(mut self, radius: f64) -> Self {
  1834. self.0.radius = Some(radius);
  1835. self
  1836. }
  1837. /// Sets `color` field fo the [`WindowEffectsConfig`] **Windows Only**
  1838. pub fn color(mut self, color: Color) -> Self {
  1839. self.0.color = Some(color);
  1840. self
  1841. }
  1842. /// Builds a [`WindowEffectsConfig`]
  1843. pub fn build(self) -> WindowEffectsConfig {
  1844. self.0
  1845. }
  1846. }
  1847. impl From<WindowEffectsConfig> for EffectsBuilder {
  1848. fn from(value: WindowEffectsConfig) -> Self {
  1849. Self(value)
  1850. }
  1851. }
  1852. #[cfg(test)]
  1853. mod tests {
  1854. #[test]
  1855. fn window_is_send_sync() {
  1856. crate::test_utils::assert_send::<super::Window>();
  1857. crate::test_utils::assert_sync::<super::Window>();
  1858. }
  1859. }