manager.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use crate::{
  5. api::{
  6. assets::Assets,
  7. config::{Config, WindowUrl},
  8. path::{resolve_path, BaseDirectory},
  9. PackageInfo,
  10. },
  11. app::{GlobalWindowEvent, GlobalWindowEventListener},
  12. event::{Event, EventHandler, Listeners},
  13. hooks::{InvokeHandler, OnPageLoad, PageLoadPayload},
  14. plugin::PluginStore,
  15. runtime::{
  16. private::ParamsBase,
  17. tag::{tags_to_javascript_array, Tag, TagRef, ToJsString},
  18. webview::{
  19. CustomProtocol, FileDropEvent, FileDropHandler, InvokePayload, WebviewRpcHandler,
  20. WindowBuilder,
  21. },
  22. window::{dpi::PhysicalSize, DetachedWindow, PendingWindow, WindowEvent},
  23. Icon, MenuId, Params, Runtime,
  24. },
  25. App, Context, Invoke, StateManager, Window,
  26. };
  27. #[cfg(feature = "menu")]
  28. use crate::app::{GlobalMenuEventListener, WindowMenuEvent};
  29. #[cfg(feature = "menu")]
  30. use crate::{
  31. runtime::menu::{Menu, MenuItem},
  32. MenuEvent,
  33. };
  34. use serde::Serialize;
  35. use serde_json::Value as JsonValue;
  36. use std::borrow::Borrow;
  37. use std::marker::PhantomData;
  38. use std::{
  39. borrow::Cow,
  40. collections::{HashMap, HashSet},
  41. fs::create_dir_all,
  42. sync::{Arc, Mutex, MutexGuard},
  43. };
  44. use uuid::Uuid;
  45. const WINDOW_RESIZED_EVENT: &str = "tauri://resize";
  46. const WINDOW_MOVED_EVENT: &str = "tauri://move";
  47. const WINDOW_CLOSE_REQUESTED_EVENT: &str = "tauri://close-requested";
  48. const WINDOW_DESTROYED_EVENT: &str = "tauri://destroyed";
  49. const WINDOW_FOCUS_EVENT: &str = "tauri://focus";
  50. const WINDOW_BLUR_EVENT: &str = "tauri://blur";
  51. const WINDOW_SCALE_FACTOR_CHANGED_EVENT: &str = "tauri://scale-change";
  52. #[cfg(feature = "menu")]
  53. const MENU_EVENT: &str = "tauri://menu";
  54. /// Parse a string representing an internal tauri event into [`Params::Event`]
  55. ///
  56. /// # Panics
  57. ///
  58. /// This will panic if the `FromStr` implementation of [`Params::Event`] returns an error.
  59. pub(crate) fn tauri_event<Event: Tag>(tauri_event: &str) -> Event {
  60. tauri_event.parse().unwrap_or_else(|_| {
  61. panic!(
  62. "failed to parse internal tauri event into Params::Event: {}",
  63. tauri_event
  64. )
  65. })
  66. }
  67. pub struct InnerWindowManager<P: Params = DefaultArgs> {
  68. windows: Mutex<HashMap<P::Label, Window<P>>>,
  69. plugins: Mutex<PluginStore<P>>,
  70. listeners: Listeners<P::Event, P::Label>,
  71. pub(crate) state: Arc<StateManager>,
  72. /// The JS message handler.
  73. invoke_handler: Box<InvokeHandler<P>>,
  74. /// The page load hook, invoked when the webview performs a navigation.
  75. on_page_load: Box<OnPageLoad<P>>,
  76. config: Arc<Config>,
  77. assets: Arc<P::Assets>,
  78. default_window_icon: Option<Vec<u8>>,
  79. /// A list of salts that are valid for the current application.
  80. salts: Mutex<HashSet<Uuid>>,
  81. package_info: PackageInfo,
  82. /// The webview protocols protocols available to all windows.
  83. uri_scheme_protocols: HashMap<String, Arc<CustomProtocol>>,
  84. /// The menu set to all windows.
  85. #[cfg(feature = "menu")]
  86. menu: Vec<Menu<P::MenuId>>,
  87. /// Maps runtime id to a strongly typed menu id.
  88. #[cfg(feature = "menu")]
  89. menu_ids: HashMap<u32, P::MenuId>,
  90. /// Menu event listeners to all windows.
  91. #[cfg(feature = "menu")]
  92. menu_event_listeners: Arc<Vec<GlobalMenuEventListener<P>>>,
  93. /// Window event listeners to all windows.
  94. window_event_listeners: Arc<Vec<GlobalWindowEventListener<P>>>,
  95. }
  96. /// This type should always match `Builder::default()`, otherwise the default type is useless.
  97. pub(crate) type DefaultArgs =
  98. Args<String, String, String, String, crate::api::assets::EmbeddedAssets, crate::Wry>;
  99. /// A [Zero Sized Type] marker representing a full [`Params`].
  100. ///
  101. /// [Zero Sized Type]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
  102. pub struct Args<E: Tag, L: Tag, MID: MenuId, TID: MenuId, A: Assets, R: Runtime> {
  103. _event: PhantomData<fn() -> E>,
  104. _label: PhantomData<fn() -> L>,
  105. _menu_id: PhantomData<fn() -> MID>,
  106. _tray_menu_id: PhantomData<fn() -> TID>,
  107. _assets: PhantomData<fn() -> A>,
  108. _runtime: PhantomData<fn() -> R>,
  109. }
  110. impl<E: Tag, L: Tag, MID: MenuId, TID: MenuId, A: Assets, R: Runtime> Default
  111. for Args<E, L, MID, TID, A, R>
  112. {
  113. fn default() -> Self {
  114. Self {
  115. _event: PhantomData,
  116. _label: PhantomData,
  117. _menu_id: PhantomData,
  118. _tray_menu_id: PhantomData,
  119. _assets: PhantomData,
  120. _runtime: PhantomData,
  121. }
  122. }
  123. }
  124. impl<E: Tag, L: Tag, MID: MenuId, TID: MenuId, A: Assets, R: Runtime> ParamsBase
  125. for Args<E, L, MID, TID, A, R>
  126. {
  127. }
  128. impl<E: Tag, L: Tag, MID: MenuId, TID: MenuId, A: Assets, R: Runtime> Params
  129. for Args<E, L, MID, TID, A, R>
  130. {
  131. type Event = E;
  132. type Label = L;
  133. type MenuId = MID;
  134. type SystemTrayMenuId = TID;
  135. type Assets = A;
  136. type Runtime = R;
  137. }
  138. pub struct WindowManager<P: Params = DefaultArgs> {
  139. pub inner: Arc<InnerWindowManager<P>>,
  140. #[allow(clippy::type_complexity)]
  141. _marker: Args<P::Event, P::Label, P::MenuId, P::SystemTrayMenuId, P::Assets, P::Runtime>,
  142. }
  143. impl<P: Params> Clone for WindowManager<P> {
  144. fn clone(&self) -> Self {
  145. Self {
  146. inner: self.inner.clone(),
  147. _marker: Args::default(),
  148. }
  149. }
  150. }
  151. #[cfg(feature = "menu")]
  152. fn get_menu_ids<I: MenuId>(menu: &[Menu<I>]) -> HashMap<u32, I> {
  153. let mut map = HashMap::new();
  154. for m in menu {
  155. for item in &m.items {
  156. if let MenuItem::Custom(i) = item {
  157. map.insert(i.id_value(), i.id.clone());
  158. }
  159. }
  160. }
  161. map
  162. }
  163. impl<P: Params> WindowManager<P> {
  164. #[allow(clippy::too_many_arguments)]
  165. pub(crate) fn with_handlers(
  166. context: Context<P::Assets>,
  167. plugins: PluginStore<P>,
  168. invoke_handler: Box<InvokeHandler<P>>,
  169. on_page_load: Box<OnPageLoad<P>>,
  170. uri_scheme_protocols: HashMap<String, Arc<CustomProtocol>>,
  171. state: StateManager,
  172. window_event_listeners: Vec<GlobalWindowEventListener<P>>,
  173. #[cfg(feature = "menu")] (menu, menu_event_listeners): (
  174. Vec<Menu<P::MenuId>>,
  175. Vec<GlobalMenuEventListener<P>>,
  176. ),
  177. ) -> Self {
  178. Self {
  179. inner: Arc::new(InnerWindowManager {
  180. windows: Mutex::default(),
  181. plugins: Mutex::new(plugins),
  182. listeners: Listeners::default(),
  183. state: Arc::new(state),
  184. invoke_handler,
  185. on_page_load,
  186. config: Arc::new(context.config),
  187. assets: context.assets,
  188. default_window_icon: context.default_window_icon,
  189. salts: Mutex::default(),
  190. package_info: context.package_info,
  191. uri_scheme_protocols,
  192. #[cfg(feature = "menu")]
  193. menu_ids: get_menu_ids(&menu),
  194. #[cfg(feature = "menu")]
  195. menu,
  196. #[cfg(feature = "menu")]
  197. menu_event_listeners: Arc::new(menu_event_listeners),
  198. window_event_listeners: Arc::new(window_event_listeners),
  199. }),
  200. _marker: Args::default(),
  201. }
  202. }
  203. /// Get a locked handle to the windows.
  204. pub(crate) fn windows_lock(&self) -> MutexGuard<'_, HashMap<P::Label, Window<P>>> {
  205. self.inner.windows.lock().expect("poisoned window manager")
  206. }
  207. /// State managed by the application.
  208. pub(crate) fn state(&self) -> Arc<StateManager> {
  209. self.inner.state.clone()
  210. }
  211. /// Get the menu ids mapper.
  212. #[cfg(feature = "menu")]
  213. pub(crate) fn menu_ids(&self) -> HashMap<u32, P::MenuId> {
  214. self.inner.menu_ids.clone()
  215. }
  216. // setup content for dev-server
  217. #[cfg(dev)]
  218. fn get_url(&self) -> String {
  219. if self.inner.config.build.dev_path.starts_with("http") {
  220. self.inner.config.build.dev_path.clone()
  221. } else {
  222. "tauri://localhost".into()
  223. }
  224. }
  225. #[cfg(custom_protocol)]
  226. fn get_url(&self) -> String {
  227. "tauri://localhost".into()
  228. }
  229. fn prepare_pending_window(
  230. &self,
  231. mut pending: PendingWindow<P>,
  232. label: P::Label,
  233. pending_labels: &[P::Label],
  234. ) -> crate::Result<PendingWindow<P>> {
  235. let is_init_global = self.inner.config.build.with_global_tauri;
  236. let plugin_init = self
  237. .inner
  238. .plugins
  239. .lock()
  240. .expect("poisoned plugin store")
  241. .initialization_script();
  242. let mut webview_attributes = pending.webview_attributes
  243. .initialization_script(&self.initialization_script(&plugin_init, is_init_global))
  244. .initialization_script(&format!(
  245. r#"
  246. window.__TAURI__.__windows = {window_labels_array}.map(function (label) {{ return {{ label: label }} }});
  247. window.__TAURI__.__currentWindow = {{ label: {current_window_label} }}
  248. "#,
  249. window_labels_array = tags_to_javascript_array(pending_labels)?,
  250. current_window_label = label.to_js_string()?,
  251. ));
  252. if !pending.window_builder.has_icon() {
  253. if let Some(default_window_icon) = &self.inner.default_window_icon {
  254. let icon = Icon::Raw(default_window_icon.clone());
  255. pending.window_builder = pending.window_builder.icon(icon)?;
  256. }
  257. }
  258. #[cfg(feature = "menu")]
  259. if !pending.window_builder.has_menu() {
  260. pending.window_builder = pending.window_builder.menu(self.inner.menu.clone());
  261. }
  262. for (uri_scheme, protocol) in &self.inner.uri_scheme_protocols {
  263. if !webview_attributes.has_uri_scheme_protocol(uri_scheme) {
  264. let protocol = protocol.clone();
  265. webview_attributes = webview_attributes
  266. .register_uri_scheme_protocol(uri_scheme.clone(), move |p| (protocol.protocol)(p));
  267. }
  268. }
  269. if !webview_attributes.has_uri_scheme_protocol("tauri") {
  270. webview_attributes = webview_attributes
  271. .register_uri_scheme_protocol("tauri", self.prepare_uri_scheme_protocol().protocol);
  272. }
  273. let local_app_data = resolve_path(
  274. &self.inner.config,
  275. &self.inner.package_info,
  276. &self.inner.config.tauri.bundle.identifier,
  277. Some(BaseDirectory::LocalData),
  278. );
  279. if let Ok(user_data_dir) = local_app_data {
  280. // Make sure the directory exist without panic
  281. if create_dir_all(&user_data_dir).is_ok() {
  282. webview_attributes = webview_attributes.data_directory(user_data_dir);
  283. }
  284. }
  285. pending.webview_attributes = webview_attributes;
  286. Ok(pending)
  287. }
  288. fn prepare_rpc_handler(&self) -> WebviewRpcHandler<P> {
  289. let manager = self.clone();
  290. Box::new(move |window, request| {
  291. let window = Window::new(manager.clone(), window);
  292. let command = request.command.clone();
  293. let arg = request
  294. .params
  295. .unwrap()
  296. .as_array_mut()
  297. .unwrap()
  298. .first_mut()
  299. .unwrap_or(&mut JsonValue::Null)
  300. .take();
  301. match serde_json::from_value::<InvokePayload>(arg) {
  302. Ok(message) => {
  303. let _ = window.on_message(command, message);
  304. }
  305. Err(e) => {
  306. let error: crate::Error = e.into();
  307. let _ = window.eval(&format!(
  308. r#"console.error({})"#,
  309. JsonValue::String(error.to_string())
  310. ));
  311. }
  312. }
  313. })
  314. }
  315. fn prepare_uri_scheme_protocol(&self) -> CustomProtocol {
  316. let assets = self.inner.assets.clone();
  317. CustomProtocol {
  318. protocol: Box::new(move |path| {
  319. let mut path = path
  320. .split('?')
  321. // ignore query string
  322. .next()
  323. .unwrap()
  324. .to_string()
  325. .replace("tauri://localhost", "");
  326. if path.ends_with('/') {
  327. path.pop();
  328. }
  329. let path = if path.is_empty() {
  330. // if the url is `tauri://localhost`, we should load `index.html`
  331. "index.html".to_string()
  332. } else {
  333. // skip leading `/`
  334. path.chars().skip(1).collect::<String>()
  335. };
  336. let asset_response = assets
  337. .get(&path)
  338. .ok_or(crate::Error::AssetNotFound(path))
  339. .map(Cow::into_owned);
  340. match asset_response {
  341. Ok(asset) => Ok(asset),
  342. Err(e) => {
  343. #[cfg(debug_assertions)]
  344. eprintln!("{:?}", e); // TODO log::error!
  345. Err(Box::new(e))
  346. }
  347. }
  348. }),
  349. }
  350. }
  351. fn prepare_file_drop(&self) -> FileDropHandler<P> {
  352. let manager = self.clone();
  353. Box::new(move |event, window| {
  354. let manager = manager.clone();
  355. crate::async_runtime::block_on(async move {
  356. let window = Window::new(manager.clone(), window);
  357. let _ = match event {
  358. FileDropEvent::Hovered(paths) => {
  359. window.emit(&tauri_event::<P::Event>("tauri://file-drop"), Some(paths))
  360. }
  361. FileDropEvent::Dropped(paths) => window.emit(
  362. &tauri_event::<P::Event>("tauri://file-drop-hover"),
  363. Some(paths),
  364. ),
  365. FileDropEvent::Cancelled => window.emit(
  366. &tauri_event::<P::Event>("tauri://file-drop-cancelled"),
  367. Some(()),
  368. ),
  369. _ => unimplemented!(),
  370. };
  371. });
  372. true
  373. })
  374. }
  375. fn initialization_script(
  376. &self,
  377. plugin_initialization_script: &str,
  378. with_global_tauri: bool,
  379. ) -> String {
  380. format!(
  381. r#"
  382. {bundle_script}
  383. {core_script}
  384. {event_initialization_script}
  385. if (window.rpc) {{
  386. window.__TAURI__.invoke("__initialized", {{ url: window.location.href }})
  387. }} else {{
  388. window.addEventListener('DOMContentLoaded', function () {{
  389. window.__TAURI__.invoke("__initialized", {{ url: window.location.href }})
  390. }})
  391. }}
  392. {plugin_initialization_script}
  393. "#,
  394. core_script = include_str!("../scripts/core.js"),
  395. bundle_script = if with_global_tauri {
  396. include_str!("../scripts/bundle.js")
  397. } else {
  398. ""
  399. },
  400. event_initialization_script = self.event_initialization_script(),
  401. plugin_initialization_script = plugin_initialization_script
  402. )
  403. }
  404. fn event_initialization_script(&self) -> String {
  405. return format!(
  406. "
  407. window['{queue}'] = [];
  408. window['{function}'] = function (eventData, salt, ignoreQueue) {{
  409. const listeners = (window['{listeners}'] && window['{listeners}'][eventData.event]) || []
  410. if (!ignoreQueue && listeners.length === 0) {{
  411. window['{queue}'].push({{
  412. eventData: eventData,
  413. salt: salt
  414. }})
  415. }}
  416. if (listeners.length > 0) {{
  417. window.__TAURI__.invoke('tauri', {{
  418. __tauriModule: 'Internal',
  419. message: {{
  420. cmd: 'validateSalt',
  421. salt: salt
  422. }}
  423. }}).then(function (flag) {{
  424. if (flag) {{
  425. for (let i = listeners.length - 1; i >= 0; i--) {{
  426. const listener = listeners[i]
  427. eventData.id = listener.id
  428. listener.handler(eventData)
  429. }}
  430. }}
  431. }})
  432. }}
  433. }}
  434. ",
  435. function = self.inner.listeners.function_name(),
  436. queue = self.inner.listeners.queue_object_name(),
  437. listeners = self.inner.listeners.listeners_object_name()
  438. );
  439. }
  440. }
  441. #[cfg(test)]
  442. mod test {
  443. use super::{Args, WindowManager};
  444. use crate::{generate_context, plugin::PluginStore, StateManager, Wry};
  445. #[test]
  446. fn check_get_url() {
  447. let context = generate_context!("test/fixture/src-tauri/tauri.conf.json", crate);
  448. let manager: WindowManager<Args<String, String, String, String, _, Wry>> =
  449. WindowManager::with_handlers(
  450. context,
  451. PluginStore::default(),
  452. Box::new(|_| ()),
  453. Box::new(|_, _| ()),
  454. Default::default(),
  455. StateManager::new(),
  456. Default::default(),
  457. #[cfg(feature = "menu")]
  458. Default::default(),
  459. );
  460. #[cfg(custom_protocol)]
  461. assert_eq!(manager.get_url(), "tauri://localhost");
  462. #[cfg(dev)]
  463. assert_eq!(manager.get_url(), manager.config().build.dev_path);
  464. }
  465. }
  466. impl<P: Params> WindowManager<P> {
  467. pub fn run_invoke_handler(&self, invoke: Invoke<P>) {
  468. (self.inner.invoke_handler)(invoke);
  469. }
  470. pub fn run_on_page_load(&self, window: Window<P>, payload: PageLoadPayload) {
  471. (self.inner.on_page_load)(window.clone(), payload.clone());
  472. self
  473. .inner
  474. .plugins
  475. .lock()
  476. .expect("poisoned plugin store")
  477. .on_page_load(window, payload);
  478. }
  479. pub fn extend_api(&self, invoke: Invoke<P>) {
  480. self
  481. .inner
  482. .plugins
  483. .lock()
  484. .expect("poisoned plugin store")
  485. .extend_api(invoke);
  486. }
  487. pub fn initialize_plugins(&self, app: &App<P>) -> crate::Result<()> {
  488. self
  489. .inner
  490. .plugins
  491. .lock()
  492. .expect("poisoned plugin store")
  493. .initialize(&app, &self.inner.config.plugins)
  494. }
  495. pub fn prepare_window(
  496. &self,
  497. mut pending: PendingWindow<P>,
  498. pending_labels: &[P::Label],
  499. ) -> crate::Result<PendingWindow<P>> {
  500. let (is_local, url) = match &pending.webview_attributes.url {
  501. WindowUrl::App(path) => {
  502. let url = self.get_url();
  503. (
  504. true,
  505. // ignore "index.html" just to simplify the url
  506. if path.to_str() != Some("index.html") {
  507. format!("{}/{}", url, path.to_string_lossy())
  508. } else {
  509. url
  510. },
  511. )
  512. }
  513. WindowUrl::External(url) => (url.as_str().starts_with("tauri://"), url.to_string()),
  514. _ => unimplemented!(),
  515. };
  516. if is_local {
  517. let label = pending.label.clone();
  518. pending = self.prepare_pending_window(pending, label, pending_labels)?;
  519. pending.rpc_handler = Some(self.prepare_rpc_handler());
  520. }
  521. pending.file_drop_handler = Some(self.prepare_file_drop());
  522. pending.url = url;
  523. Ok(pending)
  524. }
  525. pub fn attach_window(&self, window: DetachedWindow<P>) -> Window<P> {
  526. let window = Window::new(self.clone(), window);
  527. let window_ = window.clone();
  528. let window_event_listeners = self.inner.window_event_listeners.clone();
  529. window.on_window_event(move |event| {
  530. let _ = on_window_event(&window_, event);
  531. for handler in window_event_listeners.iter() {
  532. handler(GlobalWindowEvent {
  533. window: window_.clone(),
  534. event: event.clone(),
  535. });
  536. }
  537. });
  538. #[cfg(feature = "menu")]
  539. {
  540. let window_ = window.clone();
  541. let menu_event_listeners = self.inner.menu_event_listeners.clone();
  542. window.on_menu_event(move |event| {
  543. let _ = on_menu_event(&window_, &event);
  544. for handler in menu_event_listeners.iter() {
  545. handler(WindowMenuEvent {
  546. window: window_.clone(),
  547. menu_item_id: event.menu_item_id.clone(),
  548. });
  549. }
  550. });
  551. }
  552. // insert the window into our manager
  553. {
  554. self
  555. .windows_lock()
  556. .insert(window.label().clone(), window.clone());
  557. }
  558. // let plugins know that a new window has been added to the manager
  559. {
  560. self
  561. .inner
  562. .plugins
  563. .lock()
  564. .expect("poisoned plugin store")
  565. .created(window.clone());
  566. }
  567. window
  568. }
  569. pub fn emit_filter<E: ?Sized, S, F>(&self, event: &E, payload: S, filter: F) -> crate::Result<()>
  570. where
  571. P::Event: Borrow<E>,
  572. E: TagRef<P::Event>,
  573. S: Serialize + Clone,
  574. F: Fn(&Window<P>) -> bool,
  575. {
  576. self
  577. .windows_lock()
  578. .values()
  579. .filter(|&w| filter(w))
  580. .try_for_each(|window| window.emit(event, payload.clone()))
  581. }
  582. pub fn labels(&self) -> HashSet<P::Label> {
  583. self.windows_lock().keys().cloned().collect()
  584. }
  585. pub fn config(&self) -> Arc<Config> {
  586. self.inner.config.clone()
  587. }
  588. pub fn package_info(&self) -> &PackageInfo {
  589. &self.inner.package_info
  590. }
  591. pub fn unlisten(&self, handler_id: EventHandler) {
  592. self.inner.listeners.unlisten(handler_id)
  593. }
  594. pub fn trigger<E: ?Sized>(&self, event: &E, window: Option<P::Label>, data: Option<String>)
  595. where
  596. P::Event: Borrow<E>,
  597. E: TagRef<P::Event>,
  598. {
  599. self.inner.listeners.trigger(event, window, data)
  600. }
  601. pub fn listen<F: Fn(Event) + Send + 'static>(
  602. &self,
  603. event: P::Event,
  604. window: Option<P::Label>,
  605. handler: F,
  606. ) -> EventHandler {
  607. self.inner.listeners.listen(event, window, handler)
  608. }
  609. pub fn once<F: Fn(Event) + Send + 'static>(
  610. &self,
  611. event: P::Event,
  612. window: Option<P::Label>,
  613. handler: F,
  614. ) -> EventHandler {
  615. self.inner.listeners.once(event, window, handler)
  616. }
  617. pub fn event_listeners_object_name(&self) -> String {
  618. self.inner.listeners.listeners_object_name()
  619. }
  620. pub fn event_queue_object_name(&self) -> String {
  621. self.inner.listeners.queue_object_name()
  622. }
  623. pub fn event_emit_function_name(&self) -> String {
  624. self.inner.listeners.function_name()
  625. }
  626. pub fn generate_salt(&self) -> Uuid {
  627. let salt = Uuid::new_v4();
  628. self
  629. .inner
  630. .salts
  631. .lock()
  632. .expect("poisoned salt mutex")
  633. .insert(salt);
  634. salt
  635. }
  636. pub fn verify_salt(&self, salt: String) -> bool {
  637. // flat out ignore any invalid uuids
  638. let uuid: Uuid = match salt.parse() {
  639. Ok(uuid) => uuid,
  640. Err(_) => return false,
  641. };
  642. // HashSet::remove lets us know if the entry was found
  643. self
  644. .inner
  645. .salts
  646. .lock()
  647. .expect("poisoned salt mutex")
  648. .remove(&uuid)
  649. }
  650. pub fn get_window<L: ?Sized>(&self, label: &L) -> Option<Window<P>>
  651. where
  652. P::Label: Borrow<L>,
  653. L: TagRef<P::Label>,
  654. {
  655. self.windows_lock().get(label).cloned()
  656. }
  657. pub fn windows(&self) -> HashMap<P::Label, Window<P>> {
  658. self.windows_lock().clone()
  659. }
  660. }
  661. fn on_window_event<P: Params>(window: &Window<P>, event: &WindowEvent) -> crate::Result<()> {
  662. match event {
  663. WindowEvent::Resized(size) => window.emit(
  664. &WINDOW_RESIZED_EVENT
  665. .parse()
  666. .unwrap_or_else(|_| panic!("unhandled event")),
  667. Some(size),
  668. )?,
  669. WindowEvent::Moved(position) => window.emit(
  670. &WINDOW_MOVED_EVENT
  671. .parse()
  672. .unwrap_or_else(|_| panic!("unhandled event")),
  673. Some(position),
  674. )?,
  675. WindowEvent::CloseRequested => window.emit(
  676. &WINDOW_CLOSE_REQUESTED_EVENT
  677. .parse()
  678. .unwrap_or_else(|_| panic!("unhandled event")),
  679. Some(()),
  680. )?,
  681. WindowEvent::Destroyed => window.emit(
  682. &WINDOW_DESTROYED_EVENT
  683. .parse()
  684. .unwrap_or_else(|_| panic!("unhandled event")),
  685. Some(()),
  686. )?,
  687. WindowEvent::Focused(focused) => window.emit(
  688. &if *focused {
  689. WINDOW_FOCUS_EVENT
  690. .parse()
  691. .unwrap_or_else(|_| panic!("unhandled event"))
  692. } else {
  693. WINDOW_BLUR_EVENT
  694. .parse()
  695. .unwrap_or_else(|_| panic!("unhandled event"))
  696. },
  697. Some(()),
  698. )?,
  699. WindowEvent::ScaleFactorChanged {
  700. scale_factor,
  701. new_inner_size,
  702. ..
  703. } => window.emit(
  704. &WINDOW_SCALE_FACTOR_CHANGED_EVENT
  705. .parse()
  706. .unwrap_or_else(|_| panic!("unhandled event")),
  707. Some(ScaleFactorChanged {
  708. scale_factor: *scale_factor,
  709. size: new_inner_size.clone(),
  710. }),
  711. )?,
  712. _ => unimplemented!(),
  713. }
  714. Ok(())
  715. }
  716. #[derive(Serialize)]
  717. #[serde(rename_all = "camelCase")]
  718. struct ScaleFactorChanged {
  719. scale_factor: f64,
  720. size: PhysicalSize<u32>,
  721. }
  722. #[cfg(feature = "menu")]
  723. fn on_menu_event<P: Params>(window: &Window<P>, event: &MenuEvent<P::MenuId>) -> crate::Result<()> {
  724. window.emit(
  725. &MENU_EVENT
  726. .parse()
  727. .unwrap_or_else(|_| panic!("unhandled event")),
  728. Some(event.menu_item_id.clone()),
  729. )
  730. }