Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(linux): proper window decorations and reliable theme tracking
Akarshand566f868aa6b
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 2026180e6..5d56cacbe 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -21,6 +21,7 @@ dependencies = ["futures","futures-util","glob",+ "gtk","hex","hmac","hostname",@@ -2719,6 +2720,22 @@ dependencies = ["tokio-native-tls",]+[[package]]+name = "hyper-tls"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"+dependencies = [+ "bytes",+ "http-body-util",+ "hyper 1.7.0",+ "hyper-util",+ "native-tls",+ "tokio",+ "tokio-native-tls",+ "tower-service",+]+[[package]]name = "hyper-util"version = "0.1.17"@@ -4031,15 +4048,6 @@ version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"-[[package]]-name = "openssl-src"-version = "300.5.3+3.5.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc6bad8cd0233b63971e232cc9c5e83039375b8586d2312f31fda85db8f888c2"-dependencies = [- "cc",-]-[[package]]name = "openssl-sys"version = "0.9.109"@@ -4048,7 +4056,6 @@ checksum = "90096e2e47630d78b7d1c20952dc621f957103f8bc2c8359ec81290d75238571"dependencies = ["cc","libc",- "openssl-src","pkg-config","vcpkg",]@@ -4982,7 +4989,7 @@ dependencies = ["http-body 0.4.6","hyper 0.14.32","hyper-rustls 0.24.2",- "hyper-tls",+ "hyper-tls 0.5.0","ipnet","js-sys","log",@@ -5031,10 +5038,12 @@ dependencies = ["http-body-util","hyper 1.7.0","hyper-rustls 0.27.7",+ "hyper-tls 0.6.0","hyper-util","js-sys","log","mime",+ "native-tls","percent-encoding","pin-project-lite","quinn",@@ -5045,6 +5054,7 @@ dependencies = ["serde_urlencoded","sync_wrapper 1.0.2","tokio",+ "tokio-native-tls","tokio-rustls 0.26.4","tokio-util","tower",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex e111f56d4..6b11b2826 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -153,6 +153,7 @@ libc = "0.2"[target.'cfg(target_os = "linux")'.dependencies]zbus = { version = "5", default-features = false, features = ["tokio"] }+gtk = "0.18"[target.'cfg(windows)'.dependencies]libc = "0.2.172"diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rsindex 2c63d7157..c97b4ee10 100644--- a/src-tauri/src/core/setup.rs+++ b/src-tauri/src/core/setup.rs@@ -390,6 +390,47 @@ pub fn setup_tray(app: &App) -> tauri::Result<TrayIcon> {.build(app)}+/// Install a real GTK `HeaderBar` on the main window so GNOME (and any other+/// CSD-only compositor) gets native min/max/close buttons, drag, system menu,+/// and proper shadows instead of wry's bare-bones default CSD. KDE/XFCE keep+/// using SSD; this only takes effect when GTK falls back to CSD.+#[cfg(target_os = "linux")]+pub fn install_gtk_headerbar<R: Runtime>(app: &App<R>) {+ use gtk::prelude::*;++ // CSD-only DEs (GNOME, Pantheon) need a real HeaderBar; KDE/XFCE provide+ // SSD via xdg-decoration and would render a double titlebar if we install+ // one here. Match the desktop session to keep this opt-in.+ let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();+ let is_csd_desktop = desktop+ .split(':')+ .any(|d| matches!(d, "GNOME" | "GNOME-Classic" | "Unity" | "Pantheon"));+ if !is_csd_desktop {+ log::info!(+ "install_gtk_headerbar: skipping on XDG_CURRENT_DESKTOP={desktop:?} (not CSD-only)"+ );+ return;+ }++ let Some(window) = app.get_webview_window("main") else {+ return;+ };+ let gtk_window = match window.gtk_window() {+ Ok(w) => w,+ Err(e) => {+ log::warn!("install_gtk_headerbar: gtk_window() failed: {e}");+ return;+ }+ };++ let header = gtk::HeaderBar::builder()+ .show_close_button(true)+ .title("Jan")+ .build();+ header.show_all();+ gtk_window.set_titlebar(Some(&header));+}+pub fn setup_theme_listener<R: Runtime>(app: &App<R>) -> tauri::Result<()> {// Setup GTK window theme listener for main windowif let Some(window) = app.get_webview_window("main") {@@ -414,6 +455,83 @@ pub fn setup_theme_listener<R: Runtime>(app: &App<R>) -> tauri::Result<()> {Ok(())}+/// Read the current XDG Desktop Portal `org.freedesktop.appearance/color-scheme`+/// setting. Returns "dark", "light", or `None` if the portal reports no preference+/// or is unavailable.+#[cfg(target_os = "linux")]+async fn read_xdg_portal_color_scheme() -> Result<Option<&'static str>, Box<dyn std::error::Error>>+{+ use zbus::Connection;++ let connection = Connection::session().await?;+ let proxy: zbus::Proxy<'_> = zbus::proxy::Builder::new(&connection)+ .destination("org.freedesktop.portal.Desktop")?+ .path("/org/freedesktop/portal/desktop")?+ .interface("org.freedesktop.portal.Settings")?+ .build()+ .await?;++ let reply: zbus::zvariant::OwnedValue = proxy+ .call("Read", &("org.freedesktop.appearance", "color-scheme"))+ .await?;++ let inner: zbus::zvariant::OwnedValue = match reply.downcast_ref::<zbus::zvariant::Value>() {+ Ok(v) => v.try_to_owned()?,+ Err(_) => reply,+ };+ let color_scheme = u32::try_from(inner).unwrap_or(0);+ // GNOME emits 0 ("no preference") for light, 1 for dark, 2 for explicit+ // light (rare). Treat 0 and 2 as light so light↔dark toggles work on both+ // GNOME and KDE/freedesktop-compliant DEs.+ Ok(match color_scheme {+ 1 => Some("dark"),+ _ => Some("light"),+ })+}++/// Flip GTK's `gtk-application-prefer-dark-theme` so the native HeaderBar+/// installed by `install_gtk_headerbar` follows the app's effective theme+/// (user override or system). No-op on non-Linux.+#[tauri::command]+pub fn set_gtk_prefer_dark(dark: bool) {+ #[cfg(target_os = "linux")]+ {+ use gtk::prelude::*;+ // GTK objects are not Send; bounce onto the GTK main thread.+ gtk::glib::MainContext::default().invoke(move || {+ if let Some(settings) = gtk::Settings::default() {+ settings.set_gtk_application_prefer_dark_theme(dark);+ }+ });+ }+ #[cfg(not(target_os = "linux"))]+ {+ let _ = dark;+ }+}++#[tauri::command]+pub async fn get_system_theme<R: Runtime>(app: tauri::AppHandle<R>) -> Result<String, String> {+ #[cfg(target_os = "linux")]+ {+ match read_xdg_portal_color_scheme().await {+ Ok(Some(theme)) => return Ok(theme.to_string()),+ Ok(None) => {}+ Err(e) => log::warn!("get_system_theme: portal read failed: {e}"),+ }+ }++ if let Some(window) = app.get_webview_window("main") {+ if let Ok(theme) = window.theme() {+ return Ok(match theme {+ tauri::Theme::Dark => "dark".to_string(),+ _ => "light".to_string(),+ });+ }+ }+ Ok("light".to_string())+}+/// Listen to the XDG Desktop Portal `org.freedesktop.appearance` `color-scheme`/// setting via D-Bus. This fires reliably on KDE Plasma, GNOME, and other/// freedesktop-compliant desktop environments.@@ -439,6 +557,17 @@ async fn setup_xdg_portal_theme_listener<R: Runtime>(log::info!("XDG Desktop Portal theme listener active");+ // Emit the current value so the frontend doesn't have to wait for the first+ // SettingChanged signal to learn the system color-scheme on startup.+ match read_xdg_portal_color_scheme().await {+ Ok(Some(theme_str)) => {+ log::info!("XDG Portal: initial system color-scheme: {theme_str}");+ let _ = app_handle.emit("theme-changed", theme_str);+ }+ Ok(None) => log::info!("XDG Portal: initial color-scheme is 'no preference'"),+ Err(e) => log::warn!("XDG Portal: initial Read failed: {e}"),+ }+while let Some(signal) = signal_stream.next().await {let body = signal.body();if let Ok((namespace, key, value)) =@@ -449,8 +578,7 @@ async fn setup_xdg_portal_theme_listener<R: Runtime>(let color_scheme = u32::try_from(value).unwrap_or(0);let theme_str = match color_scheme {1 => "dark",- 2 => "light",- _ => "light", // default to light for "no preference"+ _ => "light",};log::info!("XDG Portal: system color-scheme changed to: {theme_str} (raw value: {color_scheme})"diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex f3085be5e..a879d3fa4 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -103,6 +103,9 @@ macro_rules! invoke_commands_with_extras {core::downloads::commands::cancel_download_task,// App lifecycleconfirm_exit,+ // Theme+ core::setup::get_system_theme,+ core::setup::set_gtk_prefer_dark,$($extra,)*@@ -336,6 +339,8 @@ pub fn run() {#[cfg(desktop)]setup::setup_jan_cli(app.handle().clone(), stored_version != app_version);setup::setup_theme_listener(app)?;+ #[cfg(target_os = "linux")]+ setup::install_gtk_headerbar(app);Ok(())}).build(tauri::generate_context!())diff --git a/src-tauri/tauri.linux.conf.json b/src-tauri/tauri.linux.conf.jsonindex c6fd26908..36923d21d 100644--- a/src-tauri/tauri.linux.conf.json+++ b/src-tauri/tauri.linux.conf.json@@ -12,18 +12,8 @@"fullscreen": false,"zoomHotkeysEnabled": true,"center": true,- "hiddenTitle": true,"transparent": false,- "trafficLightPosition": {- "x": 20,- "y": 32- },"decorations": true,- "titleBarStyle": "Overlay",- "windowEffects": {- "effects": ["fullScreenUI", "mica", "tabbed", "blur", "acrylic"],- "state": "active"- },"dragDropEnabled": false}]diff --git a/web-app/src/hooks/useTheme.ts b/web-app/src/hooks/useTheme.tsindex 35556a4e7..76d0fbfa5 100644--- a/web-app/src/hooks/useTheme.ts+++ b/web-app/src/hooks/useTheme.ts@@ -27,15 +27,18 @@ export const useTheme = create<ThemeState>()(activeTheme: 'auto' as AppTheme,isDark: checkOSDarkMode(),setTheme: async (activeTheme: AppTheme) => {+ // Commit first so the theme-changed listener (which gates on+ // activeTheme) ignores any portal/WindowEvent fired by the native+ // setTheme call below. Otherwise events arriving while activeTheme+ // is still stale ('auto') overwrite isDark with the system value.if (activeTheme === 'auto') {- const isDarkMode = checkOSDarkMode()+ set(() => ({ activeTheme, isDark: checkOSDarkMode() }))await getServiceHub().theme().setTheme(null)- set(() => ({ activeTheme, isDark: isDarkMode }))} else {+ set(() => ({ activeTheme, isDark: activeTheme === 'dark' }))await getServiceHub().theme().setTheme(activeTheme as ThemeMode)- set(() => ({ activeTheme, isDark: activeTheme === 'dark' }))}},setIsDark: (isDark: boolean) => set(() => ({ isDark })),diff --git a/web-app/src/providers/ThemeProvider.tsx b/web-app/src/providers/ThemeProvider.tsxindex b454e9653..ee0d4f83f 100644--- a/web-app/src/providers/ThemeProvider.tsx+++ b/web-app/src/providers/ThemeProvider.tsx@@ -1,84 +1,77 @@import { useEffect } from 'react'-import { useTheme, checkOSDarkMode } from '@/hooks/useTheme'+import { useTheme } from '@/hooks/useTheme'import { isPlatformTauri } from '@/lib/platform/utils'-/**- * ThemeProvider ensures theme settings are applied on every page load- * This component should be mounted at the root level of the application- * It first detects the OS theme preference and applies it accordingly- */export function ThemeProvider() {- const { activeTheme, isDark, setIsDark, setTheme } = useTheme()+ const { isDark, setIsDark } = useTheme()- // Apply dark class to root elementuseEffect(() => {if (isDark) {document.documentElement.classList.add('dark')} else {document.documentElement.classList.remove('dark')}+ if (IS_LINUX && isPlatformTauri()) {+ import('@tauri-apps/api/core')+ .then(({ invoke }) => invoke('set_gtk_prefer_dark', { dark: isDark }))+ .catch((err) => console.error('set_gtk_prefer_dark failed:', err))+ }}, [isDark])- // Detect OS theme on mount and apply ituseEffect(() => {- // Force refresh theme on mount to handle Linux startup timing issues- const refreshTheme = () => {- if (activeTheme === 'auto') {- const isDarkMode = checkOSDarkMode()- setIsDark(isDarkMode)- setTheme('auto')- }- }-- // Initial refresh- refreshTheme()+ let cancelled = false+ let unlistenTauri: (() => void) | undefined- // On Linux, desktop environment may not be ready immediately- // Add a delayed refresh to catch the correct OS theme- const timeoutId = setTimeout(refreshTheme, 100)+ // Always check the latest activeTheme at event time — calling+ // window.setTheme() from the switcher fires portal/WindowEvent events that+ // would otherwise race the zustand commit and pin isDark to the system+ // value even when the user picked an explicit light/dark override.+ const applyIfAuto = (next: boolean) => {+ if (useTheme.getState().activeTheme === 'auto') setIsDark(next)+ }- // Listen to prefers-color-scheme media query changes- // On Linux with WebKitGTK 2.42+, this reacts to XDG Desktop Portal- // color-scheme changes, which works reliably on KDE Plasma and other DEsconst mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')- const handleMediaChange = (e: MediaQueryListEvent) => {- if (activeTheme === 'auto') {- setIsDark(e.matches)- }- }+ const handleMediaChange = (e: MediaQueryListEvent) => applyIfAuto(e.matches)mediaQuery.addEventListener('change', handleMediaChange)- // Listen to Tauri native theme events (fallback for platforms where- // the media query listener may not fire)- let unlistenTauri: (() => void) | undefined-if (isPlatformTauri()) {- import('@tauri-apps/api/event')- .then(({ listen }) => {- return listen<string>('theme-changed', (event) => {- if (activeTheme === 'auto') {- const isDark = event.payload === 'dark'- setIsDark(isDark)- }+ // On Linux, WebKitGTK's prefers-color-scheme does not reliably track the+ // XDG Desktop Portal. Source-of-truth is the Rust-side portal read ++ // SettingChanged signal, re-emitted as the `theme-changed` event.+ Promise.all([+ import('@tauri-apps/api/event'),+ import('@tauri-apps/api/core'),+ ])+ .then(async ([{ listen }, { invoke }]) => {+ const unlisten = await listen<string>('theme-changed', (event) => {+ applyIfAuto(event.payload === 'dark')})- })- .then((unlisten) => {+ if (cancelled) {+ unlisten()+ return+ }unlistenTauri = unlisten++ try {+ const initial = await invoke<string>('get_system_theme')+ if (!cancelled) applyIfAuto(initial === 'dark')+ } catch (err) {+ console.error('get_system_theme failed:', err)+ }}).catch((err) => {console.error('Failed to setup Tauri theme listener:', err)})+ } else {+ applyIfAuto(mediaQuery.matches)}- // Clean upreturn () => {- clearTimeout(timeoutId)+ cancelled = truemediaQuery.removeEventListener('change', handleMediaChange)- if (unlistenTauri) {- unlistenTauri()- }+ unlistenTauri?.()}- }, [activeTheme, setIsDark, setTheme])+ }, [setIsDark])return null}diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsxindex 3a79736dc..b8cbdf834 100644--- a/web-app/src/routes/__root.tsx+++ b/web-app/src/routes/__root.tsx@@ -21,14 +21,13 @@ import ToolApproval from '@/containers/dialogs/ToolApproval'import { TranslationProvider } from '@/i18n/TranslationContext'import OutOfContextPromiseModal from '@/containers/dialogs/OutOfContextDialog'import AttachmentIngestionDialog from '@/containers/dialogs/AttachmentIngestionDialog'-import { useEffect, type MouseEvent } from 'react'+import { useEffect } from 'react'import GlobalError from '@/containers/GlobalError'import { GlobalEventHandler } from '@/providers/GlobalEventHandler'import { ServiceHubProvider } from '@/providers/ServiceHubProvider'import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'import { LeftSidebar } from '@/components/left-sidebar'import { WindowControls } from '@/components/WindowControls'-import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'import ErrorDialog from '@/containers/dialogs/ErrorDialog'import LlamacppBusyOnExitDialog from '@/containers/dialogs/LlamacppBusyOnExitDialog'import LlamacppOomListener from '@/containers/dialogs/LlamacppOomListener'@@ -61,19 +60,12 @@ const AppLayout = () => {<KeyboardShortcutsProvider />{/* Fake absolute panel top to enable window drag */}{IS_WINDOWS && <WindowControls />}- {IS_TAURI && (+ {IS_TAURI && !IS_LINUX && (<divclassName="fixed w-full h-12 z-20 top-0 cursor-grab active:cursor-grabbing"title="Drag window"aria-label="Window drag area"- {...(IS_LINUX- ? {- onMouseDown: (e: MouseEvent) => {- if (e.button !== 0) return- void getCurrentWebviewWindow().startDragging()- },- }- : { 'data-tauri-drag-region': true as const })}+ data-tauri-drag-region/>)}<DialogAppUpdater />