Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(linux): borderless window with custom titlebar following DE button layout
Akarshan Biswas0f85b119df0e
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 24f119885..486b39009 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -10,6 +10,7 @@"core:default","core:webview:allow-set-webview-zoom","core:window:allow-start-dragging",+ "core:window:allow-start-resize-dragging","core:window:allow-set-theme","core:window:allow-minimize","core:window:allow-toggle-maximize",diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rsindex 0db6d6e08..b15328917 100644--- a/src-tauri/src/core/setup.rs+++ b/src-tauri/src/core/setup.rs@@ -407,54 +407,6 @@ pub fn setup_tray(app: &App) -> tauri::Result<TrayIcon> {.build(app)}-/// Shrink tao's Wayland CSD titlebar (~46px → ~24px) and clear its hardcoded-/// `decoration_layout` so buttons follow GNOME. Do NOT `set_titlebar` here —-/// that replaces tao's drag-enabled HeaderBar and breaks drag/double-click.-#[cfg(target_os = "linux")]-pub fn shrink_gtk_headerbar<R: Runtime>(app: &App<R>) {- use gtk::prelude::*;-- 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!(- "shrink_gtk_headerbar: skipping on XDG_CURRENT_DESKTOP={desktop:?} (not CSD-only)"- );- return;- }-- let css = gtk::CssProvider::new();- let style = b"headerbar { min-height: 24px; padding: 0 4px; } \- headerbar button { min-height: 20px; min-width: 20px; padding: 0 4px; } \- headerbar .title { font-size: 0.9em; }";- if let Err(e) = css.load_from_data(style) {- log::warn!("shrink_gtk_headerbar: css load failed: {e}");- } else if let Some(screen) = gtk::gdk::Screen::default() {- gtk::StyleContext::add_provider_for_screen(- &screen,- &css,- gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,- );- }-- // `None` layout falls back to gtk-decoration-layout, synced from GNOME.- let header = app- .get_webview_window("main")- .and_then(|w| w.gtk_window().ok())- .and_then(|gw| gw.titlebar())- .and_then(|tb| tb.downcast::<gtk::EventBox>().ok())- .and_then(|eb| eb.child())- .and_then(|c| c.downcast::<gtk::HeaderBar>().ok());- match header {- Some(h) => h.set_decoration_layout(None::<&str>),- None => {- log::warn!("shrink_gtk_headerbar: titlebar not the expected EventBox>HeaderBar shape")- }- }-}-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") {@@ -513,6 +465,121 @@ async fn read_xdg_portal_color_scheme() -> Result<Option<&'static str>, Box<dyn})}+/// Window-control placement split by side. Values are `"minimize"`,+/// `"maximize"`, `"close"`; the borderless frontend renders its own buttons in+/// this order so they match the desktop's configured layout.+#[derive(serde::Serialize)]+pub struct TitlebarLayout {+ pub left: Vec<String>,+ pub right: Vec<String>,+}++impl Default for TitlebarLayout {+ fn default() -> Self {+ TitlebarLayout {+ left: vec![],+ right: vec![+ "minimize".to_string(),+ "maximize".to_string(),+ "close".to_string(),+ ],+ }+ }+}++/// Read the desktop's window-button layout so the borderless titlebar can place+/// min/max/close on the side the user configured (KDE `kwinrc`, GNOME gsettings).+/// Falls back to all-on-the-right on non-Linux or when the config is unreadable.+#[tauri::command]+pub fn get_titlebar_layout() -> TitlebarLayout {+ #[cfg(target_os = "linux")]+ {+ let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();+ let is_kde = desktop.split(':').any(|d| d.eq_ignore_ascii_case("KDE"));+ let layout = if is_kde {+ read_kde_button_layout()+ } else {+ read_gnome_button_layout()+ };+ if let Some(layout) = layout {+ return layout;+ }+ }+ TitlebarLayout::default()+}++/// Parse `~/.config/kwinrc` `[org.kde.kdecoration2]` button codes+/// (`I`=minimize, `A`=maximize, `X`=close; others ignored). Defaults match+/// KDE's own (`MS` left / `IAX` right) when the keys are absent.+#[cfg(target_os = "linux")]+fn read_kde_button_layout() -> Option<TitlebarLayout> {+ let home = std::env::var("HOME").ok()?;+ let content =+ fs::read_to_string(PathBuf::from(home).join(".config/kwinrc")).unwrap_or_default();++ let mut left = "MS".to_string();+ let mut right = "IAX".to_string();+ let mut in_section = false;+ for line in content.lines() {+ let line = line.trim();+ if line.starts_with('[') {+ in_section = line == "[org.kde.kdecoration2]";+ } else if in_section {+ if let Some(v) = line.strip_prefix("ButtonsOnLeft=") {+ left = v.trim().to_string();+ } else if let Some(v) = line.strip_prefix("ButtonsOnRight=") {+ right = v.trim().to_string();+ }+ }+ }++ let codes = |s: &str| -> Vec<String> {+ s.chars()+ .filter_map(|c| match c {+ 'I' => Some("minimize".to_string()),+ 'A' => Some("maximize".to_string()),+ 'X' => Some("close".to_string()),+ _ => None,+ })+ .collect()+ };+ Some(TitlebarLayout {+ left: codes(&left),+ right: codes(&right),+ })+}++/// Read GNOME's `button-layout` (`"appmenu:minimize,maximize,close"`); the side+/// before `:` is the left cluster. Unknown tokens (appmenu/icon/spacer) ignored.+#[cfg(target_os = "linux")]+fn read_gnome_button_layout() -> Option<TitlebarLayout> {+ let output = std::process::Command::new("gsettings")+ .args(["get", "org.gnome.desktop.wm.preferences", "button-layout"])+ .output()+ .ok()?;+ if !output.status.success() {+ return None;+ }+ let raw = String::from_utf8_lossy(&output.stdout);+ let raw = raw.trim().trim_matches('\'');+ let (left, right) = raw.split_once(':').unwrap_or(("", raw));++ let tokens = |s: &str| -> Vec<String> {+ s.split(',')+ .filter_map(|t| match t.trim() {+ "minimize" => Some("minimize".to_string()),+ "maximize" => Some("maximize".to_string()),+ "close" => Some("close".to_string()),+ _ => None,+ })+ .collect()+ };+ Some(TitlebarLayout {+ left: tokens(left),+ right: tokens(right),+ })+}+/// Flip GTK's `gtk-application-prefer-dark-theme` so the native Wayland/// HeaderBar follows the app's effective theme (user override or system)./// No-op on non-Linux.diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 85ec8dbe0..e1c6e8803 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -107,6 +107,7 @@ macro_rules! invoke_commands_with_extras {// Themecore::setup::get_system_theme,core::setup::set_gtk_prefer_dark,+ core::setup::get_titlebar_layout,$($extra,)*@@ -340,8 +341,6 @@ 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::shrink_gtk_headerbar(app);Ok(())}).build(tauri::generate_context!())diff --git a/src-tauri/tauri.linux.conf.json b/src-tauri/tauri.linux.conf.jsonindex 36923d21d..f4b440722 100644--- a/src-tauri/tauri.linux.conf.json+++ b/src-tauri/tauri.linux.conf.json@@ -13,7 +13,7 @@"zoomHotkeysEnabled": true,"center": true,"transparent": false,- "decorations": true,+ "decorations": false,"dragDropEnabled": false}]diff --git a/web-app/src/components/WindowControls.tsx b/web-app/src/components/WindowControls.tsxindex d165e15e1..124dc6d93 100644--- a/web-app/src/components/WindowControls.tsx+++ b/web-app/src/components/WindowControls.tsx@@ -1,50 +1,72 @@+import { useEffect, useState } from 'react'import { Minus, Square, X } from 'lucide-react'import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'+import { invoke } from '@tauri-apps/api/core'import { Button } from '@/components/ui/button'+type ButtonId = 'minimize' | 'maximize' | 'close'+type TitlebarLayout = { left: ButtonId[]; right: ButtonId[] }++const DEFAULT_LAYOUT: TitlebarLayout = {+ left: [],+ right: ['minimize', 'maximize', 'close'],+}+export const WindowControls = () => {const appWindow = getCurrentWebviewWindow()+ const [layout, setLayout] = useState<TitlebarLayout>(DEFAULT_LAYOUT)- const handleMinimize = async () => {- await appWindow.minimize()- }+ useEffect(() => {+ invoke<TitlebarLayout>('get_titlebar_layout')+ .then((l) => setLayout(l))+ .catch(() => setLayout(DEFAULT_LAYOUT))+ }, [])- const handleMaximize = async () => {- await appWindow.toggleMaximize()+ const actions: Record<ButtonId, () => Promise<void>> = {+ minimize: () => appWindow.minimize(),+ maximize: () => appWindow.toggleMaximize(),+ close: () => appWindow.close(),}-- const handleClose = async () => {- await appWindow.close()+ const icons: Record<ButtonId, React.ReactNode> = {+ minimize: <Minus className="size-4" />,+ maximize: <Square className="size-3" />,+ close: <X className="size-4" />,+ }+ const labels: Record<ButtonId, string> = {+ minimize: 'Minimize',+ maximize: 'Maximize',+ close: 'Close',}+ const renderGroup = (ids: ButtonId[]) =>+ ids.map((id) => (+ <Button+ key={id}+ onClick={actions[id]}+ aria-label={labels[id]}+ variant="ghost"+ size="icon-sm"+ >+ {icons[id]}+ </Button>+ ))+return (- <div className="absolute top-0 z-50 right-4 h-15">- <div className="flex items-center h-full">- <Button- onClick={handleMinimize}- aria-label="Minimize"- variant="ghost"- size="icon-sm"- >- <Minus className="size-4" />- </Button>- <Button- onClick={handleMaximize}- variant="ghost"- size="icon-sm"- aria-label="Maximize"- >- <Square className="size-3" />- </Button>- <Button- onClick={handleClose}- variant="ghost"- size="icon-sm"- aria-label="Close"- >- <X className="size-4" />- </Button>- </div>- </div>+ <>+ {layout.left.length > 0 && (+ <div className="absolute top-0 z-50 left-4 h-15">+ <div className="flex items-center h-full">+ {renderGroup(layout.left)}+ </div>+ </div>+ )}+ {layout.right.length > 0 && (+ <div className="absolute top-0 z-50 right-4 h-15">+ <div className="flex items-center h-full">+ {renderGroup(layout.right)}+ </div>+ </div>+ )}+ </>)}diff --git a/web-app/src/components/WindowResizeGrips.tsx b/web-app/src/components/WindowResizeGrips.tsxnew file mode 100644index 000000000..2ca6a2374--- /dev/null+++ b/web-app/src/components/WindowResizeGrips.tsx@@ -0,0 +1,60 @@+import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'+import type { ResizeDirection } from '@tauri-apps/api/window'++/**+ * Invisible edge/corner grips that restore window resizing for a borderless+ * window. A decorations:false window on Wayland has no compositor-drawn resize+ * handles, so each grip forwards to the compositor's interactive resize.+ */+const GRIP = 'fixed z-[60]'+const EDGE = 4+const CORNER = 10++const startResize = (direction: ResizeDirection) => () => {+ void getCurrentWebviewWindow().startResizeDragging(direction)+}++export const WindowResizeGrips = () => (+ <>+ <div+ className={GRIP}+ style={{ top: 0, left: CORNER, right: CORNER, height: EDGE, cursor: 'ns-resize' }}+ onMouseDown={startResize('North')}+ />+ <div+ className={GRIP}+ style={{ bottom: 0, left: CORNER, right: CORNER, height: EDGE, cursor: 'ns-resize' }}+ onMouseDown={startResize('South')}+ />+ <div+ className={GRIP}+ style={{ top: CORNER, bottom: CORNER, left: 0, width: EDGE, cursor: 'ew-resize' }}+ onMouseDown={startResize('West')}+ />+ <div+ className={GRIP}+ style={{ top: CORNER, bottom: CORNER, right: 0, width: EDGE, cursor: 'ew-resize' }}+ onMouseDown={startResize('East')}+ />+ <div+ className={GRIP}+ style={{ top: 0, left: 0, width: CORNER, height: CORNER, cursor: 'nwse-resize' }}+ onMouseDown={startResize('NorthWest')}+ />+ <div+ className={GRIP}+ style={{ top: 0, right: 0, width: CORNER, height: CORNER, cursor: 'nesw-resize' }}+ onMouseDown={startResize('NorthEast')}+ />+ <div+ className={GRIP}+ style={{ bottom: 0, left: 0, width: CORNER, height: CORNER, cursor: 'nesw-resize' }}+ onMouseDown={startResize('SouthWest')}+ />+ <div+ className={GRIP}+ style={{ bottom: 0, right: 0, width: CORNER, height: CORNER, cursor: 'nwse-resize' }}+ onMouseDown={startResize('SouthEast')}+ />+ </>+)diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsxindex c9bae9fa0..85fbc5097 100644--- a/web-app/src/routes/__root.tsx+++ b/web-app/src/routes/__root.tsx@@ -27,6 +27,7 @@ import { ServiceHubProvider } from '@/providers/ServiceHubProvider'import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'import { LeftSidebar } from '@/components/left-sidebar'import { WindowControls } from '@/components/WindowControls'+import { WindowResizeGrips } from '@/components/WindowResizeGrips'import ErrorDialog from '@/containers/dialogs/ErrorDialog'import LlamacppBusyOnExitDialog from '@/containers/dialogs/LlamacppBusyOnExitDialog'import LlamacppOomListener from '@/containers/dialogs/LlamacppOomListener'@@ -58,8 +59,9 @@ const AppLayout = () => {<AnalyticProvider /><KeyboardShortcutsProvider />{/* Fake absolute panel top to enable window drag */}- {IS_WINDOWS && <WindowControls />}- {IS_TAURI && !IS_LINUX && (+ {(IS_WINDOWS || IS_LINUX) && <WindowControls />}+ {IS_LINUX && <WindowResizeGrips />}+ {IS_TAURI && (<divclassName="fixed w-full h-12 z-20 top-0 cursor-grab active:cursor-grabbing"title="Drag window"