Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

2.9 KB
Raw Blame
use std::sync::atomic::{AtomicBool, Ordering};

use tauri::Manager;

static LIGHTWEIGHT_MODE: AtomicBool = AtomicBool::new(false);

pub fn enter_lightweight_mode(app: &tauri::AppHandle) -> Result<(), String> {
    #[cfg(target_os = "windows")]
    {
        if let Some(window) = app.get_webview_window("main") {
            let _ = window.set_skip_taskbar(true);
        }
    }
    #[cfg(target_os = "macos")]
    {
        crate::tray::apply_tray_policy(app, false);
    }

    if let Some(window) = app.get_webview_window("main") {
        crate::save_window_state_before_exit(app);
        window
            .destroy()
            .map_err(|e| format!("销毁主窗口失败: {e}"))?;
    }
    // else: already in lightweight mode or window not found, just set the flag

    LIGHTWEIGHT_MODE.store(true, Ordering::Release);
    crate::session_manager::cache::global().set_enabled(false);
    persist_lightweight_mode(true);
    // 托盘面板也是一个 WebView:收着的当场释放,开着的(在面板里点的轻量模式)收起时释放。
    crate::tray_panel::release_if_lightweight(app);
    crate::tray::refresh_tray_menu(app);
    log::info!("进入轻量模式");
    Ok(())
}

pub fn exit_lightweight_mode(app: &tauri::AppHandle) -> Result<(), String> {
    use tauri::WebviewWindowBuilder;

    if let Some(window) = app.get_webview_window("main") {
        crate::tray::reveal_main_window(&window, "lightweight-exit");
        LIGHTWEIGHT_MODE.store(false, Ordering::Release);
        crate::session_manager::cache::global().set_enabled(true);
        persist_lightweight_mode(false);
        crate::tray::refresh_tray_menu(app);
        log::info!("退出轻量模式");
        return Ok(());
    }

    let window_config = app
        .config()
        .app
        .windows
        .iter()
        .find(|w| w.label == "main")
        .ok_or("主窗口配置未找到")?;

    WebviewWindowBuilder::from_config(app, window_config)
        .map_err(|e| format!("加载主窗口配置失败: {e}"))?
        .build()
        .map_err(|e| format!("创建主窗口失败: {e}"))?;

    if let Some(window) = app.get_webview_window("main") {
        // 重建会重新注册平台的窗口状态恢复钩子。
        crate::tray::reveal_main_window(&window, "lightweight-recreated");
    }

    LIGHTWEIGHT_MODE.store(false, Ordering::Release);
    crate::session_manager::cache::global().set_enabled(true);
    persist_lightweight_mode(false);
    crate::tray::refresh_tray_menu(app);
    log::info!("退出轻量模式");
    Ok(())
}

/// 记进 settings.json,下次启动按它恢复;写失败只记日志,不影响这次切换。
fn persist_lightweight_mode(enabled: bool) {
    if let Err(e) = crate::settings::set_lightweight_mode(enabled) {
        log::warn!("保存轻量模式状态失败: {e}");
    }
}

pub fn is_lightweight_mode() -> bool {
    LIGHTWEIGHT_MODE.load(Ordering::Acquire)
}