-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
app.rs
1921 lines (1758 loc) · 58.8 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-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
image::Image,
ipc::{
channel::ChannelDataIpcQueue, CallbackFn, CommandArg, CommandItem, Invoke, InvokeError,
InvokeHandler, InvokeResponder, InvokeResponse,
},
manager::{
webview::{UriSchemeProtocol, WebviewLabelDef},
AppManager, Asset,
},
plugin::{Plugin, PluginStore},
runtime::{
window::{WebviewEvent as RuntimeWebviewEvent, WindowEvent as RuntimeWindowEvent},
ExitRequestedEventAction, RunEvent as RuntimeRunEvent,
},
sealed::{ManagerBase, RuntimeOrDispatch},
utils::config::Config,
utils::Env,
webview::PageLoadPayload,
Context, DeviceEventFilter, EventLoopMessage, Manager, Monitor, Runtime, Scopes, StateManager,
Theme, Webview, WebviewWindowBuilder, Window,
};
#[cfg(desktop)]
use crate::menu::{Menu, MenuEvent};
#[cfg(all(desktop, feature = "tray-icon"))]
use crate::tray::{TrayIcon, TrayIconBuilder, TrayIconEvent, TrayIconId};
use raw_window_handle::HasDisplayHandle;
use serialize_to_javascript::{default_template, DefaultTemplate, Template};
use tauri_macros::default_runtime;
#[cfg(desktop)]
use tauri_runtime::EventLoopProxy;
use tauri_runtime::{
dpi::{PhysicalPosition, PhysicalSize},
window::DragDropEvent,
RuntimeInitArgs,
};
use tauri_utils::PackageInfo;
use std::{
borrow::Cow,
collections::HashMap,
fmt,
sync::{mpsc::Sender, Arc},
};
use crate::{event::EventId, runtime::RuntimeHandle, Event, EventTarget};
#[cfg(target_os = "macos")]
use crate::ActivationPolicy;
pub(crate) mod plugin;
#[cfg(desktop)]
pub(crate) type GlobalMenuEventListener<T> = Box<dyn Fn(&T, crate::menu::MenuEvent) + Send + Sync>;
#[cfg(all(desktop, feature = "tray-icon"))]
pub(crate) type GlobalTrayIconEventListener<T> =
Box<dyn Fn(&T, crate::tray::TrayIconEvent) + Send + Sync>;
pub(crate) type GlobalWindowEventListener<R> = Box<dyn Fn(&Window<R>, &WindowEvent) + Send + Sync>;
pub(crate) type GlobalWebviewEventListener<R> =
Box<dyn Fn(&Webview<R>, &WebviewEvent) + Send + Sync>;
/// A closure that is run when the Tauri application is setting up.
pub type SetupHook<R> =
Box<dyn FnOnce(&mut App<R>) -> Result<(), Box<dyn std::error::Error>> + Send>;
/// A closure that is run every time a page starts or finishes loading.
pub type OnPageLoad<R> = dyn Fn(&Webview<R>, &PageLoadPayload<'_>) + Send + Sync + 'static;
/// The exit code on [`RunEvent::ExitRequested`] when [`AppHandle#method.restart`] is called.
pub const RESTART_EXIT_CODE: i32 = i32::MAX;
/// Api exposed on the `ExitRequested` event.
#[derive(Debug)]
pub struct ExitRequestApi(Sender<ExitRequestedEventAction>);
impl ExitRequestApi {
/// Prevents the app from exiting.
///
/// **Note:** This is ignored when using [`AppHandle#method.restart`].
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 drag and drop action.
DragDrop(DragDropEvent),
/// The system window theme has changed. Only delivered if the window [`theme`](`crate::window::WindowBuilder#method.theme`) is `None`.
///
/// 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
///
/// - **Linux**: Not supported.
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::DragDrop(event) => Self::DragDrop(event),
RuntimeWindowEvent::ThemeChanged(theme) => Self::ThemeChanged(theme),
}
}
}
/// An event from a window.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum WebviewEvent {
/// An event associated with the drag and drop action.
DragDrop(DragDropEvent),
}
impl From<RuntimeWebviewEvent> for WebviewEvent {
fn from(event: RuntimeWebviewEvent) -> Self {
match event {
RuntimeWebviewEvent::DragDrop(e) => Self::DragDrop(e),
}
}
}
/// An application event, triggered from the event loop.
///
/// See [`App::run`](crate::App#method.run) for usage examples.
#[derive(Debug)]
#[non_exhaustive]
pub enum RunEvent {
/// Event loop is exiting.
Exit,
/// The app is about to exit
#[non_exhaustive]
ExitRequested {
/// Exit code.
/// [`Option::None`] when the exit is requested by user interaction,
/// [`Option::Some`] when requested programmatically via [`AppHandle#method.exit`] and [`AppHandle#method.restart`].
code: Option<i32>,
/// Event API
api: ExitRequestApi,
},
/// An event associated with a window.
#[non_exhaustive]
WindowEvent {
/// The window label.
label: String,
/// The detailed event.
event: WindowEvent,
},
/// An event associated with a webview.
#[non_exhaustive]
WebviewEvent {
/// The window label.
label: String,
/// The detailed event.
event: WebviewEvent,
},
/// 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,
/// Emitted when the user wants to open the specified resource with the app.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", feature = "ios"))))]
Opened {
/// The URL of the resources that is being open.
urls: Vec<url::Url>,
},
/// An event from a menu item, could be on the window menu bar, application menu bar (on macOS) or tray icon menu.
#[cfg(desktop)]
#[cfg_attr(docsrs, doc(cfg(desktop)))]
MenuEvent(crate::menu::MenuEvent),
/// An event from a tray icon.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
TrayIconEvent(crate::tray::TrayIconEvent),
}
impl From<EventLoopMessage> for RunEvent {
fn from(event: EventLoopMessage) -> Self {
match event {
#[cfg(desktop)]
EventLoopMessage::MenuEvent(e) => Self::MenuEvent(e),
#[cfg(all(desktop, feature = "tray-icon"))]
EventLoopMessage::TrayIconEvent(e) => Self::TrayIconEvent(e),
}
}
}
/// The asset resolver is a helper to access the [`tauri_utils::assets::Assets`] interface.
#[derive(Debug, Clone)]
pub struct AssetResolver<R: Runtime> {
manager: Arc<AppManager<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()
}
/// Iterate on all assets.
pub fn iter(&self) -> Box<dyn Iterator<Item = (&str, &[u8])> + '_> {
self.manager.assets.iter()
}
}
/// 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> {
pub(crate) runtime_handle: R::Handle,
pub(crate) manager: Arc<AppManager<R>>,
}
/// 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::TaoWindowBuilder) + Send + 'static,
>(
&self,
f: F,
) -> crate::Result<std::sync::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::TaoWindowId,
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(),
}
}
}
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.webview().window().app_handle.clone())
}
}
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)
}
/// 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().clone();
/// std::thread::spawn(move || {
/// handle.plugin(init_plugin());
/// });
///
/// Ok(())
/// });
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(name = "app::plugin::register", skip(plugin), fields(name = plugin.name())))]
pub fn plugin<P: Plugin<R> + 'static>(&self, plugin: P) -> crate::Result<()> {
let mut plugin = Box::new(plugin) as Box<dyn Plugin<R>>;
let mut store = self.manager().plugins.lock().unwrap();
store.initialize(&mut plugin, self, &self.config().plugins)?;
store.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().clone();
/// std::thread::spawn(move || {
/// handle.remove_plugin(plugin_name);
/// });
///
/// Ok(())
/// });
/// ```
pub fn remove_plugin(&self, plugin: &'static str) -> bool {
self.manager().plugins.lock().unwrap().unregister(plugin)
}
/// Exits the app by triggering [`RunEvent::ExitRequested`] and [`RunEvent::Exit`].
pub fn exit(&self, exit_code: i32) {
if let Err(e) = self.runtime_handle.request_exit(exit_code) {
log::error!("failed to exit: {}", e);
self.cleanup_before_exit();
std::process::exit(exit_code);
}
}
/// Restarts the app by triggering [`RunEvent::ExitRequested`] with code [`RESTART_EXIT_CODE`] and [`RunEvent::Exit`]..
pub fn restart(&self) {
if self.runtime_handle.request_exit(RESTART_EXIT_CODE).is_err() {
self.cleanup_before_exit();
}
crate::process::restart(&self.env());
}
}
impl<R: Runtime> Manager<R> for AppHandle<R> {}
impl<R: Runtime> ManagerBase<R> for AppHandle<R> {
fn manager(&self) -> &AppManager<R> {
&self.manager
}
fn manager_owned(&self) -> Arc<AppManager<R>> {
self.manager.clone()
}
fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
RuntimeOrDispatch::RuntimeHandle(self.runtime_handle.clone())
}
fn managed_app_handle(&self) -> &AppHandle<R> {
self
}
}
/// The instance of the currently running application.
///
/// This type implements [`Manager`] which allows for manipulation of global application items.
#[default_runtime(crate::Wry, wry)]
pub struct App<R: Runtime> {
runtime: Option<R>,
setup: Option<SetupHook<R>>,
manager: Arc<AppManager<R>>,
handle: AppHandle<R>,
ran_setup: bool,
}
impl<R: Runtime> fmt::Debug for App<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("App")
.field("runtime", &self.runtime)
.field("manager", &self.manager)
.field("handle", &self.handle)
.finish()
}
}
impl<R: Runtime> Manager<R> for App<R> {}
impl<R: Runtime> ManagerBase<R> for App<R> {
fn manager(&self) -> &AppManager<R> {
&self.manager
}
fn manager_owned(&self) -> Arc<AppManager<R>> {
self.manager.clone()
}
fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
if let Some(runtime) = self.runtime.as_ref() {
RuntimeOrDispatch::Runtime(runtime)
} else {
self.handle.runtime()
}
}
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> + Send + 'static>(
&mut self,
plugin: P,
) where
<P as tauri_runtime_wry::PluginBuilder<EventLoopMessage>>::Plugin: Send,
{
self.handle.runtime_handle.plugin(plugin);
}
}
macro_rules! shared_app_impl {
($app: ty) => {
impl<R: Runtime> $app {
/// Registers a global menu event listener.
#[cfg(desktop)]
pub fn on_menu_event<F: Fn(&AppHandle<R>, MenuEvent) + Send + Sync + 'static>(
&self,
handler: F,
) {
self.manager.menu.on_menu_event(handler)
}
/// Registers a global tray icon menu event listener.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
pub fn on_tray_icon_event<F: Fn(&AppHandle<R>, TrayIconEvent) + Send + Sync + 'static>(
&self,
handler: F,
) {
self.manager.tray.on_tray_icon_event(handler)
}
/// Gets a tray icon using the provided id.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
pub fn tray_by_id<'a, I>(&self, id: &'a I) -> Option<TrayIcon<R>>
where
I: ?Sized,
TrayIconId: PartialEq<&'a I>,
{
self.manager.tray.tray_by_id(id)
}
/// Removes a tray icon using the provided id from tauri's internal state and returns it.
///
/// Note that dropping the returned icon, may cause the tray icon to disappear
/// if it wasn't cloned somewhere else or referenced by JS.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
pub fn remove_tray_by_id<'a, I>(&self, id: &'a I) -> Option<TrayIcon<R>>
where
I: ?Sized,
TrayIconId: PartialEq<&'a I>,
{
self.manager.tray.remove_tray_by_id(id)
}
/// Gets the app's configuration, defined on the `tauri.conf.json` file.
pub fn config(&self) -> &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(),
}
}
/// Returns the primary monitor of the system.
///
/// Returns None if it can't identify any monitor as a primary one.
pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
Ok(match self.runtime() {
RuntimeOrDispatch::Runtime(h) => h.primary_monitor().map(Into::into),
RuntimeOrDispatch::RuntimeHandle(h) => h.primary_monitor().map(Into::into),
_ => unreachable!(),
})
}
/// Returns the list of all the monitors available on the system.
pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
Ok(match self.runtime() {
RuntimeOrDispatch::Runtime(h) => {
h.available_monitors().into_iter().map(Into::into).collect()
}
RuntimeOrDispatch::RuntimeHandle(h) => {
h.available_monitors().into_iter().map(Into::into).collect()
}
_ => unreachable!(),
})
}
/// Get the cursor position relative to the top-left hand corner of the main monitor.
pub fn cursor_position(&self) -> crate::Result<PhysicalPosition<f64>> {
Ok(match self.runtime() {
RuntimeOrDispatch::Runtime(h) => h.cursor_position()?,
RuntimeOrDispatch::RuntimeHandle(h) => h.cursor_position()?,
_ => unreachable!(),
})
}
/// Returns the default window icon.
pub fn default_window_icon(&self) -> Option<&Image<'_>> {
self.manager.window.default_icon.as_ref()
}
/// Returns the app-wide menu.
#[cfg(desktop)]
pub fn menu(&self) -> Option<Menu<R>> {
self.manager.menu.menu_lock().clone()
}
/// Sets the app-wide menu and returns the previous one.
///
/// If a window was not created with an explicit menu or had one set explicitly,
/// this menu will be assigned to it.
#[cfg(desktop)]
pub fn set_menu(&self, menu: Menu<R>) -> crate::Result<Option<Menu<R>>> {
let prev_menu = self.remove_menu()?;
self.manager.menu.insert_menu_into_stash(&menu);
self.manager.menu.menu_lock().replace(menu.clone());
// set it on all windows that don't have one or previously had the app-wide menu
#[cfg(not(target_os = "macos"))]
{
for window in self.manager.windows().values() {
let has_app_wide_menu = window.has_app_wide_menu() || window.menu().is_none();
if has_app_wide_menu {
window.set_menu(menu.clone())?;
window.menu_lock().replace(crate::window::WindowMenu {
is_app_wide: true,
menu: menu.clone(),
});
}
}
}
// set it app-wide for macos
#[cfg(target_os = "macos")]
{
let menu_ = menu.clone();
self.run_on_main_thread(move || {
let _ = init_app_menu(&menu_);
})?;
}
Ok(prev_menu)
}
/// Remove the app-wide menu and returns it.
///
/// If a window was not created with an explicit menu or had one set explicitly,
/// this will remove the menu from it.
#[cfg(desktop)]
pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
let menu = self.manager.menu.menu_lock().as_ref().cloned();
#[allow(unused_variables)]
if let Some(menu) = menu {
// remove from windows that have the app-wide menu
#[cfg(not(target_os = "macos"))]
{
for window in self.manager.windows().values() {
let has_app_wide_menu = window.has_app_wide_menu();
if has_app_wide_menu {
window.remove_menu()?;
*window.menu_lock() = None;
}
}
}
// remove app-wide for macos
#[cfg(target_os = "macos")]
{
self.run_on_main_thread(move || {
menu.inner().remove_for_nsapp();
})?;
}
}
let prev_menu = self.manager.menu.menu_lock().take();
self
.manager
.remove_menu_from_stash_by_id(prev_menu.as_ref().map(|m| m.id()));
Ok(prev_menu)
}
/// Hides the app-wide menu from windows that have it.
///
/// If a window was not created with an explicit menu or had one set explicitly,
/// this will hide the menu from it.
#[cfg(desktop)]
pub fn hide_menu(&self) -> crate::Result<()> {
#[cfg(not(target_os = "macos"))]
{
let is_app_menu_set = self.manager.menu.menu_lock().is_some();
if is_app_menu_set {
for window in self.manager.windows().values() {
if window.has_app_wide_menu() {
window.hide_menu()?;
}
}
}
}
Ok(())
}
/// Shows the app-wide menu for windows that have it.
///
/// If a window was not created with an explicit menu or had one set explicitly,
/// this will show the menu for it.
#[cfg(desktop)]
pub fn show_menu(&self) -> crate::Result<()> {
#[cfg(not(target_os = "macos"))]
{
let is_app_menu_set = self.manager.menu.menu_lock().is_some();
if is_app_menu_set {
for window in self.manager.windows().values() {
if window.has_app_wide_menu() {
window.show_menu()?;
}
}
}
}
Ok(())
}
/// Shows the application, but does not automatically focus it.
#[cfg(target_os = "macos")]
pub fn show(&self) -> crate::Result<()> {
match self.runtime() {
RuntimeOrDispatch::Runtime(r) => r.show(),
RuntimeOrDispatch::RuntimeHandle(h) => h.show()?,
_ => unreachable!(),
}
Ok(())
}
/// Hides the application.
#[cfg(target_os = "macos")]
pub fn hide(&self) -> crate::Result<()> {
match self.runtime() {
RuntimeOrDispatch::Runtime(r) => r.hide(),
RuntimeOrDispatch::RuntimeHandle(h) => h.hide()?,
_ => unreachable!(),
}
Ok(())
}
/// Runs necessary cleanup tasks before exiting the process.
/// **You should always exit the tauri app immediately after this function returns and not use any tauri-related APIs.**
pub fn cleanup_before_exit(&self) {
#[cfg(all(desktop, feature = "tray-icon"))]
self.manager.tray.icons.lock().unwrap().clear();
self.resources_table().clear();
}
}
/// Event system APIs.
impl<R: Runtime> $app {
/// Listen to an event on this app.
///
/// # Examples
///
/// ```
/// use tauri::Manager;
///
/// tauri::Builder::default()
/// .setup(|app| {
/// app.listen("component-loaded", move |event| {
/// println!("window just loaded a component");
/// });
///
/// Ok(())
/// });
/// ```
pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
where
F: Fn(Event) + Send + 'static,
{
self.manager.listen(event.into(), EventTarget::App, handler)
}
/// Unlisten to an event on this app.
///
/// # Examples
///
/// ```
/// use tauri::Manager;
///
/// tauri::Builder::default()
/// .setup(|app| {
/// let handler = app.listen("component-loaded", move |event| {
/// println!("app just loaded a component");
/// });
///
/// // stop listening to the event when you do not need it anymore
/// app.unlisten(handler);
///
/// Ok(())
/// });
/// ```
pub fn unlisten(&self, id: EventId) {
self.manager.unlisten(id)
}
/// Listen to an event on this app only once.
///
/// See [`Self::listen`] for more information.
pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
where
F: FnOnce(Event) + Send + 'static,
{
self.manager.once(event.into(), EventTarget::App, handler)
}
}
};
}
shared_app_impl!(App<R>);
shared_app_impl!(AppHandle<R>);
impl<R: Runtime> App<R> {
#[cfg_attr(
feature = "tracing",
tracing::instrument(name = "app::core_plugins::register")
)]
fn register_core_plugins(&self) -> crate::Result<()> {
self.handle.plugin(crate::path::plugin::init())?;
self.handle.plugin(crate::event::plugin::init())?;
self.handle.plugin(crate::window::plugin::init())?;
self.handle.plugin(crate::webview::plugin::init())?;
self.handle.plugin(crate::app::plugin::init())?;
self.handle.plugin(crate::resources::plugin::init())?;
self.handle.plugin(crate::image::plugin::init())?;
#[cfg(desktop)]
self.handle.plugin(crate::menu::plugin::init())?;
#[cfg(all(desktop, feature = "tray-icon"))]
self.handle.plugin(crate::tray::plugin::init())?;
Ok(())
}
/// Runs the given closure on the main thread.
pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
self.app_handle().run_on_main_thread(f)
}
/// Gets a handle to the application instance.
pub fn handle(&self) -> &AppHandle<R> {
&self.handle
}
/// Sets the activation policy for the application. It is set to `NSApplicationActivationPolicyRegular` by default.
///
/// # Examples
/// ```,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(docsrs, doc(cfg(target_os = "macos")))]
pub fn set_activation_policy(&mut self, activation_policy: ActivationPolicy) {
if let Some(runtime) = self.runtime.as_mut() {
runtime.set_activation_policy(activation_policy);
} else {
let _ = self
.app_handle()
.runtime_handle
.set_activation_policy(activation_policy);
}
}
/// Change the device event filter mode.
///
/// Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, [`tao`]
/// will ignore them by default for unfocused windows on Windows. This method allows changing
/// the filter to explicitly capture them again.
///
/// ## Platform-specific
///
/// - ** Linux / macOS / iOS / Android**: Unsupported.
///
/// # Examples
/// ```,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");
/// app.set_device_event_filter(tauri::DeviceEventFilter::Always);
/// app.run(|_app_handle, _event| {});
/// ```
///
/// [`tao`]: https://crates.io/crates/tao
pub fn set_device_event_filter(&mut self, filter: DeviceEventFilter) {
self
.runtime
.as_mut()
.unwrap()
.set_device_event_filter(filter);
}
/// Runs the application.
///
/// # Examples
/// ```,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().clone();
let manager = self.manager.clone();
self.runtime.take().unwrap().run(move |event| match event {
RuntimeRunEvent::Ready => {
if let Err(e) = setup(&mut self) {
panic!("Failed to setup app: {e}");
}
let event = on_event_loop_event(&app_handle, RuntimeRunEvent::Ready, &manager);
callback(&app_handle, event);
}
RuntimeRunEvent::Exit => {
let event = on_event_loop_event(&app_handle, RuntimeRunEvent::Exit, &manager);
callback(&app_handle, event);
app_handle.cleanup_before_exit();
}
_ => {
let event = on_event_loop_event(&app_handle, event, &manager);
callback(&app_handle, event);
}
});
}
/// Runs an iteration of the runtime event loop and immediately return.
///
/// Note that when using this API, app cleanup is not automatically done.
/// The cleanup calls [`App::cleanup_before_exit`] so you may want to call that function before exiting the application.
///
/// # Examples
/// ```no_run
/// use tauri::Manager;
///
/// 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 {
/// app.run_iteration(|_app, _event| {});
/// if app.webview_windows().is_empty() {
/// app.cleanup_before_exit();
/// break;
/// }
/// }
/// ```
#[cfg(desktop)]
pub fn run_iteration<F: FnMut(&AppHandle<R>, RunEvent) + 'static>(&mut self, mut callback: F) {
let manager = self.manager.clone();
let app_handle = self.handle().clone();
if !self.ran_setup {
if let Err(e) = setup(self) {
panic!("Failed to setup app: {e}");
}
}
self.runtime.as_mut().unwrap().run_iteration(move |event| {
let event = on_event_loop_event(&app_handle, event, &manager);
callback(&app_handle, event);
})
}
}
/// Builds a Tauri application.
///
/// # Examples
/// ```,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,