Expand description
The instance of the currently running application.
This type implements Manager
which allows for manipulation of global application items.
Implementations§
source§impl App<Wry>
impl App<Wry>
APIs specific to the wry runtime.
sourcepub fn wry_plugin<P: PluginBuilder<EventLoopMessage> + 'static>(
&mut self,
plugin: P
)
pub fn wry_plugin<P: PluginBuilder<EventLoopMessage> + 'static>(
&mut self,
plugin: P
)
Adds a tauri_runtime_wry::Plugin
using its tauri_runtime_wry::PluginBuilder
.
Stability
This API is unstable.
source§impl<R: Runtime> App<R>
impl<R: Runtime> App<R>
sourcepub fn updater(&self) -> UpdateBuilder<R>
Available on crate feature updater
only.
pub fn updater(&self) -> UpdateBuilder<R>
updater
only.Gets the updater builder to manually check if an update is available.
Examples
tauri::Builder::default()
.setup(|app| {
let handle = app.handle();
tauri::async_runtime::spawn(async move {
let response = handle.updater().check().await;
});
Ok(())
});
sourcepub fn tray_handle(&self) -> SystemTrayHandle<R>
Available on crate feature system-tray
only.
pub fn tray_handle(&self) -> SystemTrayHandle<R>
system-tray
only.Gets a handle to the first system tray.
Prefer Self::tray_handle_by_id
when multiple system trays are created.
Examples
use tauri::{CustomMenuItem, SystemTray, SystemTrayMenu};
tauri::Builder::default()
.setup(|app| {
let app_handle = app.handle();
SystemTray::new()
.with_menu(
SystemTrayMenu::new()
.add_item(CustomMenuItem::new("quit", "Quit"))
.add_item(CustomMenuItem::new("open", "Open"))
)
.on_event(move |event| {
let tray_handle = app_handle.tray_handle();
})
.build(app)?;
Ok(())
});
sourcepub fn tray_handle_by_id(&self, id: &str) -> Option<SystemTrayHandle<R>>
Available on crate feature system-tray
only.
pub fn tray_handle_by_id(&self, id: &str) -> Option<SystemTrayHandle<R>>
system-tray
only.Gets a handle to a system tray by its id.
use tauri::{CustomMenuItem, SystemTray, SystemTrayMenu};
tauri::Builder::default()
.setup(|app| {
let app_handle = app.handle();
let tray_id = "my-tray";
SystemTray::new()
.with_id(tray_id)
.with_menu(
SystemTrayMenu::new()
.add_item(CustomMenuItem::new("quit", "Quit"))
.add_item(CustomMenuItem::new("open", "Open"))
)
.on_event(move |event| {
let tray_handle = app_handle.tray_handle_by_id(tray_id).unwrap();
})
.build(app)?;
Ok(())
});
sourcepub fn path_resolver(&self) -> PathResolver
pub fn path_resolver(&self) -> PathResolver
The path resolver for the application.
sourcepub fn global_shortcut_manager(&self) -> R::GlobalShortcutManager
Available on crate feature global-shortcut
only.
pub fn global_shortcut_manager(&self) -> R::GlobalShortcutManager
global-shortcut
only.Gets a copy of the global shortcut manager instance.
sourcepub fn clipboard_manager(&self) -> R::ClipboardManager
Available on crate feature clipboard
only.
pub fn clipboard_manager(&self) -> R::ClipboardManager
clipboard
only.Gets a copy of the clipboard manager instance.
sourcepub fn config(&self) -> Arc<Config>
pub fn config(&self) -> Arc<Config>
Gets the app’s configuration, defined on the tauri.conf.json
file.
Examples found in repository?
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
pub fn build<A: Assets>(mut self, context: Context<A>) -> crate::Result<App<R>> {
#[cfg(target_os = "macos")]
if self.menu.is_none() && self.enable_macos_default_menu {
self.menu = Some(Menu::os_default(&context.package_info().name));
}
#[cfg(shell_scope)]
let shell_scope = context.shell_scope.clone();
let manager = WindowManager::with_handlers(
context,
self.plugins,
self.invoke_handler,
self.on_page_load,
self.uri_scheme_protocols,
self.state,
self.window_event_listeners,
(self.menu, self.menu_event_listeners),
(self.invoke_responder, self.invoke_initialization_script),
);
// set up all the windows defined in the config
for config in manager.config().tauri.windows.clone() {
let url = config.url.clone();
let label = config.label.clone();
let mut webview_attributes =
WebviewAttributes::new(url).accept_first_mouse(config.accept_first_mouse);
if let Some(ua) = &config.user_agent {
webview_attributes = webview_attributes.user_agent(&ua.to_string());
}
if !config.file_drop_enabled {
webview_attributes = webview_attributes.disable_file_drop_handler();
}
self.pending_windows.push(PendingWindow::with_config(
config,
webview_attributes,
label,
)?);
}
#[cfg(any(windows, target_os = "linux"))]
let runtime = if self.runtime_any_thread {
R::new_any_thread()?
} else {
R::new()?
};
#[cfg(not(any(windows, target_os = "linux")))]
let runtime = R::new()?;
let runtime_handle = runtime.handle();
#[cfg(all(desktop, feature = "global-shortcut"))]
let global_shortcut_manager = runtime.global_shortcut_manager();
#[cfg(feature = "clipboard")]
let clipboard_manager = runtime.clipboard_manager();
let mut app = App {
runtime: Some(runtime),
manager: manager.clone(),
#[cfg(all(desktop, feature = "global-shortcut"))]
global_shortcut_manager: global_shortcut_manager.clone(),
#[cfg(feature = "clipboard")]
clipboard_manager: clipboard_manager.clone(),
handle: AppHandle {
runtime_handle,
manager,
#[cfg(all(desktop, feature = "global-shortcut"))]
global_shortcut_manager,
#[cfg(feature = "clipboard")]
clipboard_manager,
#[cfg(updater)]
updater_settings: self.updater_settings,
},
};
let env = Env::default();
app.manage(Scopes {
fs: FsScope::for_fs_api(
&app.manager.config(),
app.package_info(),
&env,
&app.config().tauri.allowlist.fs.scope,
)?,
#[cfg(protocol_asset)]
asset_protocol: FsScope::for_fs_api(
&app.manager.config(),
app.package_info(),
&env,
&app.config().tauri.allowlist.protocol.asset_scope,
)?,
#[cfg(http_request)]
http: crate::scope::HttpScope::for_http_api(&app.config().tauri.allowlist.http.scope),
#[cfg(shell_scope)]
shell: ShellScope::new(&app.manager.config(), app.package_info(), &env, shell_scope),
});
app.manage(env);
#[cfg(windows)]
{
if let crate::utils::config::WebviewInstallMode::FixedRuntime { path } = &app
.manager
.config()
.tauri
.bundle
.windows
.webview_install_mode
{
if let Some(resource_dir) = app.path_resolver().resource_dir() {
std::env::set_var(
"WEBVIEW2_BROWSER_EXECUTABLE_FOLDER",
resource_dir.join(path),
);
} else {
#[cfg(debug_assertions)]
eprintln!(
"failed to resolve resource directory; fallback to the installed Webview2 runtime."
);
}
}
}
#[cfg(all(desktop, feature = "system-tray"))]
{
if let Some(tray) = self.system_tray {
tray.build(&app)?;
}
for listener in self.system_tray_event_listeners {
let app_handle = app.handle();
let listener = Arc::new(std::sync::Mutex::new(listener));
app
.runtime
.as_mut()
.unwrap()
.on_system_tray_event(move |tray_id, event| {
if let Some((tray_id, tray)) = app_handle.manager().get_tray_by_runtime_id(tray_id) {
let app_handle = app_handle.clone();
let event = tray::SystemTrayEvent::from_runtime_event(event, tray_id, &tray.ids);
let listener = listener.clone();
listener.lock().unwrap()(&app_handle, event);
}
});
}
}
app.manager.initialize_plugins(&app.handle())?;
let window_labels = self
.pending_windows
.iter()
.map(|p| p.label.clone())
.collect::<Vec<_>>();
for pending in self.pending_windows {
let pending =
app
.manager
.prepare_window(app.handle.clone(), pending, &window_labels, None)?;
let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
let _window = app.manager.attach_window(app.handle(), detached);
}
(self.setup)(&mut app).map_err(|e| crate::Error::Setup(e.into()))?;
#[cfg(updater)]
app.run_updater();
Ok(app)
}
sourcepub fn package_info(&self) -> &PackageInfo
pub fn package_info(&self) -> &PackageInfo
Gets the app’s package information.
Examples found in repository?
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
pub fn build<A: Assets>(mut self, context: Context<A>) -> crate::Result<App<R>> {
#[cfg(target_os = "macos")]
if self.menu.is_none() && self.enable_macos_default_menu {
self.menu = Some(Menu::os_default(&context.package_info().name));
}
#[cfg(shell_scope)]
let shell_scope = context.shell_scope.clone();
let manager = WindowManager::with_handlers(
context,
self.plugins,
self.invoke_handler,
self.on_page_load,
self.uri_scheme_protocols,
self.state,
self.window_event_listeners,
(self.menu, self.menu_event_listeners),
(self.invoke_responder, self.invoke_initialization_script),
);
// set up all the windows defined in the config
for config in manager.config().tauri.windows.clone() {
let url = config.url.clone();
let label = config.label.clone();
let mut webview_attributes =
WebviewAttributes::new(url).accept_first_mouse(config.accept_first_mouse);
if let Some(ua) = &config.user_agent {
webview_attributes = webview_attributes.user_agent(&ua.to_string());
}
if !config.file_drop_enabled {
webview_attributes = webview_attributes.disable_file_drop_handler();
}
self.pending_windows.push(PendingWindow::with_config(
config,
webview_attributes,
label,
)?);
}
#[cfg(any(windows, target_os = "linux"))]
let runtime = if self.runtime_any_thread {
R::new_any_thread()?
} else {
R::new()?
};
#[cfg(not(any(windows, target_os = "linux")))]
let runtime = R::new()?;
let runtime_handle = runtime.handle();
#[cfg(all(desktop, feature = "global-shortcut"))]
let global_shortcut_manager = runtime.global_shortcut_manager();
#[cfg(feature = "clipboard")]
let clipboard_manager = runtime.clipboard_manager();
let mut app = App {
runtime: Some(runtime),
manager: manager.clone(),
#[cfg(all(desktop, feature = "global-shortcut"))]
global_shortcut_manager: global_shortcut_manager.clone(),
#[cfg(feature = "clipboard")]
clipboard_manager: clipboard_manager.clone(),
handle: AppHandle {
runtime_handle,
manager,
#[cfg(all(desktop, feature = "global-shortcut"))]
global_shortcut_manager,
#[cfg(feature = "clipboard")]
clipboard_manager,
#[cfg(updater)]
updater_settings: self.updater_settings,
},
};
let env = Env::default();
app.manage(Scopes {
fs: FsScope::for_fs_api(
&app.manager.config(),
app.package_info(),
&env,
&app.config().tauri.allowlist.fs.scope,
)?,
#[cfg(protocol_asset)]
asset_protocol: FsScope::for_fs_api(
&app.manager.config(),
app.package_info(),
&env,
&app.config().tauri.allowlist.protocol.asset_scope,
)?,
#[cfg(http_request)]
http: crate::scope::HttpScope::for_http_api(&app.config().tauri.allowlist.http.scope),
#[cfg(shell_scope)]
shell: ShellScope::new(&app.manager.config(), app.package_info(), &env, shell_scope),
});
app.manage(env);
#[cfg(windows)]
{
if let crate::utils::config::WebviewInstallMode::FixedRuntime { path } = &app
.manager
.config()
.tauri
.bundle
.windows
.webview_install_mode
{
if let Some(resource_dir) = app.path_resolver().resource_dir() {
std::env::set_var(
"WEBVIEW2_BROWSER_EXECUTABLE_FOLDER",
resource_dir.join(path),
);
} else {
#[cfg(debug_assertions)]
eprintln!(
"failed to resolve resource directory; fallback to the installed Webview2 runtime."
);
}
}
}
#[cfg(all(desktop, feature = "system-tray"))]
{
if let Some(tray) = self.system_tray {
tray.build(&app)?;
}
for listener in self.system_tray_event_listeners {
let app_handle = app.handle();
let listener = Arc::new(std::sync::Mutex::new(listener));
app
.runtime
.as_mut()
.unwrap()
.on_system_tray_event(move |tray_id, event| {
if let Some((tray_id, tray)) = app_handle.manager().get_tray_by_runtime_id(tray_id) {
let app_handle = app_handle.clone();
let event = tray::SystemTrayEvent::from_runtime_event(event, tray_id, &tray.ids);
let listener = listener.clone();
listener.lock().unwrap()(&app_handle, event);
}
});
}
}
app.manager.initialize_plugins(&app.handle())?;
let window_labels = self
.pending_windows
.iter()
.map(|p| p.label.clone())
.collect::<Vec<_>>();
for pending in self.pending_windows {
let pending =
app
.manager
.prepare_window(app.handle.clone(), pending, &window_labels, None)?;
let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
let _window = app.manager.attach_window(app.handle(), detached);
}
(self.setup)(&mut app).map_err(|e| crate::Error::Setup(e.into()))?;
#[cfg(updater)]
app.run_updater();
Ok(app)
}
sourcepub fn asset_resolver(&self) -> AssetResolver<R>
pub fn asset_resolver(&self) -> AssetResolver<R>
The application’s asset resolver.
source§impl<R: Runtime> App<R>
impl<R: Runtime> App<R>
sourcepub fn handle(&self) -> AppHandle<R>
pub fn handle(&self) -> AppHandle<R>
Gets a handle to the application instance.
Examples found in repository?
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
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())
}
/// Gets a handle to the first system tray.
///
/// Prefer [`Self::tray_handle_by_id`] when multiple system trays are created.
///
/// # Examples
/// ```
/// use tauri::{CustomMenuItem, SystemTray, SystemTrayMenu};
///
/// tauri::Builder::default()
/// .setup(|app| {
/// let app_handle = app.handle();
/// SystemTray::new()
/// .with_menu(
/// SystemTrayMenu::new()
/// .add_item(CustomMenuItem::new("quit", "Quit"))
/// .add_item(CustomMenuItem::new("open", "Open"))
/// )
/// .on_event(move |event| {
/// let tray_handle = app_handle.tray_handle();
/// })
/// .build(app)?;
/// Ok(())
/// });
/// ```
#[cfg(all(desktop, feature = "system-tray"))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
pub fn tray_handle(&self) -> tray::SystemTrayHandle<R> {
self
.manager()
.trays()
.values()
.next()
.cloned()
.expect("tray not configured; use the `Builder#system_tray`, `App#system_tray` or `AppHandle#system_tray` APIs first.")
}
/// Gets a handle to a system tray by its id.
///
/// ```
/// use tauri::{CustomMenuItem, SystemTray, SystemTrayMenu};
///
/// tauri::Builder::default()
/// .setup(|app| {
/// let app_handle = app.handle();
/// let tray_id = "my-tray";
/// SystemTray::new()
/// .with_id(tray_id)
/// .with_menu(
/// SystemTrayMenu::new()
/// .add_item(CustomMenuItem::new("quit", "Quit"))
/// .add_item(CustomMenuItem::new("open", "Open"))
/// )
/// .on_event(move |event| {
/// let tray_handle = app_handle.tray_handle_by_id(tray_id).unwrap();
/// })
/// .build(app)?;
/// Ok(())
/// });
/// ```
#[cfg(all(desktop, feature = "system-tray"))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
pub fn tray_handle_by_id(&self, id: &str) -> Option<tray::SystemTrayHandle<R>> {
self
.manager()
.get_tray(id)
}
/// 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(all(desktop, 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(),
}
}
/// 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(())
}
}
};
}
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
/// ```,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
///
/// ```
/// 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
/// ```,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
/// ```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;
/// }
/// }
/// ```
#[cfg(desktop)]
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 responsibilities 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
/// ```,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(all(desktop, feature = "system-tray"))]
system_tray: Option<tray::SystemTray>,
/// System tray event handlers.
#[cfg(all(desktop, 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_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(all(desktop, feature = "system-tray"))]
system_tray: None,
#[cfg(all(desktop, 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
/// ```
/// #[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
/// ```
/// 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
}
/// Defines the page load hook.
#[must_use]
pub fn on_page_load<F>(mut self, on_page_load: F) -> Self
where
F: Fn(Window<R>, PageLoadPayload) + Send + Sync + 'static,
{
self.on_page_load = Box::new(on_page_load);
self
}
/// Adds a Tauri application plugin.
///
/// A plugin is created using the [`crate::plugin::Builder`] struct.Check its documentation for more information.
///
/// # Examples
///
/// ```
/// mod plugin {
/// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, RunEvent, Runtime};
///
/// // this command can be called in the frontend using `invoke('plugin:window|do_something')`.
/// #[tauri::command]
/// async fn do_something<R: Runtime>(app: tauri::AppHandle<R>, window: tauri::Window<R>) -> Result<(), String> {
/// println!("command called");
/// Ok(())
/// }
/// pub fn init<R: Runtime>() -> TauriPlugin<R> {
/// PluginBuilder::new("window")
/// .setup(|app| {
/// // initialize the plugin here
/// Ok(())
/// })
/// .on_event(|app, event| {
/// match event {
/// RunEvent::Ready => {
/// println!("app is ready");
/// }
/// RunEvent::WindowEvent { label, event, .. } => {
/// println!("window {} received an event: {:?}", label, event);
/// }
/// _ => (),
/// }
/// })
/// .invoke_handler(tauri::generate_handler![do_something])
/// .build()
/// }
/// }
///
/// tauri::Builder::default()
/// .plugin(plugin::init());
/// ```
#[must_use]
pub fn plugin<P: Plugin<R> + 'static>(mut self, plugin: P) -> Self {
self.plugins.register(plugin);
self
}
/// Add `state` to the state managed by the application.
///
/// This method can be called any number of times as long as each call
/// refers to a different `T`.
///
/// Managed state can be retrieved by any command handler via the
/// [`State`](crate::State) guard. In particular, if a value of type `T`
/// is managed by Tauri, adding `State<T>` to the list of arguments in a
/// command handler instructs Tauri to retrieve the managed value.
///
/// # Panics
///
/// Panics if state of type `T` is already being managed.
///
/// # Mutability
///
/// Since the managed state is global and must be [`Send`] + [`Sync`], mutations can only happen through interior mutability:
///
/// ```,no_run
/// use std::{collections::HashMap, sync::Mutex};
/// use tauri::State;
/// // here we use Mutex to achieve interior mutability
/// struct Storage {
/// store: Mutex<HashMap<u64, String>>,
/// }
/// struct Connection;
/// struct DbConnection {
/// db: Mutex<Option<Connection>>,
/// }
///
/// #[tauri::command]
/// fn connect(connection: State<DbConnection>) {
/// // initialize the connection, mutating the state with interior mutability
/// *connection.db.lock().unwrap() = Some(Connection {});
/// }
///
/// #[tauri::command]
/// fn storage_insert(key: u64, value: String, storage: State<Storage>) {
/// // mutate the storage behind the Mutex
/// storage.store.lock().unwrap().insert(key, value);
/// }
///
/// tauri::Builder::default()
/// .manage(Storage { store: Default::default() })
/// .manage(DbConnection { db: Default::default() })
/// .invoke_handler(tauri::generate_handler![connect, storage_insert])
/// // 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");
/// ```
///
/// # Examples
///
/// ```,no_run
/// use tauri::State;
///
/// struct MyInt(isize);
/// struct MyString(String);
///
/// #[tauri::command]
/// fn int_command(state: State<MyInt>) -> String {
/// format!("The stateful int is: {}", state.0)
/// }
///
/// #[tauri::command]
/// fn string_command<'r>(state: State<'r, MyString>) {
/// println!("state: {}", state.inner().0);
/// }
///
/// tauri::Builder::default()
/// .manage(MyInt(10))
/// .manage(MyString("Hello, managed state!".to_string()))
/// .invoke_handler(tauri::generate_handler![int_command, string_command])
/// // 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");
/// ```
#[must_use]
pub fn manage<T>(self, state: T) -> Self
where
T: Send + Sync + 'static,
{
let type_name = std::any::type_name::<T>();
assert!(
self.state.set(state),
"state for type '{}' is already being managed",
type_name
);
self
}
/// Sets the given system tray to be built before the app runs.
///
/// Prefer the [`SystemTray#method.build`](crate::SystemTray#method.build) method to create the tray at runtime instead.
///
/// # Examples
/// ```
/// use tauri::{CustomMenuItem, SystemTray, SystemTrayMenu};
///
/// tauri::Builder::default()
/// .system_tray(SystemTray::new().with_menu(
/// SystemTrayMenu::new()
/// .add_item(CustomMenuItem::new("quit", "Quit"))
/// .add_item(CustomMenuItem::new("open", "Open"))
/// ));
/// ```
#[cfg(all(desktop, feature = "system-tray"))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
#[must_use]
pub fn system_tray(mut self, system_tray: tray::SystemTray) -> Self {
self.system_tray.replace(system_tray);
self
}
/// Sets the menu to use on all windows.
///
/// # Examples
/// ```
/// use tauri::{MenuEntry, Submenu, MenuItem, Menu, CustomMenuItem};
///
/// tauri::Builder::default()
/// .menu(Menu::with_items([
/// MenuEntry::Submenu(Submenu::new(
/// "File",
/// Menu::with_items([
/// MenuItem::CloseWindow.into(),
/// #[cfg(target_os = "macos")]
/// CustomMenuItem::new("hello", "Hello").into(),
/// ]),
/// )),
/// ]));
/// ```
#[must_use]
pub fn menu(mut self, menu: Menu) -> Self {
self.menu.replace(menu);
self
}
/// Enable or disable the default menu on macOS. Enabled by default.
///
/// # Examples
/// ```
/// use tauri::{MenuEntry, Submenu, MenuItem, Menu, CustomMenuItem};
///
/// tauri::Builder::default()
/// .enable_macos_default_menu(false);
/// ```
#[must_use]
pub fn enable_macos_default_menu(mut self, enable: bool) -> Self {
self.enable_macos_default_menu = enable;
self
}
/// Registers a menu event handler for all windows.
///
/// # Examples
/// ```
/// use tauri::{Menu, MenuEntry, Submenu, CustomMenuItem, api, Manager};
/// tauri::Builder::default()
/// .menu(Menu::with_items([
/// MenuEntry::Submenu(Submenu::new(
/// "File",
/// Menu::with_items([
/// CustomMenuItem::new("New", "New").into(),
/// CustomMenuItem::new("Learn More", "Learn More").into(),
/// ]),
/// )),
/// ]))
/// .on_menu_event(|event| {
/// match event.menu_item_id() {
/// "Learn More" => {
/// // open in browser (requires the `shell-open-api` feature)
#[cfg_attr(
feature = "shell-open-api",
doc = r#" api::shell::open(&event.window().shell_scope(), "https://github.com/tauri-apps/tauri".to_string(), None).unwrap();"#
)]
/// }
/// id => {
/// // do something with other events
/// println!("got menu event: {}", id);
/// }
/// }
/// });
/// ```
#[must_use]
pub fn on_menu_event<F: Fn(WindowMenuEvent<R>) + Send + Sync + 'static>(
mut self,
handler: F,
) -> Self {
self.menu_event_listeners.push(Box::new(handler));
self
}
/// Registers a window event handler for all windows.
///
/// # Examples
/// ```
/// tauri::Builder::default()
/// .on_window_event(|event| match event.event() {
/// tauri::WindowEvent::Focused(focused) => {
/// // hide window whenever it loses focus
/// if !focused {
/// event.window().hide().unwrap();
/// }
/// }
/// _ => {}
/// });
/// ```
#[must_use]
pub fn on_window_event<F: Fn(GlobalWindowEvent<R>) + Send + Sync + 'static>(
mut self,
handler: F,
) -> Self {
self.window_event_listeners.push(Box::new(handler));
self
}
/// Registers a system tray event handler.
///
/// Prefer the [`SystemTray#method.on_event`](crate::SystemTray#method.on_event) method when creating a tray at runtime instead.
///
/// # Examples
/// ```
/// use tauri::{Manager, SystemTrayEvent};
/// tauri::Builder::default()
/// .on_system_tray_event(|app, event| match event {
/// // show window with id "main" when the tray is left clicked
/// SystemTrayEvent::LeftClick { .. } => {
/// let window = app.get_window("main").unwrap();
/// window.show().unwrap();
/// window.set_focus().unwrap();
/// }
/// _ => {}
/// });
/// ```
#[cfg(all(desktop, feature = "system-tray"))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
#[must_use]
pub fn on_system_tray_event<
F: Fn(&AppHandle<R>, tray::SystemTrayEvent) + Send + Sync + 'static,
>(
mut self,
handler: F,
) -> Self {
self.system_tray_event_listeners.push(Box::new(handler));
self
}
/// Registers a URI scheme protocol available to all webviews.
/// Leverages [setURLSchemeHandler](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/2875766-seturlschemehandler) on macOS,
/// [AddWebResourceRequestedFilter](https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.addwebresourcerequestedfilter?view=webview2-dotnet-1.0.774.44) on Windows
/// and [webkit-web-context-register-uri-scheme](https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebContext.html#webkit-web-context-register-uri-scheme) on Linux.
///
/// # Arguments
///
/// * `uri_scheme` The URI scheme to register, such as `example`.
/// * `protocol` the protocol associated with the given URI scheme. It's a function that takes an URL such as `example://localhost/asset.css`.
#[must_use]
pub fn register_uri_scheme_protocol<
N: Into<String>,
H: Fn(&AppHandle<R>, &HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>>
+ Send
+ Sync
+ 'static,
>(
mut self,
uri_scheme: N,
protocol: H,
) -> Self {
self.uri_scheme_protocols.insert(
uri_scheme.into(),
Arc::new(CustomProtocol {
protocol: Box::new(protocol),
}),
);
self
}
/// Sets the current platform's target name for the updater.
///
/// See [`UpdateBuilder::target`](crate::updater::UpdateBuilder#method.target) for more information.
///
/// # Examples
///
/// - Use a macOS Universal binary target name:
///
/// ```
/// let mut builder = tauri::Builder::default();
/// #[cfg(target_os = "macos")]
/// {
/// builder = builder.updater_target("darwin-universal");
/// }
/// ```
///
/// - Append debug information to the target:
///
/// ```
/// let kind = if cfg!(debug_assertions) { "debug" } else { "release" };
/// tauri::Builder::default()
/// .updater_target(format!("{}-{}", tauri::updater::target().unwrap(), kind));
/// ```
///
/// - Use the platform's target triple:
///
/// ```
/// tauri::Builder::default()
/// .updater_target(tauri::utils::platform::target_triple().unwrap());
/// ```
#[cfg(updater)]
pub fn updater_target<T: Into<String>>(mut self, target: T) -> Self {
self.updater_settings.target.replace(target.into());
self
}
/// Builds the application.
#[allow(clippy::type_complexity)]
pub fn build<A: Assets>(mut self, context: Context<A>) -> crate::Result<App<R>> {
#[cfg(target_os = "macos")]
if self.menu.is_none() && self.enable_macos_default_menu {
self.menu = Some(Menu::os_default(&context.package_info().name));
}
#[cfg(shell_scope)]
let shell_scope = context.shell_scope.clone();
let manager = WindowManager::with_handlers(
context,
self.plugins,
self.invoke_handler,
self.on_page_load,
self.uri_scheme_protocols,
self.state,
self.window_event_listeners,
(self.menu, self.menu_event_listeners),
(self.invoke_responder, self.invoke_initialization_script),
);
// set up all the windows defined in the config
for config in manager.config().tauri.windows.clone() {
let url = config.url.clone();
let label = config.label.clone();
let mut webview_attributes =
WebviewAttributes::new(url).accept_first_mouse(config.accept_first_mouse);
if let Some(ua) = &config.user_agent {
webview_attributes = webview_attributes.user_agent(&ua.to_string());
}
if !config.file_drop_enabled {
webview_attributes = webview_attributes.disable_file_drop_handler();
}
self.pending_windows.push(PendingWindow::with_config(
config,
webview_attributes,
label,
)?);
}
#[cfg(any(windows, target_os = "linux"))]
let runtime = if self.runtime_any_thread {
R::new_any_thread()?
} else {
R::new()?
};
#[cfg(not(any(windows, target_os = "linux")))]
let runtime = R::new()?;
let runtime_handle = runtime.handle();
#[cfg(all(desktop, feature = "global-shortcut"))]
let global_shortcut_manager = runtime.global_shortcut_manager();
#[cfg(feature = "clipboard")]
let clipboard_manager = runtime.clipboard_manager();
let mut app = App {
runtime: Some(runtime),
manager: manager.clone(),
#[cfg(all(desktop, feature = "global-shortcut"))]
global_shortcut_manager: global_shortcut_manager.clone(),
#[cfg(feature = "clipboard")]
clipboard_manager: clipboard_manager.clone(),
handle: AppHandle {
runtime_handle,
manager,
#[cfg(all(desktop, feature = "global-shortcut"))]
global_shortcut_manager,
#[cfg(feature = "clipboard")]
clipboard_manager,
#[cfg(updater)]
updater_settings: self.updater_settings,
},
};
let env = Env::default();
app.manage(Scopes {
fs: FsScope::for_fs_api(
&app.manager.config(),
app.package_info(),
&env,
&app.config().tauri.allowlist.fs.scope,
)?,
#[cfg(protocol_asset)]
asset_protocol: FsScope::for_fs_api(
&app.manager.config(),
app.package_info(),
&env,
&app.config().tauri.allowlist.protocol.asset_scope,
)?,
#[cfg(http_request)]
http: crate::scope::HttpScope::for_http_api(&app.config().tauri.allowlist.http.scope),
#[cfg(shell_scope)]
shell: ShellScope::new(&app.manager.config(), app.package_info(), &env, shell_scope),
});
app.manage(env);
#[cfg(windows)]
{
if let crate::utils::config::WebviewInstallMode::FixedRuntime { path } = &app
.manager
.config()
.tauri
.bundle
.windows
.webview_install_mode
{
if let Some(resource_dir) = app.path_resolver().resource_dir() {
std::env::set_var(
"WEBVIEW2_BROWSER_EXECUTABLE_FOLDER",
resource_dir.join(path),
);
} else {
#[cfg(debug_assertions)]
eprintln!(
"failed to resolve resource directory; fallback to the installed Webview2 runtime."
);
}
}
}
#[cfg(all(desktop, feature = "system-tray"))]
{
if let Some(tray) = self.system_tray {
tray.build(&app)?;
}
for listener in self.system_tray_event_listeners {
let app_handle = app.handle();
let listener = Arc::new(std::sync::Mutex::new(listener));
app
.runtime
.as_mut()
.unwrap()
.on_system_tray_event(move |tray_id, event| {
if let Some((tray_id, tray)) = app_handle.manager().get_tray_by_runtime_id(tray_id) {
let app_handle = app_handle.clone();
let event = tray::SystemTrayEvent::from_runtime_event(event, tray_id, &tray.ids);
let listener = listener.clone();
listener.lock().unwrap()(&app_handle, event);
}
});
}
}
app.manager.initialize_plugins(&app.handle())?;
let window_labels = self
.pending_windows
.iter()
.map(|p| p.label.clone())
.collect::<Vec<_>>();
for pending in self.pending_windows {
let pending =
app
.manager
.prepare_window(app.handle.clone(), pending, &window_labels, None)?;
let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
let _window = app.manager.attach_window(app.handle(), detached);
}
(self.setup)(&mut app).map_err(|e| crate::Error::Setup(e.into()))?;
#[cfg(updater)]
app.run_updater();
Ok(app)
}
sourcepub fn get_cli_matches(&self) -> Result<Matches>
pub fn get_cli_matches(&self) -> Result<Matches>
Gets the argument matches of the CLI definition configured in tauri.conf.json
.
Examples
tauri::Builder::default()
.setup(|app| {
let matches = app.get_cli_matches()?;
Ok(())
});
sourcepub fn run<F: FnMut(&AppHandle<R>, RunEvent) + 'static>(self, callback: F)
pub fn run<F: FnMut(&AppHandle<R>, RunEvent) + 'static>(self, callback: F)
Runs the application.
Examples
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();
}
_ => {}
});
sourcepub fn run_iteration(&mut self) -> RunIteration
pub fn run_iteration(&mut self) -> RunIteration
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 (Windows only).
Examples
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;
}
}
Trait Implementations§
source§impl<R: Debug + Runtime> Debug for App<R>where
R::GlobalShortcutManager: Debug,
R::ClipboardManager: Debug,
impl<R: Debug + Runtime> Debug for App<R>where
R::GlobalShortcutManager: Debug,
R::ClipboardManager: Debug,
source§impl<R: Runtime> HasRawDisplayHandle for App<R>
impl<R: Runtime> HasRawDisplayHandle for App<R>
fn raw_display_handle(&self) -> RawDisplayHandle
source§impl<R: Runtime> Manager<R> for App<R>
impl<R: Runtime> Manager<R> for App<R>
source§fn app_handle(&self) -> AppHandle<R>
fn app_handle(&self) -> AppHandle<R>
source§fn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>
fn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>
source§fn emit_to<S: Serialize + Clone>(
&self,
label: &str,
event: &str,
payload: S
) -> Result<()>
fn emit_to<S: Serialize + Clone>(
&self,
label: &str,
event: &str,
payload: S
) -> Result<()>
source§fn listen_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandlerwhere
F: Fn(Event) + Send + 'static,
fn listen_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandlerwhere
F: Fn(Event) + Send + 'static,
source§fn once_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandlerwhere
F: FnOnce(Event) + Send + 'static,
fn once_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandlerwhere
F: FnOnce(Event) + Send + 'static,
source§fn unlisten(&self, handler_id: EventHandler)
fn unlisten(&self, handler_id: EventHandler)
source§fn get_window(&self, label: &str) -> Option<Window<R>>
fn get_window(&self, label: &str) -> Option<Window<R>>
source§fn manage<T>(&self, state: T) -> boolwhere
T: Send + Sync + 'static,
fn manage<T>(&self, state: T) -> boolwhere
T: Send + Sync + 'static,
state
to the state managed by the application. Read moresource§fn state<T>(&self) -> State<'_, T>where
T: Send + Sync + 'static,
fn state<T>(&self) -> State<'_, T>where
T: Send + Sync + 'static,
T
. Read moresource§fn try_state<T>(&self) -> Option<State<'_, T>>where
T: Send + Sync + 'static,
fn try_state<T>(&self) -> Option<State<'_, T>>where
T: Send + Sync + 'static,
T
. Read more