Tauri 2.x 版本 辅助性 Accessory App 如何实现单例模式 (MAC & Windows)

Tauri其实提供了 run event 中 Reopen 的方法, 但是我们初始化 run app 的时候跟他官方提供给我们的代码示例有些许不同。

首先tauri_plugin_single_instance在macos 上回调是不生效的。 因为我期望我的辅助性app 在mac 上是不显示在docker栏里面的。 但是当我重复打开app时,我的Docker栏其实会显示我的app,这不是我所期望的效果。

less 复制代码
#![cfg_attr(    all(not(debug_assertions), target_os = "windows"),    windows_subsystem = "windows")]

mod api;
mod db;
mod utils;

use sqlx::sqlite::SqlitePoolOptions;
use std::fs;
use tauri::{Manager, Wry};
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_prevent_default::Flags;

use tauri::App;
use tauri::RunEvent;

pub fn run_app<F: FnOnce(&App<Wry>) + Send + 'static>(builder: tauri::Builder<Wry>, setup: F) {
    #[allow(unused_mut)]
    let mut builder = builder
        .plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
            let window = app.get_webview_window("main");
            if let Some(window) = window {
                window.show().unwrap();
                window.set_focus().unwrap();
            }
        }))
        .plugin(tauri_plugin_clipboard::init())
        .plugin(tauri_plugin_os::init())
        .plugin(tauri_plugin_sql::Builder::default().build())
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_updater::Builder::default().build())
        .plugin(tauri_plugin_autostart::init(
            MacosLauncher::LaunchAgent,
            Some(vec![]),
        ))
        .plugin(
            tauri_plugin_prevent_default::Builder::new()
                .with_flags(Flags::all().difference(Flags::CONTEXT_MENU))
                .build(),
        )
        .plugin(tauri_plugin_global_shortcut::Builder::new().build())
        .setup(move |app| {
            #[cfg(target_os = "macos")]
            app.set_activation_policy(tauri::ActivationPolicy::Accessory);

            let app_data_dir = app.path().app_data_dir().unwrap();
            utils::logger::init_logger(&app_data_dir).expect("Failed to initialize logger");

            fs::create_dir_all(&app_data_dir).expect("Failed to create app data directory");

            let db_path = app_data_dir.join("data.db");
            let is_new_db = !db_path.exists();
            if is_new_db {
                fs::File::create(&db_path).expect("Failed to create database file");
            }

            let db_url = format!("sqlite:{}", db_path.to_str().unwrap());

            let app_handle = app.handle().clone();

            let app_handle_clone = app_handle.clone();
            tauri::async_runtime::spawn(async move {
                let pool = SqlitePoolOptions::new()
                    .max_connections(5)
                    .connect(&db_url)
                    .await
                    .expect("Failed to create pool");

                app_handle_clone.manage(pool);
            });

            let main_window = app.get_webview_window("main");

            let _ = db::database::setup(app);
            api::hotkeys::setup(app_handle.clone());
            api::tray::setup(app)?;
            api::clipboard::setup(app.handle());
            let _ = api::clipboard::start_monitor(app_handle.clone());

            utils::commands::center_window_on_current_monitor(main_window.as_ref().unwrap());
            main_window.as_ref().map(|w| w.hide()).unwrap_or(Ok(()))?;
            setup(app);

            Ok(())
        })
        .on_window_event(|_app, _event| {
            if let tauri::WindowEvent::Focused(false) = _event {
                if let Some(window) = _app.get_webview_window("main") {
                    let _ = window.hide();
                }
            }
        });

    #[allow(unused_mut)]
    let mut app = builder
        .invoke_handler(tauri::generate_handler![
            api::clipboard::write_and_paste,
            db::history::get_history,
            db::history::add_history_item,
            db::history::delete_history_item,
            db::history::clear_history,
            db::history::read_image,
        ])
        .build(tauri::generate_context!())
        .expect("error while building tauri application");

    app.run(move |_app_handle, _event| match &_event {
        RunEvent::Reopen {
            has_visible_windows,
            ..
        } => {
            if !has_visible_windows {
                if let Some(window) = _app_handle.get_webview_window("main") {
                    window.show().unwrap();
                }
            }
        }
        _ => (),
    })
}

fn main() {
    run_app(tauri::Builder::default(), |_app| {});
}
相关推荐
大鱼七成饱15 小时前
Rust Web 初学者必看:用一个宏搞定错误处理和统一返回
rust
Vallelonga16 小时前
Rust 设计模式 Marker Trait + Blanket Implementation
开发语言·设计模式·rust
ftpeak19 小时前
《Cargo 参考手册》第二十一章:Cargo 包命令
开发语言·rust
Source.Liu1 天前
【BuildFlow & 筑流】品牌命名与项目定位说明
c++·qt·rust·markdown·librecad
ftpeak1 天前
《Cargo 参考手册》第二十二章:发布命令
开发语言·rust
JoannaJuanCV3 天前
error: can‘t find Rust compiler
开发语言·后端·rust
Kiri霧3 天前
在actix-web应用用构建集成测试
后端·rust·集成测试
muyouking113 天前
Tauri Android 开发踩坑实录:从 Gradle 版本冲突到离线构建成功
android·rust
Kiri霧3 天前
Rust开发环境搭建
开发语言·后端·rust
xuejianxinokok4 天前
什么是代数类型 ? java为什么要添加record,Sealed class 和增强switch ?
后端·rust