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| {});
}
相关推荐
KENYCHEN奉孝10 小时前
基于 actix-web 框架的简单 demo
前端·rust
love530love10 小时前
【笔记】旧版MSYS2 环境中 Rust 升级问题及解决过程
开发语言·人工智能·windows·笔记·python·rust·virtualenv
Humbunklung11 小时前
Rust 函数
开发语言·后端·rust
荣江12 小时前
【实战】基于 Tauri 和 Rust 实现基于无头浏览器的高可用网页抓取
后端·rust
susnm12 小时前
创建你的第一个 Dioxus app
rust·全栈
love530love1 天前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
景天科技苑1 天前
【Rust宏编程】Rust有关宏编程底层原理解析与应用实战
开发语言·后端·rust·rust宏·宏编程·rust宏编程
维维酱1 天前
Rust - 消息传递
rust
Kapaseker2 天前
Android程序员初学Rust-线程
rust
solohoho2 天前
Rust:所有权的理解
rust