Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: open the title bar in its last color and fit tall windows on screen
Tw93b6bb966e1f09
diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rsindex 7a4d62cf..d4b168d2 100644--- a/src-tauri/src/app/invoke.rs+++ b/src-tauri/src/app/invoke.rs@@ -485,7 +485,27 @@ pub fn set_title_bar_color(.as_ref().window().set_background_color(Some(tauri::window::Color(red, green, blue, 255)))- .map_err(|e| format!("Failed to set the title bar color: {}", e))+ .map_err(|e| format!("Failed to set the title bar color: {}", e))?;+ // Remember the main window's color for the next launch; failing to+ // save it costs only that first frame, so it never fails the call.+ if window.label() == "pake" {+ let saved = window+ .app_handle()+ .path()+ .app_data_dir()+ .map_err(|e| e.to_string())+ .and_then(|directory| {+ crate::util::write_title_bar_color(+ &directory.join(crate::app::window::TITLE_BAR_COLOR_FILE),+ (red, green, blue),+ )+ .map_err(|e| e.to_string())+ });+ if let Err(error) = saved {+ eprintln!("[Pake] Could not remember the title bar color: {error}");+ }+ }+ Ok(())}#[cfg(not(target_os = "macos"))]{diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 25aca7a2..92517028 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -38,6 +38,13 @@ use tauri::Theme;#[cfg(target_os = "macos")]use tauri::TitleBarStyle;+/// Logical points kept free above a fitted window for its title bar.+const TITLE_BAR_ALLOWANCE: f64 = 40.0;++/// Where the main window's last title bar color is remembered on macOS.+#[cfg(target_os = "macos")]+pub const TITLE_BAR_COLOR_FILE: &str = "title-bar-color.txt";+#[cfg(target_os = "macos")]fn prepare_macos_new_window_configuration(features: &NewWindowFeatures) -> tauri::Result<()> {let mtm = MainThreadMarker::new().ok_or_else(|| {@@ -536,22 +543,37 @@ fn build_window(.resizable(window_config.resizable).maximized(window_config.maximize);+ // A size preset can be taller than the screen (the tablet one is 820x1180),+ // so the first window fits the primary monitor's work area; a size the+ // window-state plugin restores later is left as the user made it.+ let monitor = app.primary_monitor().ok().flatten();+ let scale_factor = monitor.as_ref().map(|m| m.scale_factor()).unwrap_or(1.0);+ let work_area = monitor.as_ref().map(|m| {+ let size = m.work_area().size;+ (f64::from(size.width), f64::from(size.height))+ });+#[cfg(target_os = "windows")]{- let scale_factor = app- .primary_monitor()- .ok()- .flatten()- .map(|m| m.scale_factor())- .unwrap_or(1.0);- let logical_width = window_config.width / scale_factor;- let logical_height = window_config.height / scale_factor;- window_builder = window_builder.inner_size(logical_width, logical_height);+ // The config size is read as physical pixels here, as before.+ let (width, height) = crate::util::fit_to_work_area(+ window_config.width,+ window_config.height,+ work_area,+ TITLE_BAR_ALLOWANCE * scale_factor,+ );+ window_builder = window_builder.inner_size(width / scale_factor, height / scale_factor);}#[cfg(not(target_os = "windows"))]{- window_builder = window_builder.inner_size(window_config.width, window_config.height);+ let (width, height) = crate::util::fit_to_work_area(+ window_config.width,+ window_config.height,+ work_area.map(|(width, height)| (width / scale_factor, height / scale_factor)),+ TITLE_BAR_ALLOWANCE,+ );+ window_builder = window_builder.inner_size(width, height);}window_builder = window_builder@@ -719,6 +741,18 @@ fn build_window(window_builder = window_builder.title_bar_style(title_bar_style);if window_config.title_bar_follows_page() {window_builder = window_builder.hidden_title(true);+ // Open in the color title_bar.js last painted, so the bar does not+ // flash the default white before the page reports its own.+ if label == "pake" {+ if let Some((red, green, blue)) =+ app.path().app_data_dir().ok().and_then(|directory| {+ crate::util::read_title_bar_color(&directory.join(TITLE_BAR_COLOR_FILE))+ })+ {+ window_builder = window_builder+ .background_color(tauri::window::Color(red, green, blue, 255));+ }+ }}window_builder = window_builder.theme(theme);diff --git a/src-tauri/src/inject/title_bar.js b/src-tauri/src/inject/title_bar.jsindex 67ddf468..398fd33d 100644--- a/src-tauri/src/inject/title_bar.js+++ b/src-tauri/src/inject/title_bar.js@@ -55,9 +55,23 @@return samples[majority === -1 ? 1 : majority];}+ // Before the page paints its top edge (or when it is see-through there),+ // the page's own theme-color still says what the bar should be. A tag with+ // a media query counts only while that query matches.+ function themeColor() {+ const tags = document.querySelectorAll?.('meta[name="theme-color"]') || [];+ for (const tag of tags) {+ const media = tag.getAttribute("media");+ if (media && !window.matchMedia?.(media)?.matches) continue;+ const color = toRgb(tag.getAttribute("content"));+ if (color) return color;+ }+ return null;+ }+function update() {pending = 0;- const color = pageTopColor();+ const color = pageTopColor() || themeColor();if (!color) return;const key = `${color.red},${color.green},${color.blue}`;if (key === lastSent) return;diff --git a/src-tauri/src/util.rs b/src-tauri/src/util.rsindex c69e355b..1514b4f0 100644--- a/src-tauri/src/util.rs+++ b/src-tauri/src/util.rs@@ -206,6 +206,55 @@ pub fn write_last_url(path: &Path, url: &tauri::Url) -> std::io::Result<()> {Ok(())}+/// The title bar color last painted on macOS, stored as `r,g,b`, so the next+/// launch opens in it instead of flashing the default bar first.+#[cfg(any(target_os = "macos", test))]+pub fn parse_title_bar_color(value: &str) -> Option<(u8, u8, u8)> {+ let mut parts = value+ .trim()+ .split(',')+ .map(|part| part.trim().parse::<u8>());+ let color = (+ parts.next()?.ok()?,+ parts.next()?.ok()?,+ parts.next()?.ok()?,+ );+ parts.next().is_none().then_some(color)+}++#[cfg(any(target_os = "macos", test))]+pub fn read_title_bar_color(path: &Path) -> Option<(u8, u8, u8)> {+ std::fs::read_to_string(path)+ .ok()+ .and_then(|value| parse_title_bar_color(&value))+}++#[cfg(any(target_os = "macos", test))]+pub fn write_title_bar_color(path: &Path, (red, green, blue): (u8, u8, u8)) -> std::io::Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ std::fs::write(path, format!("{red},{green},{blue}"))+}++/// Fits a configured window into the monitor's work area, leaving room for+/// the title bar, so a tall preset never opens past the bottom of the screen.+/// All values share one unit: logical points on macOS and Linux, physical+/// pixels on Windows, where the config size is read as physical.+pub fn fit_to_work_area(+ width: f64,+ height: f64,+ area: Option<(f64, f64)>,+ chrome: f64,+) -> (f64, f64) {+ match area {+ Some((area_width, area_height)) if area_width > 0.0 && area_height > chrome => {+ (width.min(area_width), height.min(area_height - chrome))+ }+ _ => (width, height),+ }+}+/// Both native and IPC downloads use the trusted, packaged configuration.pub fn get_download_dir(app: &AppHandle) -> Result<PathBuf, String> {let state = app@@ -520,6 +569,41 @@ mod tests {dir}+ #[test]+ fn title_bar_color_round_trips_and_rejects_anything_else() {+ let path = temp_path("state/title-bar-color.txt");+ assert_eq!(read_title_bar_color(&path), None);+ write_title_bar_color(&path, (17, 24, 39)).unwrap();+ assert_eq!(read_title_bar_color(&path), Some((17, 24, 39)));+ assert_eq!(parse_title_bar_color(" 255, 0 ,8\n"), Some((255, 0, 8)));+ for value in ["", "1,2", "1,2,3,4", "256,0,0", "-1,0,0", "a,b,c", "1,,3"] {+ assert_eq!(parse_title_bar_color(value), None, "{value:?}");+ }+ fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).unwrap();+ }++ #[test]+ fn a_window_taller_than_the_work_area_fits_inside_it() {+ // The tablet preset on a 1440x900 MacBook Air with the Dock shown.+ assert_eq!(+ fit_to_work_area(820.0, 1180.0, Some((1440.0, 875.0)), 32.0),+ (820.0, 843.0)+ );+ assert_eq!(+ fit_to_work_area(1200.0, 780.0, Some((1440.0, 875.0)), 32.0),+ (1200.0, 780.0)+ );+ assert_eq!(+ fit_to_work_area(3000.0, 780.0, Some((1440.0, 875.0)), 32.0),+ (1440.0, 780.0)+ );+ assert_eq!(fit_to_work_area(820.0, 1180.0, None, 32.0), (820.0, 1180.0));+ assert_eq!(+ fit_to_work_area(820.0, 1180.0, Some((0.0, 0.0)), 32.0),+ (820.0, 1180.0)+ );+ }+#[test]fn last_url_round_trip_preserves_full_address() {let path = temp_path("state/last-url.txt");diff --git a/tests/unit/title-bar-color.test.js b/tests/unit/title-bar-color.test.jsindex 7d46b8e1..61994fd1 100644--- a/tests/unit/title-bar-color.test.js+++ b/tests/unit/title-bar-color.test.js@@ -21,7 +21,7 @@ function element(background, parentElement = null) {return { background, parentElement };}-function loadTitleBar({ columns, width = 1000 }) {+function loadTitleBar({ columns, width = 1000, metas = [], matching = [] }) {const calls = [];let current = columns;let timer = null;@@ -58,6 +58,12 @@ function loadTitleBar({ columns, width = 1000 }) {}),};},+ querySelectorAll: (selector) =>+ selector === 'meta[name="theme-color"]'+ ? metas.map((attributes) => ({+ getAttribute: (name) => attributes[name] ?? null,+ }))+ : [],elementFromPoint(x) {const column = Math.min(2, Math.floor((x / width) * 3));return current[column];@@ -66,6 +72,7 @@ function loadTitleBar({ columns, width = 1000 }) {window: {innerWidth: width,addEventListener() {},+ matchMedia: (query) => ({ matches: matching.includes(query) }),getComputedStyle: (node) => ({ backgroundColor: node.background }),__TAURI__: {core: {@@ -133,6 +140,28 @@ describe("macOS transparent title bar color", () => {expect(calls.map((call) => call.args.red)).toEqual([255, 30]);});+ it("falls back to the theme-color whose media query matches", () => {+ const clear = element("0,0,0,0");+ const { calls } = loadTitleBar({+ columns: [clear, clear, clear],+ metas: [+ { content: "250,250,250,255", media: "(prefers-color-scheme: light)" },+ { content: "18,18,20,255", media: "(prefers-color-scheme: dark)" },+ ],+ matching: ["(prefers-color-scheme: dark)"],+ });+ expect(calls[0].args).toEqual({ red: 18, green: 18, blue: 20 });+ });++ it("prefers the painted top edge over the theme-color", () => {+ const page = element("40,40,40,255");+ const { calls } = loadTitleBar({+ columns: [page, page, page],+ metas: [{ content: "250,250,250,255" }],+ });+ expect(calls[0].args).toEqual({ red: 40, green: 40, blue: 40 });+ });+it("leaves the native color alone when nothing on top is painted", () => {const clear = element("0,0,0,0");const { calls } = loadTitleBar({ columns: [clear, clear, null] });