mod.rs 61 KB

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