/
app.rs
1679 lines (1544 loc) · 50.7 KB
/
app.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg(feature = "system-tray")]
pub(crate) mod tray;
use crate::{
api::ipc::CallbackFn,
command::{CommandArg, CommandItem},
hooks::{
window_invoke_responder, InvokeHandler, InvokeResponder, OnPageLoad, PageLoadPayload, SetupHook,
},
manager::{Asset, CustomProtocol, WindowManager},
plugin::{Plugin, PluginStore},
runtime::{
http::{Request as HttpRequest, Response as HttpResponse},
webview::WebviewAttributes,
window::{PendingWindow, WindowEvent as RuntimeWindowEvent},
ExitRequestedEventAction, RunEvent as RuntimeRunEvent,
},
scope::FsScope,
sealed::{ManagerBase, RuntimeOrDispatch},
utils::config::Config,
utils::{assets::Assets, resources::resource_relpath, Env},
Context, EventLoopMessage, Invoke, InvokeError, InvokeResponse, Manager, Runtime, Scopes,
StateManager, Theme, Window,
};
#[cfg(shell_scope)]
use crate::scope::ShellScope;
use tauri_macros::default_runtime;
use tauri_runtime::window::{
dpi::{PhysicalPosition, PhysicalSize},
FileDropEvent,
};
use tauri_utils::PackageInfo;
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{mpsc::Sender, Arc, Weak},
};
use crate::runtime::menu::{Menu, MenuId, MenuIdRef};
use crate::runtime::RuntimeHandle;
#[cfg(feature = "system-tray")]
use crate::runtime::SystemTrayEvent as RuntimeSystemTrayEvent;
#[cfg(updater)]
use crate::updater;
#[cfg(target_os = "macos")]
use crate::ActivationPolicy;
pub(crate) type GlobalMenuEventListener<R> = Box<dyn Fn(WindowMenuEvent<R>) + Send + Sync>;
pub(crate) type GlobalWindowEventListener<R> = Box<dyn Fn(GlobalWindowEvent<R>) + Send + Sync>;
#[cfg(feature = "system-tray")]
type SystemTrayEventListener<R> = Box<dyn Fn(&AppHandle<R>, tray::SystemTrayEvent) + Send + Sync>;
/// Api exposed on the `ExitRequested` event.
#[derive(Debug)]
pub struct ExitRequestApi(Sender<ExitRequestedEventAction>);
impl ExitRequestApi {
/// Prevents the app from exiting
pub fn prevent_exit(&self) {
self.0.send(ExitRequestedEventAction::Prevent).unwrap();
}
}
/// Api exposed on the `CloseRequested` event.
#[derive(Debug, Clone)]
pub struct CloseRequestApi(Sender<bool>);
impl CloseRequestApi {
/// Prevents the window from being closed.
pub fn prevent_close(&self) {
self.0.send(true).unwrap();
}
}
/// An event from a window.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum WindowEvent {
/// The size of the window has changed. Contains the client area's new dimensions.
Resized(PhysicalSize<u32>),
/// The position of the window has changed. Contains the window's new position.
Moved(PhysicalPosition<i32>),
/// The window has been requested to close.
#[non_exhaustive]
CloseRequested {
/// An API modify the behavior of the close requested event.
api: CloseRequestApi,
},
/// The window has been destroyed.
Destroyed,
/// The window gained or lost focus.
///
/// The parameter is true if the window has gained focus, and false if it has lost focus.
Focused(bool),
/// The window's scale factor has changed.
///
/// The following user actions can cause DPI changes:
///
/// - Changing the display's resolution.
/// - Changing the display's scale factor (e.g. in Control Panel on Windows).
/// - Moving the window to a display with a different scale factor.
#[non_exhaustive]
ScaleFactorChanged {
/// The new scale factor.
scale_factor: f64,
/// The window inner size.
new_inner_size: PhysicalSize<u32>,
},
/// An event associated with the file drop action.
FileDrop(FileDropEvent),
/// The system window theme has changed.
///
/// Applications might wish to react to this to change the theme of the content of the window when the system changes the window theme.
///
/// ## Platform-specific
///
/// - **macOS / Linux**: Not supported.
/// - **Windows**: Only delivered if the window [`theme`](`crate::window::WindowBuilder#method.theme`) is `None`.
ThemeChanged(Theme),
}
impl From<RuntimeWindowEvent> for WindowEvent {
fn from(event: RuntimeWindowEvent) -> Self {
match event {
RuntimeWindowEvent::Resized(size) => Self::Resized(size),
RuntimeWindowEvent::Moved(position) => Self::Moved(position),
RuntimeWindowEvent::CloseRequested { signal_tx } => Self::CloseRequested {
api: CloseRequestApi(signal_tx),
},
RuntimeWindowEvent::Destroyed => Self::Destroyed,
RuntimeWindowEvent::Focused(flag) => Self::Focused(flag),
RuntimeWindowEvent::ScaleFactorChanged {
scale_factor,
new_inner_size,
} => Self::ScaleFactorChanged {
scale_factor,
new_inner_size,
},
RuntimeWindowEvent::FileDrop(event) => Self::FileDrop(event),
RuntimeWindowEvent::ThemeChanged(theme) => Self::ThemeChanged(theme),
}
}
}
/// An application event, triggered from the event loop.
#[derive(Debug)]
#[non_exhaustive]
pub enum RunEvent {
/// Event loop is exiting.
Exit,
/// The app is about to exit
#[non_exhaustive]
ExitRequested {
/// Event API
api: ExitRequestApi,
},
/// An event associated with a window.
#[non_exhaustive]
WindowEvent {
/// The window label.
label: String,
/// The detailed event.
event: WindowEvent,
},
/// Application ready.
Ready,
/// Sent if the event loop is being resumed.
Resumed,
/// Emitted when all of the event loop’s input events have been processed and redraw processing is about to begin.
///
/// This event is useful as a place to put your code that should be run after all state-changing events have been handled and you want to do stuff (updating state, performing calculations, etc) that happens as the “main body” of your event loop.
MainEventsCleared,
/// Updater event.
#[cfg(updater)]
#[cfg_attr(doc_cfg, doc(cfg(feature = "updater")))]
Updater(crate::UpdaterEvent),
}
impl From<EventLoopMessage> for RunEvent {
fn from(event: EventLoopMessage) -> Self {
match event {
#[cfg(updater)]
EventLoopMessage::Updater(event) => RunEvent::Updater(event),
}
}
}
/// A menu event that was triggered on a window.
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct WindowMenuEvent<R: Runtime> {
pub(crate) menu_item_id: MenuId,
pub(crate) window: Window<R>,
}
impl<R: Runtime> WindowMenuEvent<R> {
/// The menu item id.
pub fn menu_item_id(&self) -> MenuIdRef<'_> {
&self.menu_item_id
}
/// The window that the menu belongs to.
pub fn window(&self) -> &Window<R> {
&self.window
}
}
/// A window event that was triggered on the specified window.
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct GlobalWindowEvent<R: Runtime> {
pub(crate) event: WindowEvent,
pub(crate) window: Window<R>,
}
impl<R: Runtime> GlobalWindowEvent<R> {
/// The event payload.
pub fn event(&self) -> &WindowEvent {
&self.event
}
/// The window that the menu belongs to.
pub fn window(&self) -> &Window<R> {
&self.window
}
}
#[cfg(updater)]
#[derive(Debug, Clone, Default)]
pub(crate) struct UpdaterSettings {
pub(crate) target: Option<String>,
}
/// The path resolver is a helper for the application-specific [`crate::api::path`] APIs.
#[derive(Debug, Clone)]
pub struct PathResolver {
env: Env,
config: Arc<Config>,
package_info: PackageInfo,
}
impl PathResolver {
/// Returns the path to the resource directory of this app.
pub fn resource_dir(&self) -> Option<PathBuf> {
crate::api::path::resource_dir(&self.package_info, &self.env)
}
/// Resolves the path of the given resource.
/// Note that the path must be the same as provided in `tauri.conf.json`.
///
/// This function is helpful when your resource path includes a root dir (`/`) or parent component (`..`),
/// because Tauri replaces them with a parent folder, so simply using [`Self::resource_dir`] and joining the path
/// won't work.
///
/// # Examples
///
/// `tauri.conf.json`:
/// ```json
/// {
/// "tauri": {
/// "bundle": {
/// "resources": ["../assets/*"]
/// }
/// }
/// }
/// ```
///
/// ```no_run
/// tauri::Builder::default()
/// .setup(|app| {
/// let resource_path = app.path_resolver()
/// .resolve_resource("../assets/logo.svg")
/// .expect("failed to resolve resource dir");
/// Ok(())
/// });
/// ```
pub fn resolve_resource<P: AsRef<Path>>(&self, path: P) -> Option<PathBuf> {
self
.resource_dir()
.map(|dir| dir.join(resource_relpath(path.as_ref())))
}
/// Returns the path to the suggested directory for your app config files.
pub fn app_dir(&self) -> Option<PathBuf> {
crate::api::path::app_dir(&self.config)
}
/// Returns the path to the suggested log directory.
pub fn log_dir(&self) -> Option<PathBuf> {
crate::api::path::log_dir(&self.config)
}
}
/// The asset resolver is a helper to access the [`tauri_utils::assets::Assets`] interface.
#[derive(Debug, Clone)]
pub struct AssetResolver<R: Runtime> {
manager: WindowManager<R>,
}
impl<R: Runtime> AssetResolver<R> {
/// Gets the app asset associated with the given path.
pub fn get(&self, path: String) -> Option<Asset> {
self.manager.get_asset(path).ok()
}
}
/// A handle to the currently running application.
///
/// This type implements [`Manager`] which allows for manipulation of global application items.
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct AppHandle<R: Runtime> {
runtime_handle: R::Handle,
pub(crate) manager: WindowManager<R>,
#[cfg(feature = "global-shortcut")]
global_shortcut_manager: R::GlobalShortcutManager,
#[cfg(feature = "clipboard")]
clipboard_manager: R::ClipboardManager,
#[cfg(feature = "system-tray")]
tray_handle: Option<tray::SystemTrayHandle<R>>,
/// The updater configuration.
#[cfg(updater)]
pub(crate) updater_settings: UpdaterSettings,
}
impl<R: Runtime> AppHandle<R> {
// currently only used on the updater
#[allow(dead_code)]
pub(crate) fn create_proxy(&self) -> R::EventLoopProxy {
self.runtime_handle.create_proxy()
}
}
/// APIs specific to the wry runtime.
#[cfg(feature = "wry")]
impl AppHandle<crate::Wry> {
/// Create a new tao window using a callback. The event loop must be running at this point.
pub fn create_tao_window<
F: FnOnce() -> (String, tauri_runtime_wry::WryWindowBuilder) + Send + 'static,
>(
&self,
f: F,
) -> crate::Result<Weak<tauri_runtime_wry::Window>> {
self.runtime_handle.create_tao_window(f).map_err(Into::into)
}
/// Sends a window message to the event loop.
pub fn send_tao_window_event(
&self,
window_id: tauri_runtime_wry::WindowId,
message: tauri_runtime_wry::WindowMessage,
) -> crate::Result<()> {
self
.runtime_handle
.send_event(tauri_runtime_wry::Message::Window(
self.runtime_handle.window_id(window_id),
message,
))
.map_err(Into::into)
}
}
impl<R: Runtime> Clone for AppHandle<R> {
fn clone(&self) -> Self {
Self {
runtime_handle: self.runtime_handle.clone(),
manager: self.manager.clone(),
#[cfg(feature = "global-shortcut")]
global_shortcut_manager: self.global_shortcut_manager.clone(),
#[cfg(feature = "clipboard")]
clipboard_manager: self.clipboard_manager.clone(),
#[cfg(feature = "system-tray")]
tray_handle: self.tray_handle.clone(),
#[cfg(updater)]
updater_settings: self.updater_settings.clone(),
}
}
}
impl<'de, R: Runtime> CommandArg<'de, R> for AppHandle<R> {
/// Grabs the [`Window`] from the [`CommandItem`] and returns the associated [`AppHandle`]. This will never fail.
fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
Ok(command.message.window().app_handle)
}
}
impl<R: Runtime> AppHandle<R> {
/// Runs the given closure on the main thread.
pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
self
.runtime_handle
.run_on_main_thread(f)
.map_err(Into::into)
}
/// Removes the system tray.
#[cfg(all(windows, feature = "system-tray"))]
#[cfg_attr(doc_cfg, doc(cfg(all(windows, feature = "system-tray"))))]
fn remove_system_tray(&self) -> crate::Result<()> {
self.runtime_handle.remove_system_tray().map_err(Into::into)
}
/// Adds a Tauri application plugin.
/// This function can be used to register a plugin that is loaded dynamically e.g. after login.
/// For plugins that are created when the app is started, prefer [`Builder::plugin`].
///
/// See [`Builder::plugin`] for more information.
///
/// # Examples
///
/// ```
/// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime};
///
/// fn init_plugin<R: Runtime>() -> TauriPlugin<R> {
/// PluginBuilder::new("dummy").build()
/// }
///
/// tauri::Builder::default()
/// .setup(move |app| {
/// let handle = app.handle();
/// std::thread::spawn(move || {
/// handle.plugin(init_plugin());
/// });
///
/// Ok(())
/// });
/// ```
pub fn plugin<P: Plugin<R> + 'static>(&self, mut plugin: P) -> crate::Result<()> {
plugin
.initialize(
self,
self
.config()
.plugins
.0
.get(plugin.name())
.cloned()
.unwrap_or_default(),
)
.map_err(|e| crate::Error::PluginInitialization(plugin.name().to_string(), e.to_string()))?;
self
.manager()
.inner
.plugins
.lock()
.unwrap()
.register(plugin);
Ok(())
}
/// Removes the plugin with the given name.
///
/// # Examples
///
/// ```
/// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin, Plugin}, Runtime};
///
/// fn init_plugin<R: Runtime>() -> TauriPlugin<R> {
/// PluginBuilder::new("dummy").build()
/// }
///
/// let plugin = init_plugin();
/// // `.name()` requires the `PLugin` trait import
/// let plugin_name = plugin.name();
/// tauri::Builder::default()
/// .plugin(plugin)
/// .setup(move |app| {
/// let handle = app.handle();
/// std::thread::spawn(move || {
/// handle.remove_plugin(plugin_name);
/// });
///
/// Ok(())
/// });
/// ```
pub fn remove_plugin(&self, plugin: &'static str) -> bool {
self
.manager()
.inner
.plugins
.lock()
.unwrap()
.unregister(plugin)
}
/// Exits the app. This is the same as [`std::process::exit`], but it performs cleanup on this application.
pub fn exit(&self, exit_code: i32) {
self.cleanup_before_exit();
std::process::exit(exit_code);
}
/// Restarts the app. This is the same as [`crate::api::process::restart`], but it performs cleanup on this application.
pub fn restart(&self) {
self.cleanup_before_exit();
crate::api::process::restart(&self.env());
}
/// Runs necessary cleanup tasks before exiting the process
fn cleanup_before_exit(&self) {
#[cfg(any(shell_execute, shell_sidecar))]
{
crate::api::process::kill_children();
}
#[cfg(all(windows, feature = "system-tray"))]
{
let _ = self.remove_system_tray();
}
}
}
impl<R: Runtime> Manager<R> for AppHandle<R> {}
impl<R: Runtime> ManagerBase<R> for AppHandle<R> {
fn manager(&self) -> &WindowManager<R> {
&self.manager
}
fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
RuntimeOrDispatch::RuntimeHandle(self.runtime_handle.clone())
}
fn managed_app_handle(&self) -> AppHandle<R> {
self.clone()
}
}
/// The instance of the currently running application.
///
/// This type implements [`Manager`] which allows for manipulation of global application items.
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct App<R: Runtime> {
runtime: Option<R>,
manager: WindowManager<R>,
#[cfg(feature = "global-shortcut")]
global_shortcut_manager: R::GlobalShortcutManager,
#[cfg(feature = "clipboard")]
clipboard_manager: R::ClipboardManager,
#[cfg(feature = "system-tray")]
tray_handle: Option<tray::SystemTrayHandle<R>>,
handle: AppHandle<R>,
}
impl<R: Runtime> Manager<R> for App<R> {}
impl<R: Runtime> ManagerBase<R> for App<R> {
fn manager(&self) -> &WindowManager<R> {
&self.manager
}
fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
RuntimeOrDispatch::Runtime(self.runtime.as_ref().unwrap())
}
fn managed_app_handle(&self) -> AppHandle<R> {
self.handle()
}
}
/// APIs specific to the wry runtime.
#[cfg(feature = "wry")]
impl App<crate::Wry> {
/// Adds a [`tauri_runtime_wry::Plugin`] using its [`tauri_runtime_wry::PluginBuilder`].
///
/// # Stability
///
/// This API is unstable.
pub fn wry_plugin<P: tauri_runtime_wry::PluginBuilder<EventLoopMessage> + 'static>(
&mut self,
plugin: P,
) {
self.runtime.as_mut().unwrap().plugin(plugin);
}
}
macro_rules! shared_app_impl {
($app: ty) => {
impl<R: Runtime> $app {
#[cfg(updater)]
#[cfg_attr(doc_cfg, doc(cfg(feature = "updater")))]
/// Gets the updater builder to manually check if an update is available.
///
/// # Examples
///
/// ```no_run
/// tauri::Builder::default()
/// .setup(|app| {
/// let handle = app.handle();
/// tauri::async_runtime::spawn(async move {
#[cfg_attr(
feature = "updater",
doc = r#" let response = handle.updater().check().await;"#
)]
/// });
/// Ok(())
/// });
/// ```
pub fn updater(&self) -> updater::UpdateBuilder<R> {
updater::builder(self.app_handle())
}
#[cfg(feature = "system-tray")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
/// Gets a handle handle to the system tray.
pub fn tray_handle(&self) -> tray::SystemTrayHandle<R> {
self
.tray_handle
.clone()
.expect("tray not configured; use the `Builder#system_tray` API first.")
}
/// The path resolver for the application.
pub fn path_resolver(&self) -> PathResolver {
PathResolver {
env: self.state::<Env>().inner().clone(),
config: self.manager.config(),
package_info: self.manager.package_info().clone(),
}
}
/// Gets a copy of the global shortcut manager instance.
#[cfg(feature = "global-shortcut")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "global-shortcut")))]
pub fn global_shortcut_manager(&self) -> R::GlobalShortcutManager {
self.global_shortcut_manager.clone()
}
/// Gets a copy of the clipboard manager instance.
#[cfg(feature = "clipboard")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "clipboard")))]
pub fn clipboard_manager(&self) -> R::ClipboardManager {
self.clipboard_manager.clone()
}
/// Gets the app's configuration, defined on the `tauri.conf.json` file.
pub fn config(&self) -> Arc<Config> {
self.manager.config()
}
/// Gets the app's package information.
pub fn package_info(&self) -> &PackageInfo {
self.manager.package_info()
}
/// The application's asset resolver.
pub fn asset_resolver(&self) -> AssetResolver<R> {
AssetResolver {
manager: self.manager.clone(),
}
}
}
};
}
shared_app_impl!(App<R>);
shared_app_impl!(AppHandle<R>);
impl<R: Runtime> App<R> {
/// Gets a handle to the application instance.
pub fn handle(&self) -> AppHandle<R> {
self.handle.clone()
}
/// Sets the activation policy for the application. It is set to `NSApplicationActivationPolicyRegular` by default.
///
/// # Examples
/// ```rust,no_run
/// let mut app = tauri::Builder::default()
/// // on an actual app, remove the string argument
/// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .expect("error while building tauri application");
/// #[cfg(target_os = "macos")]
/// app.set_activation_policy(tauri::ActivationPolicy::Accessory);
/// app.run(|_app_handle, _event| {});
/// ```
#[cfg(target_os = "macos")]
#[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
pub fn set_activation_policy(&mut self, activation_policy: ActivationPolicy) {
self
.runtime
.as_mut()
.unwrap()
.set_activation_policy(activation_policy);
}
/// Gets the argument matches of the CLI definition configured in `tauri.conf.json`.
///
/// # Examples
///
/// ```rust,no_run
/// tauri::Builder::default()
/// .setup(|app| {
/// let matches = app.get_cli_matches()?;
/// Ok(())
/// });
/// ```
#[cfg(cli)]
pub fn get_cli_matches(&self) -> crate::Result<crate::api::cli::Matches> {
if let Some(cli) = &self.manager.config().tauri.cli {
crate::api::cli::get_matches(cli, self.manager.package_info()).map_err(Into::into)
} else {
Ok(Default::default())
}
}
/// Runs the application.
///
/// # Examples
/// ```rust,no_run
/// let app = tauri::Builder::default()
/// // on an actual app, remove the string argument
/// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .expect("error while building tauri application");
/// app.run(|_app_handle, event| match event {
/// tauri::RunEvent::ExitRequested { api, .. } => {
/// api.prevent_exit();
/// }
/// _ => {}
/// });
/// ```
pub fn run<F: FnMut(&AppHandle<R>, RunEvent) + 'static>(mut self, mut callback: F) {
let app_handle = self.handle();
let manager = self.manager.clone();
self.runtime.take().unwrap().run(move |event| match event {
RuntimeRunEvent::Exit => {
on_event_loop_event(
&app_handle,
RuntimeRunEvent::Exit,
&manager,
Some(&mut callback),
);
app_handle.cleanup_before_exit();
}
_ => {
on_event_loop_event(&app_handle, event, &manager, Some(&mut callback));
}
});
}
/// Runs a iteration of the runtime event loop and immediately return.
///
/// Note that when using this API, app cleanup is not automatically done.
/// The cleanup calls [`crate::api::process::kill_children`] so you may want to call that function before exiting the application.
/// Additionally, the cleanup calls [AppHandle#remove_system_tray](`AppHandle#method.remove_system_tray`) (Windows only).
///
/// # Examples
/// ```rust,no_run
/// let mut app = tauri::Builder::default()
/// // on an actual app, remove the string argument
/// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .expect("error while building tauri application");
/// loop {
/// let iteration = app.run_iteration();
/// if iteration.window_count == 0 {
/// break;
/// }
/// }
/// ```
pub fn run_iteration(&mut self) -> crate::runtime::RunIteration {
let manager = self.manager.clone();
let app_handle = self.handle();
self.runtime.as_mut().unwrap().run_iteration(move |event| {
on_event_loop_event(
&app_handle,
event,
&manager,
Option::<&mut Box<dyn FnMut(&AppHandle<R>, RunEvent)>>::None,
)
})
}
}
#[cfg(updater)]
impl<R: Runtime> App<R> {
/// Runs the updater hook with built-in dialog.
fn run_updater_dialog(&self) {
let handle = self.handle();
crate::async_runtime::spawn(async move { updater::check_update_with_dialog(handle).await });
}
fn run_updater(&self) {
let handle = self.handle();
let handle_ = handle.clone();
let updater_config = self.manager.config().tauri.updater.clone();
// check if updater is active or not
if updater_config.active {
if updater_config.dialog {
#[cfg(not(target_os = "linux"))]
let updater_enabled = true;
#[cfg(target_os = "linux")]
let updater_enabled = cfg!(dev) || self.state::<Env>().appimage.is_some();
if updater_enabled {
// if updater dialog is enabled spawn a new task
self.run_updater_dialog();
// When dialog is enabled, if user want to recheck
// if an update is available after first start
// invoke the Event `tauri://update` from JS or rust side.
handle.listen_global(updater::EVENT_CHECK_UPDATE, move |_msg| {
let handle = handle_.clone();
// re-spawn task inside tokyo to launch the download
// we don't need to emit anything as everything is handled
// by the process (user is asked to restart at the end)
// and it's handled by the updater
crate::async_runtime::spawn(
async move { updater::check_update_with_dialog(handle).await },
);
});
}
} else {
// we only listen for `tauri://update`
// once we receive the call, we check if an update is available or not
// if there is a new update we emit `tauri://update-available` with details
// this is the user responsabilities to display dialog and ask if user want to install
// to install the update you need to invoke the Event `tauri://update-install`
updater::listener(handle);
}
}
}
}
/// Builds a Tauri application.
///
/// # Examples
/// ```rust,no_run
/// tauri::Builder::default()
/// // on an actual app, remove the string argument
/// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .expect("error while running tauri application");
/// ```
#[allow(clippy::type_complexity)]
pub struct Builder<R: Runtime> {
/// A flag indicating that the runtime must be started on an environment that supports the event loop not on the main thread.
#[cfg(any(windows, target_os = "linux"))]
runtime_any_thread: bool,
/// The JS message handler.
invoke_handler: Box<InvokeHandler<R>>,
/// The JS message responder.
invoke_responder: Arc<InvokeResponder<R>>,
/// The script that initializes the `window.__TAURI_POST_MESSAGE__` function.
invoke_initialization_script: String,
/// The setup hook.
setup: SetupHook<R>,
/// Page load hook.
on_page_load: Box<OnPageLoad<R>>,
/// windows to create when starting up.
pending_windows: Vec<PendingWindow<EventLoopMessage, R>>,
/// All passed plugins
plugins: PluginStore<R>,
/// The webview protocols available to all windows.
uri_scheme_protocols: HashMap<String, Arc<CustomProtocol<R>>>,
/// App state.
state: StateManager,
/// The menu set to all windows.
menu: Option<Menu>,
/// Enable macOS default menu creation.
#[allow(unused)]
enable_macos_default_menu: bool,
/// Menu event handlers that listens to all windows.
menu_event_listeners: Vec<GlobalMenuEventListener<R>>,
/// Window event handlers that listens to all windows.
window_event_listeners: Vec<GlobalWindowEventListener<R>>,
/// The app system tray.
#[cfg(feature = "system-tray")]
system_tray: Option<tray::SystemTray>,
/// System tray event handlers.
#[cfg(feature = "system-tray")]
system_tray_event_listeners: Vec<SystemTrayEventListener<R>>,
/// The updater configuration.
#[cfg(updater)]
updater_settings: UpdaterSettings,
}
impl<R: Runtime> Builder<R> {
/// Creates a new App builder.
pub fn new() -> Self {
Self {
#[cfg(any(windows, target_os = "linux"))]
runtime_any_thread: false,
setup: Box::new(|_| Ok(())),
invoke_handler: Box::new(|invoke| invoke.resolver.reject("not implemented")),
invoke_responder: Arc::new(window_invoke_responder),
invoke_initialization_script:
"Object.defineProperty(window, '__TAURI_POST_MESSAGE__', { value: (message) => window.ipc.postMessage(JSON.stringify(message)) })".into(),
on_page_load: Box::new(|_, _| ()),
pending_windows: Default::default(),
plugins: PluginStore::default(),
uri_scheme_protocols: Default::default(),
state: StateManager::new(),
menu: None,
enable_macos_default_menu: true,
menu_event_listeners: Vec::new(),
window_event_listeners: Vec::new(),
#[cfg(feature = "system-tray")]
system_tray: None,
#[cfg(feature = "system-tray")]
system_tray_event_listeners: Vec::new(),
#[cfg(updater)]
updater_settings: Default::default(),
}
}
/// Builds a new Tauri application running on any thread, bypassing the main thread requirement.
///
/// ## Platform-specific
///
/// - **macOS:** on macOS the application *must* be executed on the main thread, so this function is not exposed.
#[cfg(any(windows, target_os = "linux"))]
#[cfg_attr(doc_cfg, doc(cfg(any(windows, target_os = "linux"))))]
#[must_use]
pub fn any_thread(mut self) -> Self {
self.runtime_any_thread = true;
self
}
/// Defines the JS message handler callback.
///
/// # Examples
/// ```rust,no_run
/// #[tauri::command]
/// fn command_1() -> String {
/// return "hello world".to_string();
/// }
/// tauri::Builder::default()
/// .invoke_handler(tauri::generate_handler![
/// command_1,
/// // etc...
/// ]);
/// ```
#[must_use]
pub fn invoke_handler<F>(mut self, invoke_handler: F) -> Self
where
F: Fn(Invoke<R>) + Send + Sync + 'static,
{
self.invoke_handler = Box::new(invoke_handler);
self
}
/// Defines a custom JS message system.
///
/// The `responder` is a function that will be called when a command has been executed and must send a response to the JS layer.
///
/// The `initialization_script` is a script that initializes `window.__TAURI_POST_MESSAGE__`.
/// That function must take the `message: object` argument and send it to the backend.
#[must_use]
pub fn invoke_system<F>(mut self, initialization_script: String, responder: F) -> Self
where
F: Fn(Window<R>, InvokeResponse, CallbackFn, CallbackFn) + Send + Sync + 'static,
{
self.invoke_initialization_script = initialization_script;
self.invoke_responder = Arc::new(responder);
self
}
/// Defines the setup hook.
///
/// # Examples
/// ```rust,no_run
/// use tauri::Manager;
/// tauri::Builder::default()
/// .setup(|app| {
/// let main_window = app.get_window("main").unwrap();
#[cfg_attr(
feature = "dialog",
doc = r#" tauri::api::dialog::blocking::message(Some(&main_window), "Hello", "Welcome back!");"#
)]
/// Ok(())
/// });
/// ```
#[must_use]
pub fn setup<F>(mut self, setup: F) -> Self
where
F: FnOnce(&mut App<R>) -> Result<(), Box<dyn std::error::Error>> + Send + 'static,
{
self.setup = Box::new(setup);
self