A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
feat(linux): blur tray panels on Wayland (#10298)
Railgun8355116bf61a
diff --git a/README.md b/README.mdindex 3998a39cb..1a2a318c0 100644--- a/README.md+++ b/README.md@@ -585,6 +585,17 @@ If you launch from a desktop icon, add it to the `.desktop` `Exec=` line (e.g. `</details>+<details>+<summary><strong>Linux: switch WebView to software rendering</strong></summary>++On WebKitGTK 2.44 or newer with accessible GPU render devices, CC Switch enables WebView acceleration and uses shared memory to transfer frames. If you see a blank window, drawing artifacts, or crashes when resizing, quit CC Switch and relaunch with `CC_SWITCH_DISABLE_GPU=1`.++```bash+CC_SWITCH_DISABLE_GPU=1 ./CC-Switch-*.AppImage+```++</details>+For more questions, see the [FAQ](docs/user-manual/en/5-faq/5.2-questions.md) in the User Manual.## Contributingdiff --git a/README_ZH.md b/README_ZH.mdindex b3e46ede4..f9d91b6a4 100644--- a/README_ZH.md+++ b/README_ZH.md@@ -587,6 +587,17 @@ CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage</details>+<details>+<summary><strong>Linux:切换到 WebView 软件渲染</strong></summary>++WebKitGTK 2.44 及以上版本在 GPU 渲染设备可用时会启用 WebView 加速,并通过共享内存传输画面。如果遇到白屏、绘制异常或调整窗口大小时崩溃,退出 CC Switch 后可用 `CC_SWITCH_DISABLE_GPU=1` 重新启动。++```bash+CC_SWITCH_DISABLE_GPU=1 ./CC-Switch-*.AppImage+```++</details>+更多问题请查看用户手册中的[常见问题](docs/user-manual/zh/5-faq/5.2-questions.md)。## 贡献diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 002c55e97..c1c62ce51 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -37,6 +37,8 @@ mod lightweight;#[cfg(target_os = "linux")]mod linux_fix;#[cfg(target_os = "linux")]+mod linux_rendering;+#[cfg(target_os = "linux")]mod linux_window_geometry;pub mod live;#[cfg(target_os = "macos")]@@ -473,6 +475,10 @@ fn handle_second_instance(app: &tauri::AppHandle, args: Vec<String>) {#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {+ // WebKit caches its process-wide renderer settings before creating the first view.+ #[cfg(target_os = "linux")]+ let rendering = linux_rendering::configure_environment();+// 设置 panic hook,在应用崩溃时记录日志到 <app_config_dir>/crash.log(默认 ~/.cc-switch/crash.log)panic_hook::setup_panic_hook();@@ -484,9 +490,10 @@ pub fn run() {{builder = builder.plugin(tauri::plugin::Builder::<_, ()>::new("linux-webview-rendering")- .on_webview_ready(|webview| linux_fix::configure_webview(&webview))+ .on_webview_ready(move |webview| rendering.configure_webview(&webview)).build(),);+ builder = builder.manage(rendering);builder = builder.plugin(linux_window_geometry::init());}diff --git a/src-tauri/src/linux_fix.rs b/src-tauri/src/linux_fix.rsindex 48ead566b..8faeb0844 100644--- a/src-tauri/src/linux_fix.rs+++ b/src-tauri/src/linux_fix.rs@@ -34,28 +34,6 @@ use std::time::Duration;use tauri::WebviewWindow;-/// Apply the existing Linux software-rendering workaround to every newly created-/// WebView, including the tray panel and the main window recreated after lightweight-/// mode. WebKit settings belong to a WebView, not to the application (#9216).-pub(crate) fn configure_webview(view: &tauri::Webview) {- let label = view.label().to_owned();- if let Err(error) = view.with_webview(move |webview| {- use webkit2gtk::{HardwareAccelerationPolicy, SettingsExt, WebViewExt};-- if let Some(settings) = WebViewExt::settings(&webview.inner()) {- settings.set_hardware_acceleration_policy(HardwareAccelerationPolicy::Never);- log::info!("Linux: disabled WebKitGTK hardware acceleration for {label}");- } else {- log::warn!("Linux: WebKitGTK settings unavailable for {label}");- }- }) {- log::warn!(- "Linux: failed to configure WebView {}: {error}",- view.label()- );- }-}-static IS_NUDGING: AtomicBool = AtomicBool::new(false);/// 只保留最新一次 nudge 请求。轻量模式销毁重建窗口时,旧任务仍在跑,diff --git a/src-tauri/src/linux_rendering.rs b/src-tauri/src/linux_rendering.rsnew file mode 100644index 000000000..c370869e5--- /dev/null+++ b/src-tauri/src/linux_rendering.rs@@ -0,0 +1,236 @@+use std::env;+use std::ffi::OsStr;+use std::fs::{self, File, OpenOptions};+use std::io;+use std::os::fd::AsRawFd;+use std::path::Path;++use webkit2gtk::{HardwareAccelerationPolicy, Settings, SettingsExt, WebViewExt};++const DISABLE_DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";+const DISABLE_COMPOSITING: &str = "WEBKIT_DISABLE_COMPOSITING_MODE";+const FORCE_SHM: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM";+const FORCE_DMABUF: &str = "WEBKIT_FORCE_DMABUF_RENDERER";++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Rendering {+ Software,+ Accelerated,+}++fn rendering_mode(+ version: (u32, u32),+ disable_gpu: bool,+ disable_dmabuf: Option<&OsStr>,+ disable_compositing: Option<&OsStr>,+ render_devices_ready: impl FnOnce() -> bool,+) -> Rendering {+ let disabled = |value: Option<&OsStr>| value.is_some_and(|value| value != "0");+ if disable_gpu+ || disabled(disable_dmabuf)+ || disabled(disable_compositing)+ || version < (2, 44)+ || !render_devices_ready()+ {+ Rendering::Software+ } else {+ Rendering::Accelerated+ }+}++pub(crate) fn configure_environment() -> Rendering {+ // SAFETY: These functions report the linked WebKitGTK version without initializing GTK.+ let version = unsafe {+ (+ webkit2gtk::ffi::webkit_get_major_version(),+ webkit2gtk::ffi::webkit_get_minor_version(),+ )+ };+ let rendering = rendering_mode(+ version,+ env::var_os("CC_SWITCH_DISABLE_GPU").as_deref() == Some(OsStr::new("1")),+ env::var_os(DISABLE_DMABUF).as_deref(),+ env::var_os(DISABLE_COMPOSITING).as_deref(),+ || render_devices_ready(Path::new("/dev/dri"), Path::new("/sys/class/drm")),+ );+ match rendering {+ Rendering::Software => {+ // Keep the backing store and the per-view policy in agreement.+ env::set_var(DISABLE_DMABUF, "1");+ env::set_var(DISABLE_COMPOSITING, "1");+ }+ Rendering::Accelerated => {+ // WebKitGTK 2.44 added the SHM override. Keep accelerated compositing+ // while avoiding GBM buffer export, GTK's DMA-BUF import and the+ // associated NVIDIA/Wayland failures (Tauri #9394, WebKit #324551).+ let force_shm = env::var_os(FORCE_SHM);+ if force_shm.is_none() {+ env::set_var(FORCE_SHM, "1");+ }+ // TODO: Drop this when the affected Debian/Ubuntu builds are no+ // longer supported. Before Debian #1142771, their NVIDIA check+ // could return before registering SHM. This override skips that+ // check only when SHM transport is already forced.+ if version < (2, 54)+ && force_shm.as_deref() != Some(OsStr::new("0"))+ && env::var_os(FORCE_DMABUF).is_none()+ {+ env::set_var(FORCE_DMABUF, "1");+ }+ }+ }+ rendering+}++impl Rendering {+ pub(crate) fn supports_transparent_windows(self) -> bool {+ if self != Self::Accelerated || env::var_os(FORCE_SHM).is_none_or(|value| value == "0") {+ return false;+ }+ // WebKit checks the shared backing-store transport and GTK GL support+ // before accepting Always. Probe before building a transparent window,+ // including in lightweight mode when there is no main WebView.+ let settings = Settings::new();+ settings.set_hardware_acceleration_policy(HardwareAccelerationPolicy::Always);+ settings.hardware_acceleration_policy() == HardwareAccelerationPolicy::Always+ }++ pub(crate) fn configure_webview(self, view: &tauri::Webview) {+ let label = view.label().to_owned();+ if let Err(error) = view.with_webview(move |webview| {+ if let Some(settings) = WebViewExt::settings(&webview.inner()) {+ let policy = match self {+ Self::Software => HardwareAccelerationPolicy::Never,+ Self::Accelerated => HardwareAccelerationPolicy::Always,+ };+ settings.set_hardware_acceleration_policy(policy);+ let effective = settings.hardware_acceleration_policy();+ log::info!("Linux: WebKitGTK acceleration policy for {label}: {effective:?} (requested {policy:?})");+ } else {+ log::warn!("Linux: WebKitGTK settings unavailable for {label}");+ }+ }) {+ log::warn!("Linux: failed to configure WebView {}: {error}", view.label());+ }+ }+}++fn render_devices_ready(dri: &Path, sysfs: &Path) -> bool {+ let Ok(entries) = fs::read_dir(dri) else {+ return false;+ };++ let mut found_render_node = false;+ for entry in entries {+ let Ok(entry) = entry else {+ return false;+ };+ let name = entry.file_name();+ if !name.as_encoded_bytes().starts_with(b"renderD") {+ continue;+ }+ let Ok(device) = OpenOptions::new().read(true).write(true).open(entry.path()) else {+ return false;+ };+ let Ok(driver) = fs::read_link(sysfs.join(&name).join("device/driver")) else {+ return false;+ };+ // WebKit can choose either GPU on a hybrid system. Retain the fallback+ // if any candidate fails the same query that broke EGL in #986.+ if driver.file_name() == Some(OsStr::new("amdgpu")) && !amd_acceleration_ready(&device) {+ return false;+ }+ found_render_node = true;+ }+ found_render_node+}++fn amd_acceleration_ready(device: &File) -> bool {+ // Linux UAPI: struct drm_amdgpu_info with its unused union zeroed.+ #[repr(C)]+ struct AmdGpuInfo {+ return_pointer: u64,+ return_size: u32,+ query: u32,+ query_data: [u32; 4],+ }++ const DRM_IOCTL_AMDGPU_INFO: libc::Ioctl = libc::_IOW::<AmdGpuInfo>(b'd' as u32, 0x45);+ const AMDGPU_INFO_ACCEL_WORKING: u32 = 0;+ let mut working = 0_u32;+ let info = AmdGpuInfo {+ return_pointer: std::ptr::from_mut(&mut working) as usize as u64,+ return_size: size_of::<u32>() as u32,+ query: AMDGPU_INFO_ACCEL_WORKING,+ query_data: [0; 4],+ };++ loop {+ // SAFETY: The fd stays open and both the ABI request and its output pointer+ // are valid for the duration of this synchronous, read-only driver query.+ let result = unsafe { libc::ioctl(device.as_raw_fd(), DRM_IOCTL_AMDGPU_INFO, &info) };+ if result == 0 {+ return working != 0;+ }+ if io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {+ return false;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::os::unix::fs::symlink;++ #[test]+ fn requires_shm_support_and_working_render_devices() {+ assert_eq!(+ rendering_mode((2, 42), false, None, None, || unreachable!()),+ Rendering::Software+ );+ assert_eq!(+ rendering_mode((2, 44), false, None, None, || false),+ Rendering::Software+ );+ assert_eq!(+ rendering_mode((2, 44), false, None, None, || true),+ Rendering::Accelerated+ );+ }++ #[test]+ fn software_overrides_take_precedence() {+ let zero = Some(OsStr::new("0"));+ let one = Some(OsStr::new("1"));+ assert_eq!(+ rendering_mode((2, 54), true, zero, zero, || unreachable!()),+ Rendering::Software+ );+ assert_eq!(+ rendering_mode((2, 54), false, one, zero, || unreachable!()),+ Rendering::Software+ );+ assert_eq!(+ rendering_mode((2, 54), false, zero, one, || unreachable!()),+ Rendering::Software+ );+ assert_eq!(+ rendering_mode((2, 54), false, zero, zero, || true),+ Rendering::Accelerated+ );+ }++ #[test]+ fn rejects_an_openable_amd_node_when_the_acceleration_query_fails() {+ let dri = tempfile::tempdir().unwrap();+ let sysfs = tempfile::tempdir().unwrap();+ symlink("/dev/null", dri.path().join("renderD128")).unwrap();+ let amdgpu = sysfs.path().join("renderD128/device");+ fs::create_dir_all(&amdgpu).unwrap();+ symlink("/sys/bus/pci/drivers/amdgpu", amdgpu.join("driver")).unwrap();++ // The device opens successfully, but /dev/null rejects the AMD ioctl.+ assert!(!render_devices_ready(dri.path(), sysfs.path()));+ }+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex f5329eeda..349890ef4 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -2,21 +2,8 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]fn main() {- // 在 Linux 上设置 WebKit 环境变量以解决 DMA-BUF 渲染问题- // 某些 Linux 系统(如 Debian 13.2、Nvidia GPU)上 WebKitGTK 的 DMA-BUF 渲染器可能导致白屏/黑屏- // 参考: https://github.com/tauri-apps/tauri/issues/9394#[cfg(target_os = "linux")]{- if std::env::var("WEBKIT_DISABLE_DMABUF_RENDERER").is_err() {- std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");- }- // 禁用 WebKitGTK 合成模式,规避 resize 时 webview 崩溃以及部分 Wayland- // 合成器下的 surface 协商问题(整窗 UI 点击无响应、必须最大化-还原才能恢复)。- // 参考: https://github.com/tauri-apps/tauri/issues/9394- if std::env::var("WEBKIT_DISABLE_COMPOSITING_MODE").is_err() {- std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");- }-// AppImage 的 GTK 启动钩子 (linuxdeploy-plugin-gtk.sh) 会无条件// `export GDK_BACKEND=x11` 强制走 XWayland,以规避历史上的 Wayland 崩溃// (tauri-apps/tauri#8541)。但在较新的 Wayland + NVIDIA 环境下,强制 XWaylanddiff --git a/src-tauri/src/tray_panel.rs b/src-tauri/src/tray_panel.rsindex d0907a3c4..98f523679 100644--- a/src-tauri/src/tray_panel.rs+++ b/src-tauri/src/tray_panel.rs@@ -7,13 +7,16 @@//! 两块卡片各垫一块,中间留缝。//! - Windows:固定透明画布,网页只为卡片绘制不透明背景,两块卡片并成两栏;//! 原生窗口区域跟随卡片裁剪,画布其余部分透明且不拦截鼠标。-//! - Linux:AppIndicator 不派发点击事件,点图标仍是原生菜单,菜单最上面一项打开面板;没有原生模糊,-//! 使用不透明窗口和实色画布,避开 WebKitGTK 的透明合成问题。+//! - Linux:从 AppIndicator 原生菜单打开面板。支持背景模糊的 Wayland 合成器使用原生模糊,+//! 其余情况使用实色画布。//!//! 面板只换了外观:每一行沿用原生菜单的事件 id,点击走 `tray::handle_tray_menu_event`,//! 切换、路由、故障转移的行为和原生菜单一致。窗口懒创建,之后只隐藏不销毁;失焦即隐藏。use crate::sync_utils::MutexExt;++#[cfg(target_os = "linux")]+mod wayland_blur;use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::Mutex;use std::time::{Duration, Instant};@@ -34,6 +37,8 @@ pub fn uses_native_menu() -> bool {/// 弹出前发给面板:带上这次的方位,前端据此排版后回报尺寸(`tray_panel_layout`)。const SHOW_EVENT: &str = "tray-panel-show";+#[cfg(target_os = "linux")]+const GLASS_EVENT: &str = "tray-panel-glass";/// 收起时发给面板:让隐藏态下的用量页暂停定时轮询。const HIDE_EVENT: &str = "tray-panel-hide";/// 托盘状态变了(切换、额度、问题区),面板重新取数据。@@ -66,7 +71,6 @@ mod style {#[cfg(not(any(target_os = "macos", target_os = "windows")))]mod style {pub const LAYOUT: &str = "joined";- /// 没有原生模糊;面板用不透明窗口和实色画布(见 tray-panel.css),不画半透明毛玻璃pub const GLASS: &str = "frosted";pub const CARD_GAP: f64 = 0.0;pub const RADIUS: f64 = 12.0;@@ -377,7 +381,7 @@ fn place(gap,radius: style::RADIUS,layout: style::LAYOUT,- glass: platform::glass(),+ glass: style::GLASS,texts,};(x, y, placement)@@ -433,6 +437,10 @@ fn ensure_window(app: &AppHandle) -> Option<WebviewWindow> {fn create_window(app: &AppHandle) -> tauri::Result<WebviewWindow> {// 新窗口还没套过深浅色(轻量模式下面板收起即销毁,会反复新建)。*APPLIED_DARK.lock_recover() = None;+ #[cfg(target_os = "linux")]+ let transparent = wayland_blur::supports_blur(app);+ #[cfg(not(target_os = "linux"))]+ let transparent = !cfg!(target_os = "linux");let window =WebviewWindowBuilder::new(app, PANEL_LABEL, WebviewUrl::App("tray-panel.html".into())).title("CC Switch")@@ -441,9 +449,7 @@ fn create_window(app: &AppHandle) -> tauri::Result<WebviewWindow> {.maximizable(false).minimizable(false).decorations(false)- // Linux uses a rectangular opaque canvas: transparent WebKitGTK- // surfaces can lose damaged regions after lightweight recreation (#9216).- .transparent(!cfg!(target_os = "linux"))+ .transparent(transparent)// Windows 使用固定透明画布,整窗系统阴影会暴露画布的外框。.shadow(!cfg!(target_os = "windows")).always_on_top(true)@@ -453,6 +459,10 @@ fn create_window(app: &AppHandle) -> tauri::Result<WebviewWindow> {.focused(false).build()?;platform::init(&window);+ #[cfg(target_os = "linux")]+ if transparent {+ wayland_blur::attach(&window);+ }let handle = window.clone();window.on_window_event(move |event| match event {@@ -567,6 +577,36 @@ fn show_at(app: &AppHandle, window: &WebviewWindow, icon: (f64, f64, f64, f64))});}+#[cfg(target_os = "linux")]+fn set_wayland_glass(app: &AppHandle, enabled: bool) {+ #[derive(Clone, Serialize)]+ struct GlassUpdate {+ seq: u64,+ glass: &'static str,+ }++ let glass = if enabled {+ "wayland-blur"+ } else {+ style::GLASS+ };+ let update = {+ let mut anchor = ANCHOR.lock_recover();+ let Some(anchor) = anchor.as_mut() else {+ return;+ };+ if anchor.placement.glass == glass {+ return;+ }+ anchor.placement.glass = glass;+ GlassUpdate {+ seq: anchor.placement.seq,+ glass,+ }+ };+ let _ = app.emit_to(PANEL_LABEL, GLASS_EVENT, update);+}+/// 点托盘图标:开着就关,关着就在图标旁弹出。`rect` 是点击事件带的图标矩形。pub fn toggle(app: &AppHandle, rect: &tauri::Rect) {if let Some(window) = panel_window(app) {@@ -661,8 +701,11 @@ pub fn notify_changed(app: &AppHandle) {/// 卡片在窗口里的位置(逻辑像素,左上角为原点)。#[derive(Debug, Clone, Copy, Deserialize)]#[serde(rename_all = "camelCase")]-// macOS 按卡片位置垫玻璃,Windows 据此裁剪原生窗口区域。-#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]+// 各平台按卡片位置摆放模糊区域或裁剪窗口。+#[cfg_attr(+ not(any(target_os = "macos", target_os = "windows", target_os = "linux")),+ allow(dead_code)+)]pub struct CardRect {pub x: f64,pub y: f64,@@ -697,10 +740,6 @@ mod platform {use super::{style, CardRect, Frame};- pub fn glass() -> &'static str {- style::GLASS- }-thread_local! {/// 垫在网页下面的玻璃,一块卡片一块(只在主线程上碰)。static GLASS: RefCell<Vec<Retained<NSView>>> = const { RefCell::new(Vec::new()) };@@ -876,10 +915,6 @@ mod platform {/// 整窗 Acrylic 的合成背景不遵循 SetWindowRgn,会把预留画布涂成灰色;/// Windows 在网页卡片内绘制背景,画布本身保持透明。- pub fn glass() -> &'static str {- style::GLASS- }-pub fn init(_window: &WebviewWindow) {}/// 前端回报的是客户区尺寸;带阴影的无边框窗口仍有非客户区,需补回四边,@@ -1150,15 +1185,13 @@ mod platform {mod platform {use tauri::{PhysicalPosition, PhysicalSize, WebviewWindow};- use super::{style, CardRect, Frame};-- pub fn glass() -> &'static str {- style::GLASS- }+ use super::{CardRect, Frame};pub fn init(_window: &WebviewWindow) {}pub fn apply(window: &WebviewWindow, frame: Option<Frame>, scale: f64, _cards: Vec<CardRect>) {+ #[cfg(target_os = "linux")]+ super::wayland_blur::apply(window, &_cards);let Some(frame) = frame else {return;};diff --git a/src-tauri/src/tray_panel/wayland_blur.rs b/src-tauri/src/tray_panel/wayland_blur.rsnew file mode 100644index 000000000..0fbbd02a8--- /dev/null+++ b/src-tauri/src/tray_panel/wayland_blur.rs@@ -0,0 +1,510 @@+use std::cell::Cell;+use std::ffi::{c_char, c_int, c_void, CStr};+use std::ptr::{self, NonNull};+use std::rc::Rc;++use gtk::glib::{translate::ToGlibPtr, ObjectExt, WeakRef};+use gtk::prelude::*;+use tauri::{AppHandle, Manager, WebviewWindow};++use super::{set_wayland_glass, style, CardRect};+use crate::linux_rendering::Rendering;++const GLOBAL_KEY: &str = "cc-switch-wayland-blur-global";+const PANEL_KEY: &str = "cc-switch-wayland-blur-panel";+const BLUR_CAPABILITY: u32 = 1;+const MARSHAL_DESTROY: u32 = 1;+type Proxy = c_void;++#[repr(C)]+struct Interface {+ name: *const c_char,+ version: c_int,+ method_count: c_int,+ methods: *const Message,+ event_count: c_int,+ events: *const Message,+}++#[repr(C)]+struct Message {+ name: *const c_char,+ signature: *const c_char,+ types: *const *const Interface,+}++struct Types<const N: usize>([*const Interface; N]);++// SAFETY: All descriptor pointers reference immutable static Wayland metadata.+unsafe impl Sync for Interface {}+unsafe impl Sync for Message {}+unsafe impl<const N: usize> Sync for Types<N> {}++// Interface metadata from wayland-protocols/staging/ext-background-effect.+static MANAGER: Interface = Interface {+ name: c"ext_background_effect_manager_v1".as_ptr(),+ version: 1,+ method_count: 2,+ methods: MANAGER_REQUESTS.as_ptr(),+ event_count: 1,+ events: MANAGER_EVENTS.as_ptr(),+};+static SURFACE_EFFECT: Interface = Interface {+ name: c"ext_background_effect_surface_v1".as_ptr(),+ version: 1,+ method_count: 2,+ methods: EFFECT_REQUESTS.as_ptr(),+ event_count: 0,+ events: ptr::null(),+};+const DESTROY: Message = Message {+ name: c"destroy".as_ptr(),+ signature: c"".as_ptr(),+ types: ptr::null(),+};+static GET_EFFECT_TYPES: Types<2> = Types([&SURFACE_EFFECT, &raw const wl_surface_interface]);+static REGION_TYPES: Types<1> = Types([&raw const wl_region_interface]);+static FLAG_TYPES: Types<1> = Types([ptr::null()]);+static MANAGER_REQUESTS: [Message; 2] = [+ DESTROY,+ Message {+ name: c"get_background_effect".as_ptr(),+ signature: c"no".as_ptr(),+ types: GET_EFFECT_TYPES.0.as_ptr(),+ },+];+static MANAGER_EVENTS: [Message; 1] = [Message {+ name: c"capabilities".as_ptr(),+ signature: c"u".as_ptr(),+ types: FLAG_TYPES.0.as_ptr(),+}];+static EFFECT_REQUESTS: [Message; 2] = [+ DESTROY,+ Message {+ name: c"set_blur_region".as_ptr(),+ signature: c"?o".as_ptr(),+ types: REGION_TYPES.0.as_ptr(),+ },+];++#[link(name = "wayland-client")]+extern "C" {+ static wl_registry_interface: Interface;+ static wl_surface_interface: Interface;+ static wl_region_interface: Interface;+ fn wl_display_create_queue(display: *mut Proxy) -> *mut c_void;+ fn wl_display_roundtrip_queue(display: *mut Proxy, queue: *mut c_void) -> c_int;+ fn wl_event_queue_destroy(queue: *mut c_void);+ fn wl_proxy_create_wrapper(proxy: *mut Proxy) -> *mut Proxy;+ fn wl_proxy_wrapper_destroy(wrapper: *mut Proxy);+ fn wl_proxy_set_queue(proxy: *mut Proxy, queue: *mut c_void);+ fn wl_proxy_get_version(proxy: *mut Proxy) -> u32;+ fn wl_proxy_add_listener(+ proxy: *mut Proxy,+ listener: *const c_void,+ data: *mut c_void,+ ) -> c_int;+ fn wl_proxy_marshal_flags(+ proxy: *mut Proxy,+ opcode: u32,+ interface: *const Interface,+ version: u32,+ flags: u32,+ ...+ ) -> *mut Proxy;+}++extern "C" {+ fn gdk_wayland_display_get_wl_display(display: *mut gtk::gdk::ffi::GdkDisplay) -> *mut Proxy;+ fn gdk_wayland_display_get_wl_compositor(display: *mut gtk::gdk::ffi::GdkDisplay)+ -> *mut Proxy;+ fn gdk_wayland_window_get_wl_surface(window: *mut gtk::gdk::ffi::GdkWindow) -> *mut Proxy;+}++#[repr(C)]+struct RegistryListener {+ global: unsafe extern "C" fn(*mut c_void, *mut Proxy, u32, *const c_char, u32),+ remove: unsafe extern "C" fn(*mut c_void, *mut Proxy, u32),+}++#[repr(C)]+struct ManagerListener {+ capabilities: unsafe extern "C" fn(*mut c_void, *mut Proxy, u32),+}++static REGISTRY_LISTENER: RegistryListener = RegistryListener {+ global: registry_global,+ remove: registry_remove,+};+static MANAGER_LISTENER: ManagerListener = ManagerListener { capabilities };++#[derive(Default)]+struct BlurGlobal {+ manager: Cell<Option<(u32, NonNull<Proxy>)>>,+ can_blur: Cell<bool>,+ panel: WeakRef<gtk::ApplicationWindow>,+}++impl BlurGlobal {+ fn manager(&self) -> Option<NonNull<Proxy>> {+ self.manager+ .get()+ .and_then(|(_, manager)| self.can_blur.get().then_some(manager))+ }++ fn set_capability(&self, can_blur: bool) {+ if self.can_blur.replace(can_blur) == can_blur {+ return;+ }+ // Reapply the cached bounds on recovery even if the layout is unchanged.+ if let Some(widget) = self.panel.upgrade().filter(|widget| widget.is_mapped()) {+ // SAFETY: The live widget owns the state installed by attach().+ if let Some(panel) = unsafe { widget.data::<Rc<PanelBlur>>(PANEL_KEY) } {+ unsafe { panel.as_ref() }.sync(&widget);+ }+ }+ }++ fn discover(display: >k::gdk::Display) -> Option<Box<Self>> {+ let global = Box::new(Self::default());+ // SAFETY: Only called for a live Wayland GdkDisplay on the GTK thread.+ // The private queue keeps the initial round trips from dispatching GTK+ // events reentrantly. The registry and its listener survive on GDK's+ // connection until it closes.+ unsafe {+ let connection = gdk_wayland_display_get_wl_display(display.to_glib_none().0);+ let queue = NonNull::new(wl_display_create_queue(connection))?;+ let registry = NonNull::new(wl_proxy_create_wrapper(connection)).and_then(|wrapper| {+ let wrapper = wrapper.as_ptr();+ wl_proxy_set_queue(wrapper, queue.as_ptr());+ let registry = wl_proxy_marshal_flags(+ wrapper,+ 1,+ &wl_registry_interface,+ wl_proxy_get_version(wrapper),+ 0,+ ptr::null_mut::<Proxy>(),+ );+ wl_proxy_wrapper_destroy(wrapper);+ NonNull::new(registry)+ });+ if let Some(registry) = registry {+ let data = ptr::from_ref(global.as_ref()).cast_mut().cast();+ let registry = registry.as_ptr();+ wl_proxy_add_listener(registry, ptr::from_ref(®ISTRY_LISTENER).cast(), data);+ if wl_display_roundtrip_queue(connection, queue.as_ptr()) >= 0+ && global.manager.get().is_some()+ {+ wl_display_roundtrip_queue(connection, queue.as_ptr());+ }+ // GTK dispatches future capability changes on the default queue.+ wl_proxy_set_queue(registry, ptr::null_mut());+ if let Some((_, manager)) = global.manager.get() {+ wl_proxy_set_queue(manager.as_ptr(), ptr::null_mut());+ }+ }+ wl_event_queue_destroy(queue.as_ptr());+ registry?;+ }+ Some(global)+ }++ fn for_display(display: >k::gdk::Display) -> Option<NonNull<Self>> {+ if display.is_closed() || display.type_().name() != "GdkWaylandDisplay" {+ return None;+ }+ // SAFETY: This private key always stores the listener state. Its address+ // is stable for the life of the GdkDisplay that dispatches its events.+ unsafe {+ if display.data::<Box<BlurGlobal>>(GLOBAL_KEY).is_none() {+ display.set_data(GLOBAL_KEY, Self::discover(display)?);+ }+ let global = display.data::<Box<BlurGlobal>>(GLOBAL_KEY)?.as_ref();+ Some(NonNull::from(global.as_ref()))+ }+ }+}++unsafe extern "C" fn registry_global(+ data: *mut c_void,+ registry: *mut Proxy,+ name: u32,+ interface: *const c_char,+ version: u32,+) {+ let global = &*data.cast::<BlurGlobal>();+ if version < 1+ || global.manager.get().is_some()+ || CStr::from_ptr(interface) != c"ext_background_effect_manager_v1"+ {+ return;+ }+ let manager = wl_proxy_marshal_flags(+ registry,+ 0,+ &MANAGER,+ 1,+ 0,+ name,+ MANAGER.name,+ 1_u32,+ ptr::null_mut::<Proxy>(),+ );+ if let Some(manager) = NonNull::new(manager) {+ wl_proxy_add_listener(+ manager.as_ptr(),+ ptr::from_ref(&MANAGER_LISTENER).cast(),+ data,+ );+ global.manager.set(Some((name, manager)));+ }+}++unsafe extern "C" fn registry_remove(data: *mut c_void, _: *mut Proxy, name: u32) {+ let global = &*data.cast::<BlurGlobal>();+ if let Some((_, manager)) = global.manager.get().filter(|&(id, _)| id == name) {+ global.manager.set(None);+ destroy(manager);+ global.set_capability(false);+ }+}++unsafe extern "C" fn capabilities(data: *mut c_void, _: *mut Proxy, flags: u32) {+ (&*data.cast::<BlurGlobal>()).set_capability(flags & BLUR_CAPABILITY != 0);+}++unsafe fn destroy(proxy: NonNull<Proxy>) {+ let proxy = proxy.as_ptr();+ wl_proxy_marshal_flags(+ proxy,+ 0,+ ptr::null(),+ wl_proxy_get_version(proxy),+ MARSHAL_DESTROY,+ );+}++#[derive(Clone, Copy, PartialEq, Eq)]+struct Bounds {+ x: i32,+ y: i32,+ width: i32,+ height: i32,+}++impl Bounds {+ fn from_cards(cards: &[CardRect]) -> Option<Self> {+ let mut bounds = None::<(f64, f64, f64, f64)>;+ for card in cards.iter().take(2) {+ let right = card.x + card.width;+ let bottom = card.y + card.height;+ if card.width <= 0.0+ || card.height <= 0.0+ || [card.x, card.y, right, bottom]+ .iter()+ .any(|value| !(0.0..=32767.0).contains(value))+ {+ continue;+ }+ bounds = Some(match bounds {+ None => (card.x, card.y, right, bottom),+ Some((x, y, r, b)) => (x.min(card.x), y.min(card.y), r.max(right), b.max(bottom)),+ });+ }+ // The joined Linux layout covers one contiguous rectangle.+ bounds.map(|(x, y, right, bottom)| {+ let x = x.floor() as i32;+ let y = y.floor() as i32;+ Self {+ x,+ y,+ width: right.ceil() as i32 - x,+ height: bottom.ceil() as i32 - y,+ }+ })+ }++ fn rounded(self, mut add: impl FnMut(i32, i32, i32, i32)) {+ let radius = (style::RADIUS as i32).min(self.width.min(self.height) / 2);+ let diameter = 2 * radius;+ if self.height > diameter {+ add(self.x, self.y + radius, self.width, self.height - diameter);+ }+ for row in 0..radius {+ let dy = diameter - 2 * row - 1;+ let inset = (0..radius)+ .find(|&inset| {+ let dx = diameter - 2 * inset - 1;+ dx * dx + dy * dy <= diameter * diameter+ })+ .unwrap_or(radius);+ let width = self.width - 2 * inset;+ if width > 0 {+ add(self.x + inset, self.y + row, width, 1);+ add(self.x + inset, self.y + self.height - 1 - row, width, 1);+ }+ }+ }+}++struct PanelBlur {+ app: AppHandle,+ effect: Cell<Option<NonNull<Proxy>>>,+ bounds: Cell<Option<Bounds>>,+}++impl PanelBlur {+ fn sync(&self, widget: >k::ApplicationWindow) {+ if widget.is_mapped() {+ set_wayland_glass(&self.app, self.apply(widget));+ }+ }++ fn apply(&self, widget: >k::ApplicationWindow) -> bool {+ let Some(window) = widget.window() else {+ return false;+ };+ let display = gtk::prelude::WidgetExt::display(widget);+ // SAFETY: The display owns the listener state while we use it.+ let Some(manager) = BlurGlobal::for_display(&display)+ .and_then(|global| unsafe { global.as_ref() }.manager())+ else {+ return false;+ };+ let bounds = self.bounds.get();+ // SAFETY: GTK owns the currently mapped wl_surface. Requests are sent on+ // its thread and the effect is released synchronously when GTK unmaps it.+ unsafe {+ let surface = gdk_wayland_window_get_wl_surface(window.to_glib_none().0);+ if surface.is_null() {+ return false;+ }+ let effect = self.effect.get().or_else(|| {+ let effect = NonNull::new(wl_proxy_marshal_flags(+ manager.as_ptr(),+ 1,+ &SURFACE_EFFECT,+ 1,+ 0,+ ptr::null_mut::<Proxy>(),+ surface,+ ));+ self.effect.set(effect);+ effect+ });+ let Some(effect) = effect else { return false };+ let mut region = None;+ if let Some(bounds) = bounds {+ let compositor = gdk_wayland_display_get_wl_compositor(display.to_glib_none().0);+ let version = wl_proxy_get_version(compositor);+ region = NonNull::new(wl_proxy_marshal_flags(+ compositor,+ 1,+ &wl_region_interface,+ version,+ 0,+ ptr::null_mut::<Proxy>(),+ ));+ let Some(region) = region else { return false };+ bounds.rounded(|x, y, width, height| {+ wl_proxy_marshal_flags(+ region.as_ptr(),+ 1,+ ptr::null(),+ 1,+ 0,+ x,+ y,+ width,+ height,+ );+ });+ }+ wl_proxy_marshal_flags(+ effect.as_ptr(),+ 1,+ ptr::null(),+ 1,+ 0,+ region.map_or(ptr::null_mut(), NonNull::as_ptr),+ );+ if let Some(region) = region {+ destroy(region);+ }+ }+ // The region is double-buffered; GTK commits the surface on redraw.+ widget.queue_draw();+ bounds.is_some()+ }++ fn unmap(&self, widget: >k::ApplicationWindow) {+ // SAFETY: The protocol permits destroying the effect after its surface+ // is gone. GTK3 destroys and recreates the wl_surface around each hide.+ if let Some(effect) = self+ .effect+ .take()+ .filter(|_| !gtk::prelude::WidgetExt::display(widget).is_closed())+ {+ unsafe { destroy(effect) };+ }+ }+}++pub(super) fn supports_blur(app: &AppHandle) -> bool {+ gtk::is_initialized_main_thread()+ && gtk::gdk::Display::default().is_some_and(|display| {+ display.default_screen().rgba_visual().is_some()+ && BlurGlobal::for_display(&display)+ // SAFETY: The display owns the listener state while we use it.+ .is_some_and(|global| unsafe { global.as_ref() }.manager().is_some())+ })+ && app+ .try_state::<Rendering>()+ .is_some_and(|rendering| rendering.supports_transparent_windows())+}++pub(super) fn attach(window: &WebviewWindow) {+ if !gtk::is_initialized_main_thread() {+ return;+ }+ let Ok(widget) = window.gtk_window() else {+ return;+ };+ let display = gtk::prelude::WidgetExt::display(&widget);+ let Some(global) = BlurGlobal::for_display(&display) else {+ return;+ };+ let panel = Rc::new(PanelBlur {+ app: window.app_handle().clone(),+ effect: Cell::default(),+ bounds: Cell::default(),+ });+ // SAFETY: The display owns the listener state. This private key is only+ // used for the blur state on this widget.+ unsafe {+ global.as_ref().panel.set(Some(&widget));+ widget.set_data(PANEL_KEY, panel.clone());+ }+ let on_map = panel.clone();+ widget.connect_map(move |widget| on_map.sync(widget));+ let on_unmap = panel.clone();+ widget.connect_unmap(move |widget| on_unmap.unmap(widget));+ widget.connect_destroy(move |widget| panel.unmap(widget));+}++pub(super) fn apply(window: &WebviewWindow, cards: &[CardRect]) {+ if !gtk::is_initialized_main_thread() {+ return;+ }+ let Ok(widget) = window.gtk_window() else {+ return;+ };+ // SAFETY: The widget owns its blur state for the duration of this call.+ if let Some(panel) = unsafe { widget.data::<Rc<PanelBlur>>(PANEL_KEY) } {+ let panel = unsafe { panel.as_ref() };+ let bounds = Bounds::from_cards(cards);+ if panel.bounds.replace(bounds) != bounds {+ panel.sync(&widget);+ }+ }+}diff --git a/src/tray-panel/TrayPanel.tsx b/src/tray-panel/TrayPanel.tsxindex 597b5d167..6ec0b11be 100644--- a/src/tray-panel/TrayPanel.tsx+++ b/src/tray-panel/TrayPanel.tsx@@ -36,6 +36,7 @@ import { cn } from "@/lib/utils";import type { AppMode } from "@/types/proxy";import {CHANGED_EVENT,+ GLASS_EVENT,HIDE_EVENT,SHOW_EVENT,trayPanelApi,@@ -786,6 +787,15 @@ function FooterButton({export function TrayPanel() {const [nativePlacement, setPlacement] = useState<PanelPlacement | null>(null);+ const [glassUpdate, setGlassUpdate] = useState<Pick<+ PanelPlacement,+ "seq" | "glass"+ > | null>(null);+ const glass =+ glassUpdate && glassUpdate.seq === nativePlacement?.seq+ ? glassUpdate.glass+ : nativePlacement?.glass;+ const layout = nativePlacement?.layout;const [pixelRatio, setPixelRatio] = useState(window.devicePixelRatio || 1);// 将 CSS 像素换算为原生窗口逻辑像素,适配文本和 WebKit 缩放。const coordinateScale =@@ -929,6 +939,13 @@ export function TrayPanel() {let disposed = false;const offs: Array<() => void> = [];void (async () => {+ const offGlass = await listen<Pick<PanelPlacement, "seq" | "glass">>(+ GLASS_EVENT,+ ({ payload }) =>+ setGlassUpdate((current) =>+ current && current.seq > payload.seq ? current : payload,+ ),+ );const offShow = await listen<PanelPlacement>(SHOW_EVENT, (event) => {void begin(event.payload);});@@ -936,13 +953,11 @@ export function TrayPanel() {setPanelVisible(false);});const offChanged = await listen(CHANGED_EVENT, () => void load());+ offs.push(offGlass, offShow, offHide, offChanged);if (disposed) {- offShow();- offHide();- offChanged();+ offs.forEach((off) => off());return;}- offs.push(offShow, offHide, offChanged);// 第一次弹出时窗口是新建的,事件可能早于这里开始监听const pending = await trayPanelApi.placement();if (pending && !disposed) void begin(pending);@@ -953,11 +968,11 @@ export function TrayPanel() {};}, [begin, load]);- useEffect(() => {- if (!placement) return;- document.documentElement.dataset.glass = placement.glass;- document.documentElement.dataset.layout = placement.layout;- }, [placement]);+ useLayoutEffect(() => {+ if (!glass || !layout) return;+ document.documentElement.dataset.glass = glass;+ document.documentElement.dataset.layout = layout;+ }, [glass, layout]);const apps = state?.apps ?? [];const openEntry =diff --git a/src/tray-panel/api.ts b/src/tray-panel/api.tsindex ee9e3366b..549077477 100644--- a/src/tray-panel/api.ts+++ b/src/tray-panel/api.ts@@ -112,7 +112,7 @@ export interface PanelPlacement {gap: number;radius: number;layout: "floating" | "joined";- glass: "native" | "frosted";+ glass: "native" | "wayland-blur" | "frosted";texts: PanelTexts;}@@ -134,6 +134,7 @@ export interface PanelLayout {}export const SHOW_EVENT = "tray-panel-show";+export const GLASS_EVENT = "tray-panel-glass";export const HIDE_EVENT = "tray-panel-hide";export const CHANGED_EVENT = "tray-panel-changed";diff --git a/src/tray-panel/tray-panel.css b/src/tray-panel/tray-panel.cssindex e13ef430f..cc429f030 100644--- a/src/tray-panel/tray-panel.css+++ b/src/tray-panel/tray-panel.css@@ -1,4 +1,4 @@-/* macOS 背景交给系统玻璃;Windows 保留透明画布,Linux 在内层画布铺实色。 */+/* 系统模糊和 Windows 使用透明画布,Linux 回退模式在内层画布铺实色。 */html,body.tray-panel,body.tray-panel #root {@@ -68,20 +68,28 @@ html.dark[data-glass="frosted"] .tp-card {inset 0 1px 0 rgba(255, 255, 255, 0.1);}-/* Windows / Linux:卡片自己提供完整底色,避免桌面内容透进菜单。- Linux WebKitGTK 使用软件渲染;不依赖 backdrop-filter 的合成层,避免轻量模式- 重建面板后悬停或调整大小时出现透明缺块(#9216)。+/* Wayland 由合成器模糊窗口后方的内容,卡片仅画半透明底色。 */+html[data-glass="wayland-blur"] .tp-card {+ background: rgba(235, 235, 237, 0.76);+}+html.dark[data-glass="wayland-blur"] .tp-card {+ background: rgba(36, 36, 40, 0.74);+}++/* Windows / Linux 回退:卡片自己提供完整底色,避免桌面内容透进菜单。+ Linux WebKitGTK 回退到软件渲染时,实色画布可避免轻量模式重建面板后+ 悬停或调整大小时出现透明缺块(#9216)。保留卡片上的控件、选中态和用量区块的层次;Windows 卡片之外的画布仍透明。 */html [data-platform="windows"] .tp-card,-html [data-platform="linux"],-html [data-platform="linux"] .tp-card {+html:not([data-glass="wayland-blur"]) [data-platform="linux"],+html:not([data-glass="wayland-blur"]) [data-platform="linux"] .tp-card {background: #ebebed;-webkit-backdrop-filter: none;backdrop-filter: none;}html.dark [data-platform="windows"] .tp-card,-html.dark [data-platform="linux"],-html.dark [data-platform="linux"] .tp-card {+html.dark:not([data-glass="wayland-blur"]) [data-platform="linux"],+html.dark:not([data-glass="wayland-blur"]) [data-platform="linux"] .tp-card {background: #242428;}diff --git a/tests/components/TrayPanel.styles.test.ts b/tests/components/TrayPanel.styles.test.tsindex 402f92072..59e856865 100644--- a/tests/components/TrayPanel.styles.test.ts+++ b/tests/components/TrayPanel.styles.test.ts@@ -24,9 +24,13 @@ afterEach(() => {else root.dataset.layout = originalLayout;});-function cardFor(platform: "windows" | "macos" | "linux", dark: boolean) {+function cardFor(+ platform: "windows" | "macos" | "linux",+ dark: boolean,+ glass = platform === "macos" ? "native" : "frosted",+) {root.classList.toggle("dark", dark);- root.dataset.glass = platform === "macos" ? "native" : "frosted";+ root.dataset.glass = glass;root.dataset.layout = platform === "macos" ? "floating" : "joined";canvas = document.createElement("div");canvas.dataset.platform = platform;@@ -59,6 +63,18 @@ describe("TrayPanel backgrounds stay scoped to each platform", () => {},);+ it.each([false, true])(+ "uses a translucent tint over compositor blur on Wayland (dark=%s)",+ (dark) => {+ const style = cardFor("linux", dark, "wayland-blur");+ expect(style.backgroundColor).toBe(+ dark ? "rgba(36, 36, 40, 0.74)" : "rgba(235, 235, 237, 0.76)",+ );+ expect(style.getPropertyValue("backdrop-filter")).not.toContain("blur(");+ expect(getComputedStyle(canvas).backgroundColor).toBe("rgba(0, 0, 0, 0)");+ },+ );+it.each([false, true])("preserves the macOS overlay on native glass (dark=%s)",(dark) => {diff --git a/tests/components/TrayPanel.test.tsx b/tests/components/TrayPanel.test.tsxindex 975d07fd6..c7822f8da 100644--- a/tests/components/TrayPanel.test.tsx+++ b/tests/components/TrayPanel.test.tsx@@ -15,6 +15,7 @@ import {} from "@/tray-panel/TrayPanel";import {CHANGED_EVENT,+ GLASS_EVENT,SHOW_EVENT,trayPanelApi,type PanelPlacement,@@ -172,6 +173,26 @@ describe("TrayPanel window layout", () => {delete document.documentElement.dataset.layout;});+ it("updates Wayland glass in place when compositor blur is withdrawn and restored", async () => {+ const linux: PanelPlacement = { ...windows, platform: "linux" };+ await openPanel(linux);+ const glass = () => document.documentElement.dataset.glass;+ expect(glass()).toBe("frosted");++ const loads = vi.mocked(trayPanelApi.state).mock.calls.length;+ for (const mode of ["wayland-blur", "frosted", "wayland-blur"] as const) {+ await act(async () => {+ emitTauriEvent(GLASS_EVENT, { seq: linux.seq, glass: mode });+ });+ expect(glass()).toBe(mode);+ }+ await act(async () => {+ emitTauriEvent(GLASS_EVENT, { seq: linux.seq - 1, glass: "frosted" });+ });+ expect(glass()).toBe("wayland-blur");+ expect(trayPanelApi.state).toHaveBeenCalledTimes(loads);+ });+it("colors only the balance amount green, like the provider card", async () => {vi.mocked(trayPanelApi.state).mockResolvedValue({...state,