window.rs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. // Copyright 2019-2021 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 menu;
  6. pub use menu::{MenuEvent, MenuHandle};
  7. use crate::{
  8. app::AppHandle,
  9. command::{CommandArg, CommandItem},
  10. event::{Event, EventHandler},
  11. hooks::{InvokePayload, InvokeResponder},
  12. manager::WindowManager,
  13. runtime::{
  14. http::{Request as HttpRequest, Response as HttpResponse},
  15. menu::Menu,
  16. monitor::Monitor as RuntimeMonitor,
  17. webview::{WebviewAttributes, WindowBuilder as _},
  18. window::{
  19. dpi::{PhysicalPosition, PhysicalSize, Position, Size},
  20. DetachedWindow, JsEventListenerKey, PendingWindow,
  21. },
  22. Dispatch, RuntimeHandle, UserAttentionType,
  23. },
  24. sealed::ManagerBase,
  25. sealed::RuntimeOrDispatch,
  26. utils::config::WindowUrl,
  27. CursorIcon, EventLoopMessage, Icon, Invoke, InvokeError, InvokeMessage, InvokeResolver, Manager,
  28. PageLoadPayload, Runtime, Theme, WindowEvent,
  29. };
  30. use serde::Serialize;
  31. #[cfg(windows)]
  32. use windows::Win32::Foundation::HWND;
  33. use tauri_macros::default_runtime;
  34. use std::{
  35. fmt,
  36. hash::{Hash, Hasher},
  37. path::PathBuf,
  38. sync::Arc,
  39. };
  40. #[derive(Clone, Serialize)]
  41. struct WindowCreatedEvent {
  42. label: String,
  43. }
  44. /// Monitor descriptor.
  45. #[derive(Debug, Clone, Serialize)]
  46. #[serde(rename_all = "camelCase")]
  47. pub struct Monitor {
  48. pub(crate) name: Option<String>,
  49. pub(crate) size: PhysicalSize<u32>,
  50. pub(crate) position: PhysicalPosition<i32>,
  51. pub(crate) scale_factor: f64,
  52. }
  53. impl From<RuntimeMonitor> for Monitor {
  54. fn from(monitor: RuntimeMonitor) -> Self {
  55. Self {
  56. name: monitor.name,
  57. size: monitor.size,
  58. position: monitor.position,
  59. scale_factor: monitor.scale_factor,
  60. }
  61. }
  62. }
  63. impl Monitor {
  64. /// Returns a human-readable name of the monitor.
  65. /// Returns None if the monitor doesn't exist anymore.
  66. pub fn name(&self) -> Option<&String> {
  67. self.name.as_ref()
  68. }
  69. /// Returns the monitor's resolution.
  70. pub fn size(&self) -> &PhysicalSize<u32> {
  71. &self.size
  72. }
  73. /// Returns the top-left corner position of the monitor relative to the larger full screen area.
  74. pub fn position(&self) -> &PhysicalPosition<i32> {
  75. &self.position
  76. }
  77. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  78. pub fn scale_factor(&self) -> f64 {
  79. self.scale_factor
  80. }
  81. }
  82. /// A builder for a webview window managed by Tauri.
  83. #[default_runtime(crate::Wry, wry)]
  84. pub struct WindowBuilder<'a, R: Runtime> {
  85. manager: WindowManager<R>,
  86. runtime: RuntimeOrDispatch<'a, R>,
  87. app_handle: AppHandle<R>,
  88. label: String,
  89. pub(crate) window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder,
  90. pub(crate) webview_attributes: WebviewAttributes,
  91. web_resource_request_handler: Option<Box<dyn Fn(&HttpRequest, &mut HttpResponse) + Send + Sync>>,
  92. }
  93. impl<'a, R: Runtime> fmt::Debug for WindowBuilder<'a, R> {
  94. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  95. f.debug_struct("WindowBuilder")
  96. .field("manager", &self.manager)
  97. .field("app_handle", &self.app_handle)
  98. .field("label", &self.label)
  99. .field("window_builder", &self.window_builder)
  100. .field("webview_attributes", &self.webview_attributes)
  101. .finish()
  102. }
  103. }
  104. impl<'a, R: Runtime> WindowBuilder<'a, R> {
  105. /// Initializes a webview window builder with the given window label and URL to load on the webview.
  106. ///
  107. /// # Examples
  108. ///
  109. /// - Create a window in the setup hook:
  110. ///
  111. /// ```
  112. /// tauri::Builder::default()
  113. /// .setup(|app| {
  114. /// let window = tauri::WindowBuilder::new(app, "label", tauri::WindowUrl::App("index.html".into()))
  115. /// .build()?;
  116. /// Ok(())
  117. /// });
  118. /// ```
  119. ///
  120. /// - Create a window in a separate thread:
  121. ///
  122. /// ```
  123. /// tauri::Builder::default()
  124. /// .setup(|app| {
  125. /// let handle = app.handle();
  126. /// std::thread::spawn(move || {
  127. /// let window = tauri::WindowBuilder::new(&handle, "label", tauri::WindowUrl::App("index.html".into()))
  128. /// .build()
  129. /// .unwrap();
  130. /// });
  131. /// Ok(())
  132. /// });
  133. /// ```
  134. ///
  135. /// - Create a window in a command:
  136. ///
  137. /// ```
  138. /// #[tauri::command]
  139. /// async fn create_window(app: tauri::AppHandle) {
  140. /// let window = tauri::WindowBuilder::new(&app, "label", tauri::WindowUrl::External("https://tauri.app/".parse().unwrap()))
  141. /// .build()
  142. /// .unwrap();
  143. /// }
  144. /// ```
  145. ///
  146. /// # Known issues
  147. ///
  148. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  149. /// You should use `async` commands when creating windows.
  150. ///
  151. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  152. pub fn new<M: Manager<R>, L: Into<String>>(manager: &'a M, label: L, url: WindowUrl) -> Self {
  153. let runtime = manager.runtime();
  154. let app_handle = manager.app_handle();
  155. Self {
  156. manager: manager.manager().clone(),
  157. runtime,
  158. app_handle,
  159. label: label.into(),
  160. window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder::new(),
  161. webview_attributes: WebviewAttributes::new(url),
  162. web_resource_request_handler: None,
  163. }
  164. }
  165. /// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
  166. ///
  167. /// Currently only implemented for the `tauri` URI protocol.
  168. ///
  169. /// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
  170. /// but it might be implemented in the future. **Always** check the request URL.
  171. ///
  172. /// # Examples
  173. ///
  174. /// ```rust,no_run
  175. /// use tauri::{
  176. /// utils::config::{Csp, CspDirectiveSources, WindowUrl},
  177. /// http::header::HeaderValue,
  178. /// window::WindowBuilder,
  179. /// };
  180. /// use std::collections::HashMap;
  181. /// tauri::Builder::default()
  182. /// .setup(|app| {
  183. /// WindowBuilder::new(app, "core", WindowUrl::App("index.html".into()))
  184. /// .on_web_resource_request(|request, response| {
  185. /// if request.uri().starts_with("tauri://") {
  186. /// // if we have a CSP header, Tauri is loading an HTML file
  187. /// // for this example, let's dynamically change the CSP
  188. /// if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
  189. /// // use the tauri helper to parse the CSP policy to a map
  190. /// let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
  191. /// csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
  192. /// // use the tauri helper to get a CSP string from the map
  193. /// let csp_string = Csp::from(csp_map).to_string();
  194. /// *csp = HeaderValue::from_str(&csp_string).unwrap();
  195. /// }
  196. /// }
  197. /// })
  198. /// .build()?;
  199. /// Ok(())
  200. /// });
  201. /// ```
  202. pub fn on_web_resource_request<F: Fn(&HttpRequest, &mut HttpResponse) + Send + Sync + 'static>(
  203. mut self,
  204. f: F,
  205. ) -> Self {
  206. self.web_resource_request_handler.replace(Box::new(f));
  207. self
  208. }
  209. /// Creates a new webview window.
  210. pub fn build(mut self) -> crate::Result<Window<R>> {
  211. let web_resource_request_handler = self.web_resource_request_handler.take();
  212. let pending = PendingWindow::new(
  213. self.window_builder.clone(),
  214. self.webview_attributes.clone(),
  215. self.label.clone(),
  216. )?;
  217. let labels = self.manager.labels().into_iter().collect::<Vec<_>>();
  218. let pending = self.manager.prepare_window(
  219. self.app_handle.clone(),
  220. pending,
  221. &labels,
  222. web_resource_request_handler,
  223. )?;
  224. let window = match &mut self.runtime {
  225. RuntimeOrDispatch::Runtime(runtime) => runtime.create_window(pending),
  226. RuntimeOrDispatch::RuntimeHandle(handle) => handle.create_window(pending),
  227. RuntimeOrDispatch::Dispatch(dispatcher) => dispatcher.create_window(pending),
  228. }
  229. .map(|window| self.manager.attach_window(self.app_handle.clone(), window))?;
  230. self.manager.emit_filter(
  231. "tauri://window-created",
  232. None,
  233. Some(WindowCreatedEvent {
  234. label: window.label().into(),
  235. }),
  236. |w| w != &window,
  237. )?;
  238. Ok(window)
  239. }
  240. // --------------------------------------------- Window builder ---------------------------------------------
  241. /// Sets the menu for the window.
  242. #[must_use]
  243. pub fn menu(mut self, menu: Menu) -> Self {
  244. self.window_builder = self.window_builder.menu(menu);
  245. self
  246. }
  247. /// Show window in the center of the screen.
  248. #[must_use]
  249. pub fn center(mut self) -> Self {
  250. self.window_builder = self.window_builder.center();
  251. self
  252. }
  253. /// The initial position of the window's.
  254. #[must_use]
  255. pub fn position(mut self, x: f64, y: f64) -> Self {
  256. self.window_builder = self.window_builder.position(x, y);
  257. self
  258. }
  259. /// Window size.
  260. #[must_use]
  261. pub fn inner_size(mut self, width: f64, height: f64) -> Self {
  262. self.window_builder = self.window_builder.inner_size(width, height);
  263. self
  264. }
  265. /// Window min inner size.
  266. #[must_use]
  267. pub fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
  268. self.window_builder = self.window_builder.min_inner_size(min_width, min_height);
  269. self
  270. }
  271. /// Window max inner size.
  272. #[must_use]
  273. pub fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
  274. self.window_builder = self.window_builder.max_inner_size(max_width, max_height);
  275. self
  276. }
  277. /// Whether the window is resizable or not.
  278. #[must_use]
  279. pub fn resizable(mut self, resizable: bool) -> Self {
  280. self.window_builder = self.window_builder.resizable(resizable);
  281. self
  282. }
  283. /// The title of the window in the title bar.
  284. #[must_use]
  285. pub fn title<S: Into<String>>(mut self, title: S) -> Self {
  286. self.window_builder = self.window_builder.title(title);
  287. self
  288. }
  289. /// Whether to start the window in fullscreen or not.
  290. #[must_use]
  291. pub fn fullscreen(mut self, fullscreen: bool) -> Self {
  292. self.window_builder = self.window_builder.fullscreen(fullscreen);
  293. self
  294. }
  295. /// Whether the window will be initially hidden or focused.
  296. #[must_use]
  297. pub fn focus(mut self) -> Self {
  298. self.window_builder = self.window_builder.focus();
  299. self
  300. }
  301. /// Whether the window should be maximized upon creation.
  302. #[must_use]
  303. pub fn maximized(mut self, maximized: bool) -> Self {
  304. self.window_builder = self.window_builder.maximized(maximized);
  305. self
  306. }
  307. /// Whether the window should be immediately visible upon creation.
  308. #[must_use]
  309. pub fn visible(mut self, visible: bool) -> Self {
  310. self.window_builder = self.window_builder.visible(visible);
  311. self
  312. }
  313. /// Forces a theme or uses the system settings if None was provided.
  314. ///
  315. /// ## Platform-specific
  316. ///
  317. /// - **macOS**: Only supported on macOS 10.14+.
  318. /// - **Linux**: Not implemented, the value is ignored.
  319. #[must_use]
  320. pub fn theme(mut self, theme: Option<Theme>) -> Self {
  321. self.window_builder = self.window_builder.theme(theme);
  322. self
  323. }
  324. /// Whether the the window should be transparent. If this is true, writing colors
  325. /// with alpha values different than `1.0` will produce a transparent window.
  326. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  327. #[cfg_attr(
  328. doc_cfg,
  329. doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
  330. )]
  331. #[must_use]
  332. pub fn transparent(mut self, transparent: bool) -> Self {
  333. self.window_builder = self.window_builder.transparent(transparent);
  334. self
  335. }
  336. /// Whether the window should have borders and bars.
  337. #[must_use]
  338. pub fn decorations(mut self, decorations: bool) -> Self {
  339. self.window_builder = self.window_builder.decorations(decorations);
  340. self
  341. }
  342. /// Whether the window should always be on top of other windows.
  343. #[must_use]
  344. pub fn always_on_top(mut self, always_on_top: bool) -> Self {
  345. self.window_builder = self.window_builder.always_on_top(always_on_top);
  346. self
  347. }
  348. /// Sets the window icon.
  349. pub fn icon(mut self, icon: Icon) -> crate::Result<Self> {
  350. self.window_builder = self.window_builder.icon(icon.try_into()?)?;
  351. Ok(self)
  352. }
  353. /// Sets whether or not the window icon should be added to the taskbar.
  354. #[must_use]
  355. pub fn skip_taskbar(mut self, skip: bool) -> Self {
  356. self.window_builder = self.window_builder.skip_taskbar(skip);
  357. self
  358. }
  359. /// Sets a parent to the window to be created.
  360. ///
  361. /// A child window has the WS_CHILD style and is confined to the client area of its parent window.
  362. ///
  363. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
  364. #[cfg(windows)]
  365. #[must_use]
  366. pub fn parent_window(mut self, parent: HWND) -> Self {
  367. self.window_builder = self.window_builder.parent_window(parent);
  368. self
  369. }
  370. /// Sets a parent to the window to be created.
  371. #[cfg(target_os = "macos")]
  372. #[must_use]
  373. pub fn parent_window(mut self, parent: *mut std::ffi::c_void) -> Self {
  374. self.window_builder = self.window_builder.parent_window(parent);
  375. self
  376. }
  377. /// Set an owner to the window to be created.
  378. ///
  379. /// From MSDN:
  380. /// - An owned window is always above its owner in the z-order.
  381. /// - The system automatically destroys an owned window when its owner is destroyed.
  382. /// - An owned window is hidden when its owner is minimized.
  383. ///
  384. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
  385. #[cfg(windows)]
  386. #[must_use]
  387. pub fn owner_window(mut self, owner: HWND) -> Self {
  388. self.window_builder = self.window_builder.owner_window(owner);
  389. self
  390. }
  391. // ------------------------------------------- Webview attributes -------------------------------------------
  392. /// Sets the init script.
  393. #[must_use]
  394. pub fn initialization_script(mut self, script: &str) -> Self {
  395. self
  396. .webview_attributes
  397. .initialization_scripts
  398. .push(script.to_string());
  399. self
  400. }
  401. /// Data directory for the webview.
  402. #[must_use]
  403. pub fn data_directory(mut self, data_directory: PathBuf) -> Self {
  404. self
  405. .webview_attributes
  406. .data_directory
  407. .replace(data_directory);
  408. self
  409. }
  410. /// Disables the file drop handler. This is required to use drag and drop APIs on the front end on Windows.
  411. #[must_use]
  412. pub fn disable_file_drop_handler(mut self) -> Self {
  413. self.webview_attributes.file_drop_handler_enabled = false;
  414. self
  415. }
  416. /// Enables clipboard access for the page rendered on **Linux** and **Windows**.
  417. ///
  418. /// **macOS** doesn't provide such method and is always enabled by default,
  419. /// but you still need to add menu item accelerators to use shortcuts.
  420. #[must_use]
  421. pub fn enable_clipboard_access(mut self) -> Self {
  422. self.webview_attributes.clipboard = true;
  423. self
  424. }
  425. }
  426. // TODO: expand these docs since this is a pretty important type
  427. /// A webview window managed by Tauri.
  428. ///
  429. /// This type also implements [`Manager`] which allows you to manage other windows attached to
  430. /// the same application.
  431. #[default_runtime(crate::Wry, wry)]
  432. #[derive(Debug)]
  433. pub struct Window<R: Runtime> {
  434. /// The webview window created by the runtime.
  435. window: DetachedWindow<EventLoopMessage, R>,
  436. /// The manager to associate this webview window with.
  437. manager: WindowManager<R>,
  438. pub(crate) app_handle: AppHandle<R>,
  439. }
  440. #[cfg(any(windows, target_os = "macos"))]
  441. #[cfg_attr(doc_cfg, doc(cfg(any(windows, target_os = "macos"))))]
  442. unsafe impl<R: Runtime> raw_window_handle::HasRawWindowHandle for Window<R> {
  443. #[cfg(windows)]
  444. fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle {
  445. let mut handle = raw_window_handle::Win32Handle::empty();
  446. handle.hwnd = self.hwnd().expect("failed to get window `hwnd`").0 as *mut _;
  447. raw_window_handle::RawWindowHandle::Win32(handle)
  448. }
  449. #[cfg(target_os = "macos")]
  450. fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle {
  451. let mut handle = raw_window_handle::AppKitHandle::empty();
  452. handle.ns_window = self
  453. .ns_window()
  454. .expect("failed to get window's `ns_window`");
  455. raw_window_handle::RawWindowHandle::AppKit(handle)
  456. }
  457. }
  458. impl<R: Runtime> Clone for Window<R> {
  459. fn clone(&self) -> Self {
  460. Self {
  461. window: self.window.clone(),
  462. manager: self.manager.clone(),
  463. app_handle: self.app_handle.clone(),
  464. }
  465. }
  466. }
  467. impl<R: Runtime> Hash for Window<R> {
  468. /// Only use the [`Window`]'s label to represent its hash.
  469. fn hash<H: Hasher>(&self, state: &mut H) {
  470. self.window.label.hash(state)
  471. }
  472. }
  473. impl<R: Runtime> Eq for Window<R> {}
  474. impl<R: Runtime> PartialEq for Window<R> {
  475. /// Only use the [`Window`]'s label to compare equality.
  476. fn eq(&self, other: &Self) -> bool {
  477. self.window.label.eq(&other.window.label)
  478. }
  479. }
  480. impl<R: Runtime> Manager<R> for Window<R> {}
  481. impl<R: Runtime> ManagerBase<R> for Window<R> {
  482. fn manager(&self) -> &WindowManager<R> {
  483. &self.manager
  484. }
  485. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  486. RuntimeOrDispatch::Dispatch(self.dispatcher())
  487. }
  488. fn managed_app_handle(&self) -> AppHandle<R> {
  489. self.app_handle.clone()
  490. }
  491. }
  492. impl<'de, R: Runtime> CommandArg<'de, R> for Window<R> {
  493. /// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
  494. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  495. Ok(command.message.window())
  496. }
  497. }
  498. /// The platform webview handle. Accessed with [`Window#method.with_webview`];
  499. #[cfg(feature = "wry")]
  500. #[cfg_attr(doc_cfg, doc(cfg(feature = "wry")))]
  501. pub struct PlatformWebview(tauri_runtime_wry::Webview);
  502. #[cfg(feature = "wry")]
  503. impl PlatformWebview {
  504. /// Returns [`webkit2gtk::WebView`] handle.
  505. #[cfg(any(
  506. target_os = "linux",
  507. target_os = "dragonfly",
  508. target_os = "freebsd",
  509. target_os = "netbsd",
  510. target_os = "openbsd"
  511. ))]
  512. #[cfg_attr(
  513. doc_cfg,
  514. doc(cfg(any(
  515. target_os = "linux",
  516. target_os = "dragonfly",
  517. target_os = "freebsd",
  518. target_os = "netbsd",
  519. target_os = "openbsd"
  520. )))
  521. )]
  522. pub fn inner(&self) -> std::rc::Rc<webkit2gtk::WebView> {
  523. self.0.clone()
  524. }
  525. /// Returns the WebView2 controller.
  526. #[cfg(windows)]
  527. #[cfg_attr(doc_cfg, doc(cfg(windows)))]
  528. pub fn controller(
  529. &self,
  530. ) -> webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller {
  531. self.0.controller.clone()
  532. }
  533. /// Returns the [WKWebView] handle.
  534. ///
  535. /// [WKWebView]: https://developer.apple.com/documentation/webkit/wkwebview
  536. #[cfg(target_os = "macos")]
  537. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  538. pub fn inner(&self) -> cocoa::base::id {
  539. self.0.webview
  540. }
  541. /// Returns WKWebView [controller] handle.
  542. ///
  543. /// [controller]: https://developer.apple.com/documentation/webkit/wkusercontentcontroller
  544. #[cfg(target_os = "macos")]
  545. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  546. pub fn controller(&self) -> cocoa::base::id {
  547. self.0.manager
  548. }
  549. /// Returns [NSWindow] associated with the WKWebView webview.
  550. ///
  551. /// [NSWindow]: https://developer.apple.com/documentation/appkit/nswindow
  552. #[cfg(target_os = "macos")]
  553. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  554. pub fn ns_window(&self) -> cocoa::base::id {
  555. self.0.ns_window
  556. }
  557. }
  558. /// APIs specific to the wry runtime.
  559. #[cfg(feature = "wry")]
  560. impl Window<crate::Wry> {
  561. /// Executes the closure accessing the platform's webview handle.
  562. ///
  563. /// The closure is executed in the main thread.
  564. ///
  565. /// # Examples
  566. ///
  567. /// ```rust,no_run
  568. /// #[cfg(target_os = "macos")]
  569. /// #[macro_use]
  570. /// extern crate objc;
  571. /// use tauri::Manager;
  572. ///
  573. /// fn main() {
  574. /// tauri::Builder::default()
  575. /// .setup(|app| {
  576. /// let main_window = app.get_window("main").unwrap();
  577. /// main_window.with_webview(|webview| {
  578. /// #[cfg(target_os = "linux")]
  579. /// {
  580. /// // see https://docs.rs/webkit2gtk/latest/webkit2gtk/struct.WebView.html
  581. /// // and https://docs.rs/webkit2gtk/latest/webkit2gtk/trait.WebViewExt.html
  582. /// use webkit2gtk::traits::WebViewExt;
  583. /// webview.inner().set_zoom_level(4.);
  584. /// }
  585. ///
  586. /// #[cfg(windows)]
  587. /// unsafe {
  588. /// // see https://docs.rs/webview2-com/latest/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html
  589. /// webview.controller().SetZoomFactor(4.).unwrap();
  590. /// }
  591. ///
  592. /// #[cfg(target_os = "macos")]
  593. /// unsafe {
  594. /// let () = msg_send![webview.inner(), setPageZoom: 4.];
  595. /// let () = msg_send![webview.controller(), removeAllUserScripts];
  596. /// let bg_color: cocoa::base::id = msg_send![class!(NSColor), colorWithDeviceRed:0.5 green:0.2 blue:0.4 alpha:1.];
  597. /// let () = msg_send![webview.ns_window(), setBackgroundColor: bg_color];
  598. /// }
  599. /// });
  600. /// Ok(())
  601. /// });
  602. /// }
  603. /// ```
  604. #[cfg_attr(doc_cfg, doc(cfg(eature = "wry")))]
  605. pub fn with_webview<F: FnOnce(PlatformWebview) + Send + 'static>(
  606. &self,
  607. f: F,
  608. ) -> crate::Result<()> {
  609. self
  610. .window
  611. .dispatcher
  612. .with_webview(|w| f(PlatformWebview(w)))
  613. .map_err(Into::into)
  614. }
  615. }
  616. /// Base window functions.
  617. impl<R: Runtime> Window<R> {
  618. /// Create a new window that is attached to the manager.
  619. pub(crate) fn new(
  620. manager: WindowManager<R>,
  621. window: DetachedWindow<EventLoopMessage, R>,
  622. app_handle: AppHandle<R>,
  623. ) -> Self {
  624. Self {
  625. window,
  626. manager,
  627. app_handle,
  628. }
  629. }
  630. /// Initializes a webview window builder with the given window label and URL to load on the webview.
  631. ///
  632. /// Data URLs are only supported with the `window-data-url` feature flag.
  633. pub fn builder<'a, M: Manager<R>, L: Into<String>>(
  634. manager: &'a M,
  635. label: L,
  636. url: WindowUrl,
  637. ) -> WindowBuilder<'a, R> {
  638. WindowBuilder::<'a, R>::new(manager, label.into(), url)
  639. }
  640. pub(crate) fn invoke_responder(&self) -> Arc<InvokeResponder<R>> {
  641. self.manager.invoke_responder()
  642. }
  643. /// The current window's dispatcher.
  644. pub(crate) fn dispatcher(&self) -> R::Dispatcher {
  645. self.window.dispatcher.clone()
  646. }
  647. /// Runs the given closure on the main thread.
  648. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  649. self
  650. .window
  651. .dispatcher
  652. .run_on_main_thread(f)
  653. .map_err(Into::into)
  654. }
  655. /// The label of this window.
  656. pub fn label(&self) -> &str {
  657. &self.window.label
  658. }
  659. /// Registers a window event listener.
  660. pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) {
  661. self
  662. .window
  663. .dispatcher
  664. .on_window_event(move |event| f(&event.clone().into()));
  665. }
  666. /// Registers a menu event listener.
  667. pub fn on_menu_event<F: Fn(MenuEvent) + Send + 'static>(&self, f: F) -> uuid::Uuid {
  668. let menu_ids = self.window.menu_ids.clone();
  669. self.window.dispatcher.on_menu_event(move |event| {
  670. f(MenuEvent {
  671. menu_item_id: menu_ids
  672. .lock()
  673. .unwrap()
  674. .get(&event.menu_item_id)
  675. .unwrap()
  676. .clone(),
  677. })
  678. })
  679. }
  680. }
  681. /// Window getters.
  682. impl<R: Runtime> Window<R> {
  683. /// Gets a handle to the window menu.
  684. pub fn menu_handle(&self) -> MenuHandle<R> {
  685. MenuHandle {
  686. ids: self.window.menu_ids.clone(),
  687. dispatcher: self.dispatcher(),
  688. }
  689. }
  690. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  691. pub fn scale_factor(&self) -> crate::Result<f64> {
  692. self.window.dispatcher.scale_factor().map_err(Into::into)
  693. }
  694. /// 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.
  695. pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  696. self.window.dispatcher.inner_position().map_err(Into::into)
  697. }
  698. /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
  699. pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> {
  700. self.window.dispatcher.outer_position().map_err(Into::into)
  701. }
  702. /// Returns the physical size of the window's client area.
  703. ///
  704. /// The client area is the content of the window, excluding the title bar and borders.
  705. pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> {
  706. self.window.dispatcher.inner_size().map_err(Into::into)
  707. }
  708. /// Returns the physical size of the entire window.
  709. ///
  710. /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
  711. pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> {
  712. self.window.dispatcher.outer_size().map_err(Into::into)
  713. }
  714. /// Gets the window's current fullscreen state.
  715. pub fn is_fullscreen(&self) -> crate::Result<bool> {
  716. self.window.dispatcher.is_fullscreen().map_err(Into::into)
  717. }
  718. /// Gets the window's current maximized state.
  719. pub fn is_maximized(&self) -> crate::Result<bool> {
  720. self.window.dispatcher.is_maximized().map_err(Into::into)
  721. }
  722. /// Gets the window’s current decoration state.
  723. pub fn is_decorated(&self) -> crate::Result<bool> {
  724. self.window.dispatcher.is_decorated().map_err(Into::into)
  725. }
  726. /// Gets the window’s current resizable state.
  727. pub fn is_resizable(&self) -> crate::Result<bool> {
  728. self.window.dispatcher.is_resizable().map_err(Into::into)
  729. }
  730. /// Gets the window's current vibility state.
  731. pub fn is_visible(&self) -> crate::Result<bool> {
  732. self.window.dispatcher.is_visible().map_err(Into::into)
  733. }
  734. /// Returns the monitor on which the window currently resides.
  735. ///
  736. /// Returns None if current monitor can't be detected.
  737. pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
  738. self
  739. .window
  740. .dispatcher
  741. .current_monitor()
  742. .map(|m| m.map(Into::into))
  743. .map_err(Into::into)
  744. }
  745. /// Returns the primary monitor of the system.
  746. ///
  747. /// Returns None if it can't identify any monitor as a primary one.
  748. pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
  749. self
  750. .window
  751. .dispatcher
  752. .primary_monitor()
  753. .map(|m| m.map(Into::into))
  754. .map_err(Into::into)
  755. }
  756. /// Returns the list of all the monitors available on the system.
  757. pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
  758. self
  759. .window
  760. .dispatcher
  761. .available_monitors()
  762. .map(|m| m.into_iter().map(Into::into).collect())
  763. .map_err(Into::into)
  764. }
  765. /// Returns the native handle that is used by this window.
  766. #[cfg(target_os = "macos")]
  767. pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> {
  768. self.window.dispatcher.ns_window().map_err(Into::into)
  769. }
  770. /// Returns the native handle that is used by this window.
  771. #[cfg(windows)]
  772. pub fn hwnd(&self) -> crate::Result<HWND> {
  773. self.window.dispatcher.hwnd().map_err(Into::into)
  774. }
  775. /// Returns the `ApplicatonWindow` from gtk crate that is used by this window.
  776. ///
  777. /// Note that this can only be used on the main thread.
  778. #[cfg(any(
  779. target_os = "linux",
  780. target_os = "dragonfly",
  781. target_os = "freebsd",
  782. target_os = "netbsd",
  783. target_os = "openbsd"
  784. ))]
  785. pub fn gtk_window(&self) -> crate::Result<gtk::ApplicationWindow> {
  786. self.window.dispatcher.gtk_window().map_err(Into::into)
  787. }
  788. /// Returns the current window theme.
  789. ///
  790. /// ## Platform-specific
  791. ///
  792. /// - **macOS**: Only supported on macOS 10.14+.
  793. /// - **Linux**: Not implemented, always return [`Theme::Light`].
  794. pub fn theme(&self) -> crate::Result<Theme> {
  795. self.window.dispatcher.theme().map_err(Into::into)
  796. }
  797. }
  798. /// Window setters and actions.
  799. impl<R: Runtime> Window<R> {
  800. /// Centers the window.
  801. pub fn center(&self) -> crate::Result<()> {
  802. self.window.dispatcher.center().map_err(Into::into)
  803. }
  804. /// Requests user attention to the window, this has no effect if the application
  805. /// is already focused. How requesting for user attention manifests is platform dependent,
  806. /// see `UserAttentionType` for details.
  807. ///
  808. /// Providing `None` will unset the request for user attention. Unsetting the request for
  809. /// user attention might not be done automatically by the WM when the window receives input.
  810. ///
  811. /// ## Platform-specific
  812. ///
  813. /// - **macOS:** `None` has no effect.
  814. /// - **Linux:** Urgency levels have the same effect.
  815. pub fn request_user_attention(
  816. &self,
  817. request_type: Option<UserAttentionType>,
  818. ) -> crate::Result<()> {
  819. self
  820. .window
  821. .dispatcher
  822. .request_user_attention(request_type)
  823. .map_err(Into::into)
  824. }
  825. /// Opens the dialog to prints the contents of the webview.
  826. /// Currently only supported on macOS on `wry`.
  827. /// `window.print()` works on all platforms.
  828. pub fn print(&self) -> crate::Result<()> {
  829. self.window.dispatcher.print().map_err(Into::into)
  830. }
  831. /// Determines if this window should be resizable.
  832. pub fn set_resizable(&self, resizable: bool) -> crate::Result<()> {
  833. self
  834. .window
  835. .dispatcher
  836. .set_resizable(resizable)
  837. .map_err(Into::into)
  838. }
  839. /// Set this window's title.
  840. pub fn set_title(&self, title: &str) -> crate::Result<()> {
  841. self
  842. .window
  843. .dispatcher
  844. .set_title(title.to_string())
  845. .map_err(Into::into)
  846. }
  847. /// Maximizes this window.
  848. pub fn maximize(&self) -> crate::Result<()> {
  849. self.window.dispatcher.maximize().map_err(Into::into)
  850. }
  851. /// Un-maximizes this window.
  852. pub fn unmaximize(&self) -> crate::Result<()> {
  853. self.window.dispatcher.unmaximize().map_err(Into::into)
  854. }
  855. /// Minimizes this window.
  856. pub fn minimize(&self) -> crate::Result<()> {
  857. self.window.dispatcher.minimize().map_err(Into::into)
  858. }
  859. /// Un-minimizes this window.
  860. pub fn unminimize(&self) -> crate::Result<()> {
  861. self.window.dispatcher.unminimize().map_err(Into::into)
  862. }
  863. /// Show this window.
  864. pub fn show(&self) -> crate::Result<()> {
  865. self.window.dispatcher.show().map_err(Into::into)
  866. }
  867. /// Hide this window.
  868. pub fn hide(&self) -> crate::Result<()> {
  869. self.window.dispatcher.hide().map_err(Into::into)
  870. }
  871. /// Closes this window.
  872. /// # Panics
  873. ///
  874. /// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
  875. /// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
  876. ///
  877. /// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
  878. pub fn close(&self) -> crate::Result<()> {
  879. self.window.dispatcher.close().map_err(Into::into)
  880. }
  881. /// Determines if this window should be [decorated].
  882. ///
  883. /// [decorated]: https://en.wikipedia.org/wiki/Window_(computing)#Window_decoration
  884. pub fn set_decorations(&self, decorations: bool) -> crate::Result<()> {
  885. self
  886. .window
  887. .dispatcher
  888. .set_decorations(decorations)
  889. .map_err(Into::into)
  890. }
  891. /// Determines if this window should always be on top of other windows.
  892. pub fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> {
  893. self
  894. .window
  895. .dispatcher
  896. .set_always_on_top(always_on_top)
  897. .map_err(Into::into)
  898. }
  899. /// Resizes this window.
  900. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
  901. self
  902. .window
  903. .dispatcher
  904. .set_size(size.into())
  905. .map_err(Into::into)
  906. }
  907. /// Sets this window's minimum size.
  908. pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  909. self
  910. .window
  911. .dispatcher
  912. .set_min_size(size.map(|s| s.into()))
  913. .map_err(Into::into)
  914. }
  915. /// Sets this window's maximum size.
  916. pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
  917. self
  918. .window
  919. .dispatcher
  920. .set_max_size(size.map(|s| s.into()))
  921. .map_err(Into::into)
  922. }
  923. /// Sets this window's position.
  924. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  925. self
  926. .window
  927. .dispatcher
  928. .set_position(position.into())
  929. .map_err(Into::into)
  930. }
  931. /// Determines if this window should be fullscreen.
  932. pub fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
  933. self
  934. .window
  935. .dispatcher
  936. .set_fullscreen(fullscreen)
  937. .map_err(Into::into)
  938. }
  939. /// Bring the window to front and focus.
  940. pub fn set_focus(&self) -> crate::Result<()> {
  941. self.window.dispatcher.set_focus().map_err(Into::into)
  942. }
  943. /// Sets this window' icon.
  944. pub fn set_icon(&self, icon: Icon) -> crate::Result<()> {
  945. self
  946. .window
  947. .dispatcher
  948. .set_icon(icon.try_into()?)
  949. .map_err(Into::into)
  950. }
  951. /// Whether to show the window icon in the task bar or not.
  952. pub fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> {
  953. self
  954. .window
  955. .dispatcher
  956. .set_skip_taskbar(skip)
  957. .map_err(Into::into)
  958. }
  959. /// Grabs the cursor, preventing it from leaving the window.
  960. ///
  961. /// There's no guarantee that the cursor will be hidden. You should
  962. /// hide it by yourself if you want so.
  963. ///
  964. /// ## Platform-specific
  965. ///
  966. /// - **Linux:** Unsupported.
  967. /// - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
  968. pub fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
  969. self
  970. .window
  971. .dispatcher
  972. .set_cursor_grab(grab)
  973. .map_err(Into::into)
  974. }
  975. /// Modifies the cursor's visibility.
  976. ///
  977. /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
  978. ///
  979. /// ## Platform-specific
  980. ///
  981. /// - **Windows:** The cursor is only hidden within the confines of the window.
  982. /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
  983. /// outside of the window.
  984. pub fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
  985. self
  986. .window
  987. .dispatcher
  988. .set_cursor_visible(visible)
  989. .map_err(Into::into)
  990. }
  991. /// Modifies the cursor icon of the window.
  992. pub fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
  993. self
  994. .window
  995. .dispatcher
  996. .set_cursor_icon(icon)
  997. .map_err(Into::into)
  998. }
  999. /// Changes the position of the cursor in window coordinates.
  1000. pub fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1001. self
  1002. .window
  1003. .dispatcher
  1004. .set_cursor_position(position)
  1005. .map_err(Into::into)
  1006. }
  1007. /// Starts dragging the window.
  1008. pub fn start_dragging(&self) -> crate::Result<()> {
  1009. self.window.dispatcher.start_dragging().map_err(Into::into)
  1010. }
  1011. }
  1012. /// Webview APIs.
  1013. impl<R: Runtime> Window<R> {
  1014. /// Handles this window receiving an [`InvokeMessage`].
  1015. pub fn on_message(self, payload: InvokePayload) -> crate::Result<()> {
  1016. let manager = self.manager.clone();
  1017. match payload.cmd.as_str() {
  1018. "__initialized" => {
  1019. let payload: PageLoadPayload = serde_json::from_value(payload.inner)?;
  1020. manager.run_on_page_load(self, payload);
  1021. }
  1022. _ => {
  1023. let message = InvokeMessage::new(
  1024. self.clone(),
  1025. manager.state(),
  1026. payload.cmd.to_string(),
  1027. payload.inner,
  1028. );
  1029. let resolver = InvokeResolver::new(self, payload.callback, payload.error);
  1030. let invoke = Invoke { message, resolver };
  1031. if let Some(module) = &payload.tauri_module {
  1032. crate::endpoints::handle(
  1033. module.to_string(),
  1034. invoke,
  1035. manager.config(),
  1036. manager.package_info(),
  1037. );
  1038. } else if payload.cmd.starts_with("plugin:") {
  1039. manager.extend_api(invoke);
  1040. } else {
  1041. manager.run_invoke_handler(invoke);
  1042. }
  1043. }
  1044. }
  1045. Ok(())
  1046. }
  1047. /// Evaluates JavaScript on this window.
  1048. pub fn eval(&self, js: &str) -> crate::Result<()> {
  1049. self.window.dispatcher.eval_script(js).map_err(Into::into)
  1050. }
  1051. pub(crate) fn register_js_listener(&self, window_label: Option<String>, event: String, id: u64) {
  1052. self
  1053. .window
  1054. .js_event_listeners
  1055. .lock()
  1056. .unwrap()
  1057. .entry(JsEventListenerKey {
  1058. window_label,
  1059. event,
  1060. })
  1061. .or_insert_with(Default::default)
  1062. .insert(id);
  1063. }
  1064. pub(crate) fn unregister_js_listener(&self, id: u64) {
  1065. let mut empty = None;
  1066. let mut js_listeners = self.window.js_event_listeners.lock().unwrap();
  1067. let iter = js_listeners.iter_mut();
  1068. for (key, ids) in iter {
  1069. if ids.contains(&id) {
  1070. ids.remove(&id);
  1071. if ids.is_empty() {
  1072. empty.replace(key.clone());
  1073. }
  1074. break;
  1075. }
  1076. }
  1077. if let Some(key) = empty {
  1078. js_listeners.remove(&key);
  1079. }
  1080. }
  1081. /// Whether this window registered a listener to an event from the given window and event name.
  1082. pub(crate) fn has_js_listener(&self, window_label: Option<String>, event: &str) -> bool {
  1083. self
  1084. .window
  1085. .js_event_listeners
  1086. .lock()
  1087. .unwrap()
  1088. .contains_key(&JsEventListenerKey {
  1089. window_label,
  1090. event: event.into(),
  1091. })
  1092. }
  1093. /// Opens the developer tools window (Web Inspector).
  1094. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1095. ///
  1096. /// ## Platform-specific
  1097. ///
  1098. /// - **macOS:** This is a private API on macOS,
  1099. /// so you cannot use this if your application will be published on the App Store.
  1100. ///
  1101. /// # Examples
  1102. ///
  1103. /// ```rust,no_run
  1104. /// use tauri::Manager;
  1105. /// tauri::Builder::default()
  1106. /// .setup(|app| {
  1107. /// #[cfg(debug_assertions)]
  1108. /// app.get_window("main").unwrap().open_devtools();
  1109. /// Ok(())
  1110. /// });
  1111. /// ```
  1112. #[cfg(any(debug_assertions, feature = "devtools"))]
  1113. #[cfg_attr(doc_cfg, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1114. pub fn open_devtools(&self) {
  1115. self.window.dispatcher.open_devtools();
  1116. }
  1117. /// Closes the developer tools window (Web Inspector).
  1118. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1119. ///
  1120. /// ## Platform-specific
  1121. ///
  1122. /// - **macOS:** This is a private API on macOS,
  1123. /// so you cannot use this if your application will be published on the App Store.
  1124. /// - **Windows:** Unsupported.
  1125. ///
  1126. /// # Examples
  1127. ///
  1128. /// ```rust,no_run
  1129. /// use tauri::Manager;
  1130. /// tauri::Builder::default()
  1131. /// .setup(|app| {
  1132. /// #[cfg(debug_assertions)]
  1133. /// {
  1134. /// let window = app.get_window("main").unwrap();
  1135. /// window.open_devtools();
  1136. /// std::thread::spawn(move || {
  1137. /// std::thread::sleep(std::time::Duration::from_secs(10));
  1138. /// window.close_devtools();
  1139. /// });
  1140. /// }
  1141. /// Ok(())
  1142. /// });
  1143. /// ```
  1144. #[cfg(any(debug_assertions, feature = "devtools"))]
  1145. #[cfg_attr(doc_cfg, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1146. pub fn close_devtools(&self) {
  1147. self.window.dispatcher.close_devtools();
  1148. }
  1149. /// Checks if the developer tools window (Web Inspector) is opened.
  1150. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1151. ///
  1152. /// ## Platform-specific
  1153. ///
  1154. /// - **macOS:** This is a private API on macOS,
  1155. /// so you cannot use this if your application will be published on the App Store.
  1156. /// - **Windows:** Unsupported.
  1157. ///
  1158. /// # Examples
  1159. ///
  1160. /// ```rust,no_run
  1161. /// use tauri::Manager;
  1162. /// tauri::Builder::default()
  1163. /// .setup(|app| {
  1164. /// #[cfg(debug_assertions)]
  1165. /// {
  1166. /// let window = app.get_window("main").unwrap();
  1167. /// if !window.is_devtools_open() {
  1168. /// window.open_devtools();
  1169. /// }
  1170. /// }
  1171. /// Ok(())
  1172. /// });
  1173. /// ```
  1174. #[cfg(any(debug_assertions, feature = "devtools"))]
  1175. #[cfg_attr(doc_cfg, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1176. pub fn is_devtools_open(&self) -> bool {
  1177. self
  1178. .window
  1179. .dispatcher
  1180. .is_devtools_open()
  1181. .unwrap_or_default()
  1182. }
  1183. }
  1184. /// Event system APIs.
  1185. impl<R: Runtime> Window<R> {
  1186. /// Emits an event to both the JavaScript and the Rust listeners.
  1187. pub fn emit_and_trigger<S: Serialize + Clone>(
  1188. &self,
  1189. event: &str,
  1190. payload: S,
  1191. ) -> crate::Result<()> {
  1192. self.trigger(event, Some(serde_json::to_string(&payload)?));
  1193. self.emit(event, payload)
  1194. }
  1195. pub(crate) fn emit_internal<S: Serialize>(
  1196. &self,
  1197. event: &str,
  1198. source_window_label: Option<&str>,
  1199. payload: S,
  1200. ) -> crate::Result<()> {
  1201. self.eval(&format!(
  1202. "window['{}']({{event: {}, windowLabel: {}, payload: {}}})",
  1203. self.manager.event_emit_function_name(),
  1204. serde_json::to_string(event)?,
  1205. serde_json::to_string(&source_window_label)?,
  1206. serde_json::to_value(payload)?,
  1207. ))?;
  1208. Ok(())
  1209. }
  1210. /// Emits an event to the JavaScript listeners on the current window.
  1211. ///
  1212. /// The event is only delivered to listeners that used the `WebviewWindow#listen` method on the @tauri-apps/api `window` module.
  1213. pub fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> crate::Result<()> {
  1214. self
  1215. .manager
  1216. .emit_filter(event, Some(self.label()), payload, |w| {
  1217. w.has_js_listener(None, event) || w.has_js_listener(Some(self.label().into()), event)
  1218. })?;
  1219. Ok(())
  1220. }
  1221. /// Listen to an event on this window.
  1222. ///
  1223. /// This listener only receives events that are triggered using the
  1224. /// [`trigger`](Window#method.trigger) and [`emit_and_trigger`](Window#method.emit_and_trigger) methods or
  1225. /// the `appWindow.emit` function from the @tauri-apps/api `window` module.
  1226. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
  1227. where
  1228. F: Fn(Event) + Send + 'static,
  1229. {
  1230. let label = self.window.label.clone();
  1231. self.manager.listen(event.into(), Some(label), handler)
  1232. }
  1233. /// Unlisten to an event on this window.
  1234. pub fn unlisten(&self, handler_id: EventHandler) {
  1235. self.manager.unlisten(handler_id)
  1236. }
  1237. /// Listen to an event on this window a single time.
  1238. pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
  1239. where
  1240. F: FnOnce(Event) + Send + 'static,
  1241. {
  1242. let label = self.window.label.clone();
  1243. self.manager.once(event.into(), Some(label), handler)
  1244. }
  1245. /// Triggers an event to the Rust listeners on this window.
  1246. ///
  1247. /// The event is only delivered to listeners that used the [`listen`](Window#method.listen) method.
  1248. pub fn trigger(&self, event: &str, data: Option<String>) {
  1249. let label = self.window.label.clone();
  1250. self.manager.trigger(event, Some(label), data)
  1251. }
  1252. }
  1253. #[cfg(test)]
  1254. mod tests {
  1255. #[test]
  1256. fn window_is_send_sync() {
  1257. crate::test_utils::assert_send::<super::Window>();
  1258. crate::test_utils::assert_sync::<super::Window>();
  1259. }
  1260. }