Skip to content

Commit

Permalink
refactor: avoid blocking at startup
Browse files Browse the repository at this point in the history
Signed-off-by: 1111mp <[email protected]>
  • Loading branch information
1111mp committed Nov 4, 2024
1 parent b5c0aa4 commit eef766d
Show file tree
Hide file tree
Showing 10 changed files with 808 additions and 165 deletions.
637 changes: 610 additions & 27 deletions src-tauri/Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ tauri = { version = "2.0", features = [
"tray-icon",
"devtools",
] }
tauri-plugin-devtools = "2.0"
tauri-plugin-dialog = "2.0"
tauri-plugin-log = { version = "2.0", features = ["colored"] }
tauri-plugin-shell = "2.0"
tauri-plugin-single-instance = "2.0"
tauri-plugin-window-state = "2.0"
tauri-plugin-updater = "2.0"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
Expand Down
53 changes: 42 additions & 11 deletions src-tauri/capabilities/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,52 @@
"core:path:default",
"core:event:default",
"core:window:default",
"core:window:allow-close",
"core:window:allow-start-dragging",
"core:window:allow-minimize",
"core:window:allow-unminimize",
"core:window:allow-show",
"core:window:allow-set-focus",
"core:window:allow-create",
"core:window:allow-center",
"core:window:allow-request-user-attention",
"core:window:allow-set-resizable",
"core:window:allow-set-closable",
"core:window:allow-set-title",
"core:window:allow-show",
"core:window:allow-hide",
"core:window:allow-close",
"core:window:allow-set-decorations",
"core:window:allow-set-always-on-top",
"core:window:allow-set-content-protected",
"core:window:allow-set-size",
"core:window:allow-set-min-size",
"core:window:allow-set-max-size",
"core:window:allow-set-position",
"core:window:allow-set-fullscreen",
"core:window:allow-set-focus",
"core:window:allow-set-icon",
"core:window:allow-set-skip-taskbar",
"core:window:allow-set-cursor-grab",
"core:window:allow-set-cursor-visible",
"core:window:allow-set-cursor-icon",
"core:window:allow-set-cursor-position",
"core:window:allow-set-ignore-cursor-events",
"core:window:allow-start-dragging",
"core:window:allow-maximize",
"core:window:allow-toggle-maximize",
"core:window:allow-unmaximize",
"core:window:allow-minimize",
"core:window:allow-unminimize",
"core:window:allow-set-maximizable",
"core:window:allow-set-minimizable",
"core:webview:allow-print",
"core:app:default",
"core:image:default",
"core:resources:default",
"core:menu:default",
"core:tray:default",
"shell:allow-open",
"updater:allow-check",
"updater:allow-download",
"updater:allow-install",
"updater:allow-download-and-install"
"shell:allow-execute",
"shell:allow-open",
"shell:allow-kill",
"shell:allow-spawn",
"shell:allow-stdin-write",
"dialog:default",
"updater:default",
"window-state:default"
]
}
43 changes: 20 additions & 23 deletions src-tauri/src/core/handle.rs
Original file line number Diff line number Diff line change
@@ -1,54 +1,51 @@
use super::tray::Tray;
use anyhow::{bail, Result};
use anyhow::Result;
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use parking_lot::RwLock;
use std::sync::Arc;
use tauri::AppHandle;
use tauri::{AppHandle, Manager, WebviewWindow};

#[derive(Debug, Default, Clone)]
pub struct Handle {
pub app_handle: Arc<Mutex<Option<AppHandle>>>,
pub app_handle: Arc<RwLock<Option<AppHandle>>>,
}

impl Handle {
pub fn global() -> &'static Handle {
static HANDLE: OnceCell<Handle> = OnceCell::new();

HANDLE.get_or_init(|| Handle {
app_handle: Arc::new(Mutex::new(None)),
app_handle: Arc::new(RwLock::new(None)),
})
}

pub fn init(&self, app_handle: AppHandle) {
*self.app_handle.lock() = Some(app_handle);
pub fn init(&self, app_handle: &AppHandle) {
let mut handle = self.app_handle.write();
*handle = Some(app_handle.clone());
}

pub fn update_systray() -> Result<()> {
let app_handle = Self::global().app_handle.lock();
if app_handle.is_none() {
bail!("update_systray unhandled error");
pub fn app_handle(&self) -> Option<AppHandle> {
self.app_handle.read().clone()
}

pub fn get_window(&self) -> Option<WebviewWindow> {
let app_handle = self.app_handle().unwrap();
let window: Option<WebviewWindow> = app_handle.get_webview_window("main");
if window.is_none() {
log::debug!(target:"app", "main window not found");
}
Tray::update_systray(app_handle.as_ref().unwrap())?;
Ok(())
window
}

/// update the system tray state
pub fn update_systray_part() -> Result<()> {
let app_handle = Self::global().app_handle.lock();
if app_handle.is_none() {
bail!("update_systray unhandled error");
}
Tray::update_part(app_handle.as_ref().unwrap())?;
Tray::update_part()?;
Ok(())
}

/// update the system tray state & emit event
pub fn update_systray_part_with_emit(event: &str, version: &str) -> Result<()> {
let app_handle = Self::global().app_handle.lock();
if app_handle.is_none() {
bail!("update_systray unhandled error");
}
Tray::update_part_with_emit(app_handle.as_ref().unwrap(), event, version)?;
Tray::update_part_with_emit(event, version)?;
Ok(())
}
}
26 changes: 15 additions & 11 deletions src-tauri/src/core/tray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use tauri::{
AppHandle, Emitter, Manager, Wry,
};

use super::handle;

pub struct Tray {}

fn gen_check_menu_items(
Expand All @@ -36,7 +38,7 @@ fn gen_check_menu_items(
}

impl Tray {
pub fn tray_menu(app_handle: &AppHandle) -> Result<Menu<Wry>> {
pub fn create_tray_menu(app_handle: &AppHandle) -> Result<Menu<Wry>> {
let package_info = app_handle.package_info();
let version = package_info.version.to_string();
let app_name: String = package_info.name.to_string();
Expand Down Expand Up @@ -153,17 +155,17 @@ impl Tray {
.build()?)
}

pub fn update_systray(app_handle: &AppHandle) -> Result<()> {
pub fn create_systray() -> Result<()> {
let app_handle = handle::Handle::global().app_handle().unwrap();
if let Some(tray) = app_handle.tray_by_id("main") {
tray.set_menu(Some(Tray::tray_menu(app_handle)?))?;
tray.on_tray_icon_event(|tray, event| {
tray.on_tray_icon_event(|_, event| {
#[cfg(not(target_os = "macos"))]
if let TrayIconEvent::Click {
button: MouseButton::Left,
..
} = event
{
let _ = resolve::create_window(&tray.app_handle());
let _ = resolve::create_window();
}
});
tray.on_menu_event(Tray::on_menu_event);
Expand All @@ -172,19 +174,21 @@ impl Tray {
Ok(())
}

pub fn update_part(app_handle: &AppHandle) -> Result<()> {
pub fn update_part() -> Result<()> {
let app_handle = handle::Handle::global().app_handle().unwrap();
if let Some(tray) = app_handle.tray_by_id("main") {
tray.set_menu(Some(Tray::tray_menu(app_handle)?))?;
let _ = tray.set_menu(Some(Tray::create_tray_menu(&app_handle)?));
Ok(())
} else {
bail!("The system tray menu has not been initialized")
}
}

pub fn update_part_with_emit(app_handle: &AppHandle, event: &str, version: &str) -> Result<()> {
pub fn update_part_with_emit(event: &str, version: &str) -> Result<()> {
let app_handle = handle::Handle::global().app_handle().unwrap();
if let Some(tray) = app_handle.tray_by_id("main") {
tray.set_menu(Some(Tray::tray_menu(app_handle)?))?;
if let Some(window) = app_handle.get_webview_window("main") {
let _ = tray.set_menu(Some(Tray::create_tray_menu(&app_handle)?));
if let Some(window) = handle::Handle::global().get_window() {
window.emit(event, version)?;
}
Ok(())
Expand All @@ -196,7 +200,7 @@ impl Tray {
pub fn on_menu_event(app_handle: &AppHandle, event: MenuEvent) {
match event.id().as_ref() {
"open_window" => {
let _ = resolve::create_window(app_handle);
let _ = resolve::create_window();
}
"quit" => cmds::exit_app(app_handle.clone()),
"open_data_dir" => crate::log_err!(cmds::open_data_dir()),
Expand Down
62 changes: 41 additions & 21 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,16 @@ mod utils;

use config::Config;
use tauri::Manager;
use tauri_plugin_log::{Target, TargetKind};
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
use utils::resolve;

fn main() -> tauri::Result<()> {
#[cfg(target_os = "linux")]
std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");

let builder = tauri::Builder::default()
.setup(|app| {
resolve::resolve_setup(app)?;
Ok(())
})
let mut builder = tauri::Builder::default()
.plugin(tauri_plugin_window_state::Builder::default().build())
.plugin(tauri_plugin_updater::Builder::default().build())
.plugin(
tauri_plugin_log::Builder::default()
.rotation_strategy(tauri_plugin_log::RotationStrategy::KeepAll)
.targets([
Target::new(TargetKind::Stdout),
Target::new(TargetKind::LogDir { file_name: None }),
// Target::new(TargetKind::Webview),
])
.build(),
)
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_shell::init())
// Ensure single instance operation
Expand All @@ -42,6 +29,13 @@ fn main() -> tauri::Result<()> {
}
},
))
.setup(|app| {
tauri::async_runtime::block_on(async move {
resolve::resolve_setup(app).await;
});

Ok(())
})
.invoke_handler(tauri::generate_handler![
// settings
cmds::read_settings,
Expand All @@ -60,8 +54,8 @@ fn main() -> tauri::Result<()> {
cmds::update_projects,
cmds::sync_project_version,
cmds::batch_update_project_version,
cmds::open_dir,
cmds::open_with_vscode,
cmds::open_dir,
cmds::open_with_vscode,
// groups
cmds::group_list,
cmds::update_groups,
Expand All @@ -73,6 +67,28 @@ fn main() -> tauri::Result<()> {
cmds::restart,
]);

#[cfg(debug_assertions)]
{
let devtools = tauri_plugin_devtools::init();
builder = builder.plugin(devtools);
}

#[cfg(not(debug_assertions))]
{
use tauri_plugin_log::{Builder, Target, TargetKind};

let log_plugin = Builder::default()
.rotation_strategy(tauri_plugin_log::RotationStrategy::KeepAll)
.targets([
Target::new(TargetKind::Stdout),
Target::new(TargetKind::LogDir { file_name: None }),
// Target::new(TargetKind::Webview),
])
.build();

builder = builder.plugin(log_plugin);
}

let app = builder.build(tauri::generate_context!())?;

app.run(|app_handle, err| match err {
Expand All @@ -84,16 +100,20 @@ fn main() -> tauri::Result<()> {

if closer == "minimize" {
api.prevent_exit();
return;
}

let _ = app_handle.save_window_state(StateFlags::default());
}
tauri::RunEvent::WindowEvent { label, event, .. } => {
if label == "main" {
match event {
tauri::WindowEvent::Destroyed => {
// Destroyed Event
}
tauri::WindowEvent::CloseRequested { api, .. } => {
// CloseRequested Event
api.prevent_close();
if let Some(window) = core::handle::Handle::global().get_window() {
log_err!(window.hide());
}
}
_ => {}
}
Expand Down
26 changes: 14 additions & 12 deletions src-tauri/src/utils/dirs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,22 +65,24 @@ pub fn default_install_dir() -> PathBuf {

/// get the resources dir
pub fn app_resources_dir() -> Result<PathBuf> {
let handle = handle::Handle::global();
let app_handle = handle.app_handle.lock();
if let Some(app_handle) = app_handle.as_ref() {
let res_dir = app_handle.path().resource_dir()?.join("resources");
return Ok(res_dir);
let app_handle = handle::Handle::global().app_handle().unwrap();
match app_handle.path().resource_dir() {
Ok(dir) => Ok(dir.join("resources")),
Err(e) => {
log::error!(target:"app", "Failed to get the resource directory: {}", e);
Err(anyhow::anyhow!("Failed to get the resource directory"))
}
}
Err(anyhow::anyhow!("failed to get the resource dir"))
}

/// get the logs dir
pub fn app_logs_dir() -> Result<PathBuf> {
let handle = handle::Handle::global();
let app_handle = handle.app_handle.lock();
if let Some(app_handle) = app_handle.as_ref() {
let res_dir = app_handle.path().app_log_dir()?;
return Ok(res_dir);
let app_handle = handle::Handle::global().app_handle().unwrap();
match app_handle.path().app_log_dir() {
Ok(dir) => Ok(dir),
Err(e) => {
log::error!(target:"app", "Failed to get the logs directory: {}", e);
Err(anyhow::anyhow!("Failed to get the logs directory"))
}
}
Err(anyhow::anyhow!("failed to get the logs dir"))
}
Loading

0 comments on commit eef766d

Please sign in to comment.