manager.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. use crate::{
  2. api::{
  3. assets::Assets,
  4. config::{Config, WindowUrl},
  5. PackageInfo,
  6. },
  7. event::{Event, EventHandler, Listeners},
  8. hooks::{InvokeHandler, InvokeMessage, InvokePayload, OnPageLoad, PageLoadPayload},
  9. plugin::PluginStore,
  10. runtime::{
  11. sealed::ParamsPrivate,
  12. tag::{tags_to_javascript_array, Tag, ToJavascript},
  13. webview::{
  14. Attributes, AttributesPrivate, CustomProtocol, FileDropEvent, FileDropHandler,
  15. WebviewRpcHandler,
  16. },
  17. window::{DetachedWindow, PendingWindow, Window},
  18. Context, Dispatch, Icon, Params, Runtime,
  19. },
  20. };
  21. use serde::Serialize;
  22. use serde_json::Value as JsonValue;
  23. use std::{
  24. borrow::Cow,
  25. collections::HashSet,
  26. convert::TryInto,
  27. sync::{Arc, Mutex},
  28. };
  29. use uuid::Uuid;
  30. pub struct InnerWindowManager<M: Params> {
  31. windows: Mutex<HashSet<Window<M>>>,
  32. plugins: Mutex<PluginStore<M>>,
  33. listeners: Listeners<M::Event, M::Label>,
  34. /// The JS message handler.
  35. invoke_handler: Box<InvokeHandler<M>>,
  36. /// The page load hook, invoked when the webview performs a navigation.
  37. on_page_load: Box<OnPageLoad<M>>,
  38. config: Config,
  39. assets: Arc<M::Assets>,
  40. default_window_icon: Option<Vec<u8>>,
  41. /// A list of salts that are valid for the current application.
  42. salts: Mutex<HashSet<Uuid>>,
  43. package_info: PackageInfo,
  44. }
  45. pub struct WindowManager<E, L, A, R>
  46. where
  47. E: Tag,
  48. L: Tag,
  49. A: Assets + 'static,
  50. R: Runtime,
  51. {
  52. pub(crate) inner: Arc<InnerWindowManager<Self>>,
  53. }
  54. impl<E, L, A, R> Clone for WindowManager<E, L, A, R>
  55. where
  56. E: Tag,
  57. L: Tag,
  58. A: Assets + 'static,
  59. R: Runtime,
  60. {
  61. fn clone(&self) -> Self {
  62. Self {
  63. inner: self.inner.clone(),
  64. }
  65. }
  66. }
  67. impl<E, L, A, R> WindowManager<E, L, A, R>
  68. where
  69. E: Tag,
  70. L: Tag,
  71. A: Assets,
  72. R: Runtime,
  73. {
  74. pub(crate) fn with_handlers(
  75. context: Context<A>,
  76. invoke_handler: Box<InvokeHandler<Self>>,
  77. on_page_load: Box<OnPageLoad<Self>>,
  78. ) -> Self {
  79. Self {
  80. inner: Arc::new(InnerWindowManager {
  81. windows: Mutex::default(),
  82. plugins: Mutex::default(),
  83. listeners: Listeners::default(),
  84. invoke_handler,
  85. on_page_load,
  86. config: context.config,
  87. assets: Arc::new(context.assets),
  88. default_window_icon: context.default_window_icon,
  89. salts: Mutex::default(),
  90. package_info: context.package_info,
  91. }),
  92. }
  93. }
  94. // setup content for dev-server
  95. #[cfg(dev)]
  96. fn get_url(&self) -> String {
  97. if self.inner.config.build.dev_path.starts_with("http") {
  98. self.inner.config.build.dev_path.clone()
  99. } else {
  100. format!("tauri://{}", self.inner.config.tauri.bundle.identifier)
  101. }
  102. }
  103. #[cfg(custom_protocol)]
  104. fn get_url(&self) -> String {
  105. format!("tauri://{}", self.inner.config.tauri.bundle.identifier)
  106. }
  107. fn prepare_attributes(
  108. &self,
  109. attrs: <R::Dispatcher as Dispatch>::Attributes,
  110. url: String,
  111. label: L,
  112. pending_labels: &[L],
  113. ) -> crate::Result<<R::Dispatcher as Dispatch>::Attributes> {
  114. let is_init_global = self.inner.config.build.with_global_tauri;
  115. let plugin_init = self
  116. .inner
  117. .plugins
  118. .lock()
  119. .expect("poisoned plugin store")
  120. .initialization_script();
  121. let mut attributes = attrs
  122. .url(url)
  123. .initialization_script(&self.initialization_script(&plugin_init, is_init_global))
  124. .initialization_script(&format!(
  125. r#"
  126. window.__TAURI__.__windows = {window_labels_array}.map(function (label) {{ return {{ label: label }} }});
  127. window.__TAURI__.__currentWindow = {{ label: {current_window_label} }}
  128. "#,
  129. window_labels_array = tags_to_javascript_array(pending_labels)?,
  130. current_window_label = label.to_javascript()?,
  131. ));
  132. if !attributes.has_icon() {
  133. if let Some(default_window_icon) = &self.inner.default_window_icon {
  134. let icon = Icon::Raw(default_window_icon.clone());
  135. let icon = icon.try_into().expect("infallible icon convert failed");
  136. attributes = attributes.icon(icon);
  137. }
  138. }
  139. // If we are on windows use App Data Local as webview temp dir
  140. // to prevent any bundled application to failed.
  141. // Fix: https://github.com/tauri-apps/tauri/issues/1365
  142. #[cfg(windows)]
  143. {
  144. // Should return a path similar to C:\Users\<User>\AppData\Local\<AppName>
  145. let local_app_data = tauri_api::path::resolve_path(
  146. self.inner.package_info.name,
  147. Some(tauri_api::path::BaseDirectory::LocalData),
  148. );
  149. // Make sure the directory exist without panic
  150. if let Ok(user_data_dir) = local_app_data {
  151. if let Ok(()) = std::fs::create_dir_all(&user_data_dir) {
  152. attributes = attributes.user_data_path(Some(user_data_dir));
  153. }
  154. }
  155. }
  156. Ok(attributes)
  157. }
  158. fn prepare_rpc_handler(&self) -> WebviewRpcHandler<Self> {
  159. let manager = self.clone();
  160. Box::new(move |window, request| {
  161. let window = manager.attach_window(window);
  162. let command = request.command.clone();
  163. let arg = request
  164. .params
  165. .unwrap()
  166. .as_array_mut()
  167. .unwrap()
  168. .first_mut()
  169. .unwrap_or(&mut JsonValue::Null)
  170. .take();
  171. match serde_json::from_value::<InvokePayload>(arg) {
  172. Ok(message) => {
  173. let _ = window.on_message(command, message);
  174. }
  175. Err(e) => {
  176. let error: crate::Error = e.into();
  177. let _ = window.eval(&format!(
  178. r#"console.error({})"#,
  179. JsonValue::String(error.to_string())
  180. ));
  181. }
  182. }
  183. })
  184. }
  185. fn prepare_custom_protocol(&self) -> CustomProtocol {
  186. let assets = self.inner.assets.clone();
  187. let bundle_identifier = self.inner.config.tauri.bundle.identifier.clone();
  188. CustomProtocol {
  189. name: "tauri".into(),
  190. handler: Box::new(move |path| {
  191. let mut path = path
  192. .split('?')
  193. // ignore query string
  194. .next()
  195. .unwrap()
  196. .to_string()
  197. .replace(&format!("tauri://{}", bundle_identifier), "");
  198. if path.ends_with('/') {
  199. path.pop();
  200. }
  201. let path = if path.is_empty() {
  202. // if the url is `tauri://${appId}`, we should load `index.html`
  203. "index.html".to_string()
  204. } else {
  205. // skip leading `/`
  206. path.chars().skip(1).collect::<String>()
  207. };
  208. let asset_response = assets
  209. .get(&path)
  210. .ok_or(crate::Error::AssetNotFound(path))
  211. .map(Cow::into_owned);
  212. match asset_response {
  213. Ok(asset) => Ok(asset),
  214. Err(e) => {
  215. #[cfg(debug_assertions)]
  216. eprintln!("{:?}", e); // TODO log::error!
  217. Err(e)
  218. }
  219. }
  220. }),
  221. }
  222. }
  223. fn prepare_file_drop(&self) -> FileDropHandler<Self> {
  224. let manager = self.clone();
  225. Box::new(move |event, window| {
  226. let manager = manager.clone();
  227. crate::async_runtime::block_on(async move {
  228. let window = manager.attach_window(window);
  229. let _ = match event {
  230. FileDropEvent::Hovered(paths) => {
  231. window.emit_internal("tauri://file-drop".to_string(), Some(paths))
  232. }
  233. FileDropEvent::Dropped(paths) => {
  234. window.emit_internal("tauri://file-drop-hover".to_string(), Some(paths))
  235. }
  236. FileDropEvent::Cancelled => {
  237. window.emit_internal("tauri://file-drop-cancelled".to_string(), Some(()))
  238. }
  239. };
  240. });
  241. true
  242. })
  243. }
  244. fn initialization_script(
  245. &self,
  246. plugin_initialization_script: &str,
  247. with_global_tauri: bool,
  248. ) -> String {
  249. format!(
  250. r#"
  251. {bundle_script}
  252. {core_script}
  253. {event_initialization_script}
  254. if (window.rpc) {{
  255. window.__TAURI__.invoke("__initialized", {{ url: window.location.href }})
  256. }} else {{
  257. window.addEventListener('DOMContentLoaded', function () {{
  258. window.__TAURI__.invoke("__initialized", {{ url: window.location.href }})
  259. }})
  260. }}
  261. {plugin_initialization_script}
  262. "#,
  263. core_script = include_str!("../../scripts/core.js"),
  264. bundle_script = if with_global_tauri {
  265. include_str!("../../scripts/bundle.js")
  266. } else {
  267. ""
  268. },
  269. event_initialization_script = self.event_initialization_script(),
  270. plugin_initialization_script = plugin_initialization_script
  271. )
  272. }
  273. fn event_initialization_script(&self) -> String {
  274. return format!(
  275. "
  276. window['{queue}'] = [];
  277. window['{function}'] = function (eventData, salt, ignoreQueue) {{
  278. const listeners = (window['{listeners}'] && window['{listeners}'][eventData.event]) || []
  279. if (!ignoreQueue && listeners.length === 0) {{
  280. window['{queue}'].push({{
  281. eventData: eventData,
  282. salt: salt
  283. }})
  284. }}
  285. if (listeners.length > 0) {{
  286. window.__TAURI__.invoke('tauri', {{
  287. __tauriModule: 'Internal',
  288. message: {{
  289. cmd: 'validateSalt',
  290. salt: salt
  291. }}
  292. }}).then(function (flag) {{
  293. if (flag) {{
  294. for (let i = listeners.length - 1; i >= 0; i--) {{
  295. const listener = listeners[i]
  296. eventData.id = listener.id
  297. listener.handler(eventData)
  298. }}
  299. }}
  300. }})
  301. }}
  302. }}
  303. ",
  304. function = self.inner.listeners.function_name(),
  305. queue = self.inner.listeners.queue_object_name(),
  306. listeners = self.inner.listeners.listeners_object_name()
  307. );
  308. }
  309. }
  310. #[cfg(test)]
  311. mod test {
  312. use crate::{generate_context, runtime::flavor::wry::Wry};
  313. use super::WindowManager;
  314. #[test]
  315. fn check_get_url() {
  316. let context = generate_context!("test/fixture/src-tauri/tauri.conf.json", crate::Context);
  317. let manager: WindowManager<String, String, _, Wry> =
  318. WindowManager::with_handlers(context, Box::new(|_| ()), Box::new(|_, _| ()));
  319. #[cfg(custom_protocol)]
  320. assert_eq!(manager.get_url(), "tauri://studio.tauri.example");
  321. #[cfg(dev)]
  322. {
  323. use crate::runtime::sealed::ParamsPrivate;
  324. assert_eq!(manager.get_url(), manager.config().build.dev_path);
  325. }
  326. }
  327. }
  328. impl<E, L, A, R> ParamsPrivate<Self> for WindowManager<E, L, A, R>
  329. where
  330. E: Tag,
  331. L: Tag,
  332. A: Assets + 'static,
  333. R: Runtime,
  334. {
  335. fn run_invoke_handler(&self, message: InvokeMessage<Self>) {
  336. (self.inner.invoke_handler)(message);
  337. }
  338. fn run_on_page_load(&self, window: Window<Self>, payload: PageLoadPayload) {
  339. (self.inner.on_page_load)(window.clone(), payload.clone());
  340. self
  341. .inner
  342. .plugins
  343. .lock()
  344. .expect("poisoned plugin store")
  345. .on_page_load(window, payload);
  346. }
  347. fn extend_api(&self, command: String, message: InvokeMessage<Self>) {
  348. self
  349. .inner
  350. .plugins
  351. .lock()
  352. .expect("poisoned plugin store")
  353. .extend_api(command, message);
  354. }
  355. fn initialize_plugins(&self) -> crate::Result<()> {
  356. self
  357. .inner
  358. .plugins
  359. .lock()
  360. .expect("poisoned plugin store")
  361. .initialize(&self.inner.config.plugins)
  362. }
  363. fn prepare_window(
  364. &self,
  365. mut pending: PendingWindow<Self>,
  366. pending_labels: &[L],
  367. ) -> crate::Result<PendingWindow<Self>> {
  368. let (is_local, url) = match &pending.url {
  369. WindowUrl::App => (true, self.get_url()),
  370. // todo: we should probably warn about how custom urls usually need to be valid urls
  371. // e.g. cannot be relative without a base
  372. WindowUrl::Custom(url) => (url.len() > 7 && &url[0..8] == "tauri://", url.clone()),
  373. };
  374. let attributes = pending.attributes.clone();
  375. if is_local {
  376. let label = pending.label.clone();
  377. pending.attributes = self.prepare_attributes(attributes, url, label, pending_labels)?;
  378. pending.rpc_handler = Some(self.prepare_rpc_handler());
  379. pending.custom_protocol = Some(self.prepare_custom_protocol());
  380. } else {
  381. pending.attributes = attributes.url(url);
  382. }
  383. pending.file_drop_handler = Some(self.prepare_file_drop());
  384. Ok(pending)
  385. }
  386. fn attach_window(&self, window: DetachedWindow<Self>) -> Window<Self> {
  387. let window = Window::new(self.clone(), window);
  388. // insert the window into our manager
  389. {
  390. self
  391. .inner
  392. .windows
  393. .lock()
  394. .expect("poisoned window manager")
  395. .insert(window.clone());
  396. }
  397. // let plugins know that a new window has been added to the manager
  398. {
  399. self
  400. .inner
  401. .plugins
  402. .lock()
  403. .expect("poisoned plugin store")
  404. .created(window.clone());
  405. }
  406. window
  407. }
  408. fn emit_filter_internal<S: Serialize + Clone, F: Fn(&Window<Self>) -> bool>(
  409. &self,
  410. event: String,
  411. payload: Option<S>,
  412. filter: F,
  413. ) -> crate::Result<()> {
  414. self
  415. .inner
  416. .windows
  417. .lock()
  418. .expect("poisoned window manager")
  419. .iter()
  420. .filter(|&w| filter(w))
  421. .try_for_each(|window| window.emit_internal(event.clone(), payload.clone()))
  422. }
  423. fn emit_filter<S: Serialize + Clone, F: Fn(&Window<Self>) -> bool>(
  424. &self,
  425. event: E,
  426. payload: Option<S>,
  427. filter: F,
  428. ) -> crate::Result<()> {
  429. self
  430. .inner
  431. .windows
  432. .lock()
  433. .expect("poisoned window manager")
  434. .iter()
  435. .filter(|&w| filter(w))
  436. .try_for_each(|window| window.emit(&event, payload.clone()))
  437. }
  438. fn labels(&self) -> HashSet<L> {
  439. self
  440. .inner
  441. .windows
  442. .lock()
  443. .expect("poisoned window manager")
  444. .iter()
  445. .map(|w| w.label().clone())
  446. .collect()
  447. }
  448. fn config(&self) -> &Config {
  449. &self.inner.config
  450. }
  451. fn package_info(&self) -> &PackageInfo {
  452. &self.inner.package_info
  453. }
  454. fn unlisten(&self, handler_id: EventHandler) {
  455. self.inner.listeners.unlisten(handler_id)
  456. }
  457. fn trigger(&self, event: E, window: Option<L>, data: Option<String>) {
  458. self.inner.listeners.trigger(event, window, data)
  459. }
  460. fn listen<F: Fn(Event) + Send + 'static>(
  461. &self,
  462. event: E,
  463. window: Option<L>,
  464. handler: F,
  465. ) -> EventHandler {
  466. self.inner.listeners.listen(event, window, handler)
  467. }
  468. fn once<F: Fn(Event) + Send + 'static>(&self, event: E, window: Option<L>, handler: F) {
  469. self.inner.listeners.once(event, window, handler)
  470. }
  471. fn event_listeners_object_name(&self) -> String {
  472. self.inner.listeners.listeners_object_name()
  473. }
  474. fn event_queue_object_name(&self) -> String {
  475. self.inner.listeners.queue_object_name()
  476. }
  477. fn event_emit_function_name(&self) -> String {
  478. self.inner.listeners.function_name()
  479. }
  480. fn generate_salt(&self) -> Uuid {
  481. let salt = Uuid::new_v4();
  482. self
  483. .inner
  484. .salts
  485. .lock()
  486. .expect("poisoned salt mutex")
  487. .insert(salt);
  488. salt
  489. }
  490. fn verify_salt(&self, salt: String) -> bool {
  491. // flat out ignore any invalid uuids
  492. let uuid: Uuid = match salt.parse() {
  493. Ok(uuid) => uuid,
  494. Err(_) => return false,
  495. };
  496. // HashSet::remove lets us know if the entry was found
  497. self
  498. .inner
  499. .salts
  500. .lock()
  501. .expect("poisoned salt mutex")
  502. .remove(&uuid)
  503. }
  504. }
  505. impl<E, L, A, R> Params for WindowManager<E, L, A, R>
  506. where
  507. E: Tag,
  508. L: Tag,
  509. A: Assets,
  510. R: Runtime,
  511. {
  512. type Event = E;
  513. type Label = L;
  514. type Assets = A;
  515. type Runtime = R;
  516. }