diff --git a/crates/waybetter-host/src/app.rs b/crates/waybetter-host/src/app.rs index f6a380a..8e1b1e5 100644 --- a/crates/waybetter-host/src/app.rs +++ b/crates/waybetter-host/src/app.rs @@ -1160,6 +1160,32 @@ pub fn reset_lost_geometry(window: &tauri::Window, size: (f64, f64), min: (f64, } } +/// A restored window lies inside the work area of the monitor it opens on (the primary one when +/// that monitor is gone): a state saved on a larger or rearranged screen would otherwise leave +/// its titlebar out of reach ([`crate::window_fit::fit`]). A maximized or full-screen window is +/// the OS's to place. +pub fn fit_to_monitor(window: &tauri::Window) { + use crate::window_fit::{fit, Rect}; + if window.is_maximized().unwrap_or(false) || window.is_fullscreen().unwrap_or(false) { + return; + } + let (Ok(position), Ok(size), Ok(monitors)) = (window.outer_position(), window.outer_size(), window.available_monitors()) else { return }; + let area = |monitor: &tauri::Monitor| { + let work = monitor.work_area(); + Rect::new(work.position.x, work.position.y, work.size.width, work.size.height) + }; + let areas: Vec = monitors.iter().map(area).collect(); + let primary = window.primary_monitor().ok().flatten().map(|monitor| area(&monitor)); + let Some(fitted) = fit(Rect::new(position.x, position.y, size.width, size.height), &areas, primary) else { return }; + if (fitted.width, fitted.height) != (size.width, size.height) { + // The outer frame must fit; the inner size is what can be set, so the frame's border comes off it. + let inner = window.inner_size().unwrap_or(size); + let (extra_w, extra_h) = (size.width.saturating_sub(inner.width), size.height.saturating_sub(inner.height)); + let _ = window.set_size(tauri::PhysicalSize::new(fitted.width.saturating_sub(extra_w), fitted.height.saturating_sub(extra_h))); + } + let _ = window.set_position(tauri::PhysicalPosition::new(fitted.x, fitted.y)); +} + /// The host's commands ([`commands::SHELL`], [`commands::TAB`], [`commands::SITE`]). fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { tauri::generate_handler![ @@ -1459,6 +1485,7 @@ fn open_window(app: &mut tauri::App, config: &AppConfig) -> Result<(), Box< let _ = window.restore_state(window_state_flags()); } reset_lost_geometry(&window, config.window_size, config.min_window_size); + fit_to_monitor(&window); // `taskkill` (and anything else closing "the first visible window") must close the app // even when a minimized window sits below the runtime's helper windows. host::route_helper_closes(&window); diff --git a/crates/waybetter-host/src/lib.rs b/crates/waybetter-host/src/lib.rs index de90492..b61a5c0 100644 --- a/crates/waybetter-host/src/lib.rs +++ b/crates/waybetter-host/src/lib.rs @@ -76,6 +76,7 @@ pub mod tabs; pub mod testkit; pub mod theme; pub mod update; +pub mod window_fit; pub mod workspaces; pub mod zoom; diff --git a/crates/waybetter-host/src/window_fit.rs b/crates/waybetter-host/src/window_fit.rs new file mode 100644 index 0000000..b144f30 --- /dev/null +++ b/crates/waybetter-host/src/window_fit.rs @@ -0,0 +1,108 @@ +//! A restored window fits the monitor it opens on. A saved state can come from a larger or a +//! differently arranged monitor (2720x1800 saved on a big screen, restored on a smaller second +//! one): the window then hangs past the work area, its titlebar out of reach, and it cannot be +//! moved. [`fit`] picks the monitor the window is mostly on (the primary one when it is on none), +//! shrinks the window to that monitor's work area when it is larger, and moves it inside. +//! Physical pixels throughout, as the OS reports monitors. + +/// A rectangle in physical pixels (a window's outer frame, a monitor's work area). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rect { + pub x: i32, + pub y: i32, + pub width: u32, + pub height: u32, +} + +impl Rect { + pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self { + Self { x, y, width, height } + } + + fn right(&self) -> i64 { + i64::from(self.x) + i64::from(self.width) + } + + fn bottom(&self) -> i64 { + i64::from(self.y) + i64::from(self.height) + } + + /// The area two rectangles share (0 when they do not meet). + fn overlap(&self, other: &Rect) -> i64 { + let width = self.right().min(other.right()) - i64::from(self.x.max(other.x)); + let height = self.bottom().min(other.bottom()) - i64::from(self.y.max(other.y)); + if width <= 0 || height <= 0 { 0 } else { width * height } + } +} + +/// Where `window` should be so it lies inside a work area: `None` when it already does. +/// +/// The work area is the one of the monitor the window overlaps most; when it overlaps none (that +/// monitor is gone), `primary`, else the first one. The size shrinks to the work area (never +/// grows); the position moves just enough to bring the whole frame inside. +pub fn fit(window: Rect, work_areas: &[Rect], primary: Option) -> Option { + let best = work_areas + .iter() + .map(|area| (window.overlap(area), area)) + .filter(|(shared, _)| *shared > 0) + .max_by_key(|(shared, _)| *shared) + .map(|(_, area)| *area); + let area = best.or(primary).or_else(|| work_areas.first().copied())?; + if area.width == 0 || area.height == 0 { + return None; + } + let width = window.width.min(area.width); + let height = window.height.min(area.height); + let clamp = |at: i32, len: u32, start: i32, room: u32| -> i32 { + let last = i64::from(start) + i64::from(room) - i64::from(len); + i64::from(at).clamp(i64::from(start), last.max(i64::from(start))) as i32 + }; + let fitted = Rect::new(clamp(window.x, width, area.x, area.width), clamp(window.y, height, area.y, area.height), width, height); + (fitted != window).then_some(fitted) +} + +#[cfg(test)] +mod tests { + use super::*; + + // A 2560x1600 main monitor (taskbar 48 px) and a smaller 1920x1080 one to its right. + const MAIN: Rect = Rect::new(0, 0, 2560, 1552); + const SECOND: Rect = Rect::new(2560, 0, 1920, 1032); + + #[test] + fn a_window_saved_on_a_bigger_screen_shrinks_into_the_smaller_monitor_it_opens_on() { + // The reported case: 2720x1800 at x=3347, mostly on the second monitor; its titlebar was off-screen. + let fitted = fit(Rect::new(3347, 40, 2720, 1800), &[MAIN, SECOND], Some(MAIN)).unwrap(); + assert_eq!(fitted, SECOND); + } + + #[test] + fn a_window_hanging_past_an_edge_moves_inside_and_keeps_its_size() { + let fitted = fit(Rect::new(3800, -30, 1200, 800), &[MAIN, SECOND], Some(MAIN)).unwrap(); + assert_eq!(fitted, Rect::new(2560 + 1920 - 1200, 0, 1200, 800)); + // Past the start edges too. + assert_eq!(fit(Rect::new(-500, 900, 1200, 800), &[MAIN, SECOND], Some(MAIN)), Some(Rect::new(0, 1552 - 800, 1200, 800))); + } + + #[test] + fn a_window_whose_monitor_is_gone_opens_on_the_primary_one() { + let fitted = fit(Rect::new(6000, 200, 1400, 900), &[MAIN], Some(MAIN)).unwrap(); + assert_eq!(fitted, Rect::new(2560 - 1400, 200, 1400, 900)); + // No primary reported: the first monitor. + assert_eq!(fit(Rect::new(6000, 200, 1400, 900), &[SECOND], None), Some(Rect::new(2560 + 1920 - 1400, 1032 - 900, 1400, 900))); + } + + #[test] + fn a_window_inside_its_work_area_is_left_alone() { + assert_eq!(fit(Rect::new(100, 80, 1600, 1000), &[MAIN, SECOND], Some(MAIN)), None); + assert_eq!(fit(SECOND, &[MAIN, SECOND], Some(MAIN)), None); + assert_eq!(fit(Rect::new(100, 80, 1600, 1000), &[], None), None); + } + + #[test] + fn monitors_left_of_and_above_the_main_one_work_too() { + let left = Rect::new(-1920, -200, 1920, 1040); + let fitted = fit(Rect::new(-2100, -260, 2000, 1200), &[MAIN, left], Some(MAIN)).unwrap(); + assert_eq!(fitted, left); + } +} diff --git a/packages/runtime/src/themeRuntime.ts b/packages/runtime/src/themeRuntime.ts index c938b5a..e0326d2 100644 --- a/packages/runtime/src/themeRuntime.ts +++ b/packages/runtime/src/themeRuntime.ts @@ -5,7 +5,7 @@ // the site adapter (`ThemeRuntimeSite`): X re-declares its own stylesheet rules with the theme's // colors (`buildThemeCss`) and adds type/shape/layout rules over its selectors. -import { domRoots } from './domHub.ts'; +import { domRoots, watchDom, type DomWatchHandle } from './domHub.ts'; import { FONT_ROLE_NAMES, themeKey, themeVarsCss, type ResolvedFonts, type ResolvedTheme } from './themeApi.ts'; import type { ThemeCatalog, ThemeChoice } from './themeChoice.ts'; import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts'; @@ -160,7 +160,7 @@ export type ThemeRuntimeSite = { /** The site's color mode as the page paints it now (read before the theme's own override: e.g. the body's inline style). */ readMode(win: Window): Mode; /** The theme's CSS for the site's current `rules` (the engine's own sheet excluded) in `mode`; `vars` are `siteVars` as the site sets them. */ - css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record): string; + css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record, flags: readonly string[]): string; /** The active theme resolved for plugins and the UI kit (the site's own palette when the theme keeps its colors). */ resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme; /** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */ @@ -178,8 +178,28 @@ export type ThemeRuntimeSite = { styleId?: string; /** Name in console errors. */ name?: string; + /** + * Page states the theme's CSS keys on, as `html[data-wb-]` attributes kept by the engine: + * set while `selector` matches in the page or one of its open shadow roots (domHub `shadowHosts`). + * A theme rule gated by `html[data-wb-chat]` costs nothing when the page changes; the same gate + * as `html:has(...)` makes the browser re-match the whole page on every insertion (seen on x.com: + * 10-100 ms per inserted node under a theme instead of 0.1 ms). + */ + flags?: Readonly>; }; +/** The attribute a page flag sets on ``. */ +export const flagAttribute = (name: string) => `data-wb-${name}`; + +/** Which of `flags` hold in `roots` now (pure, for tests). */ +export function pageFlags(roots: ReadonlyArray<{ querySelector(selector: string): unknown }>, flags: Readonly>): string[] { + const on: string[] = []; + for (const [name, selector] of Object.entries(flags)) { + try { if (roots.some(root => !!root.querySelector(selector))) on.push(name); } catch { /* A bad selector is never on. */ } + } + return on; +} + export type ThemeHandle = { apply(choice: unknown): void; current(): ThemeChoice; @@ -266,6 +286,36 @@ export function installThemeRuntime(win: Window, site: Them let staticKey = ''; let staticText = ''; let siteVars: Record = {}; + // Page flags (`site.flags`): checked once per hub frame after the page changed, on every page (heavy ones too). + const flagNames = Object.keys(site.flags ?? {}); + let flagWatch: DomWatchHandle | null = null; + // The flags that hold now; the theme's CSS is rebuilt when they change (a rule that only applies to a + // signed-out page can then be left out of a signed-in one instead of being gated by `:has()`). + let flagState: string[] = []; + const syncFlags = () => { + const root = doc.documentElement; + if (!root || !flagNames.length) return; + let on: string[] = []; + try { on = pageFlags(domRoots(win), site.flags!); } catch { on = []; } + for (const name of flagNames) { + const attr = flagAttribute(name); + const want = on.includes(name); + if (root.hasAttribute(attr) !== want) { if (want) root.setAttribute(attr, ''); else root.removeAttribute(attr); } + } + const changed = on.join(' ') !== flagState.join(' '); + flagState = on; + return changed; + }; + const flagsOn = (on: boolean) => { + if (!flagNames.length) return; + if (on) { + syncFlags(); + if (!flagWatch) { try { flagWatch = watchDom(win as never, () => { if (syncFlags()) { try { render(); } catch { /* Never break the site. */ } } }, { offOnHeavy: false }); } catch { flagWatch = null; } } + } else { + flagWatch?.dispose(); flagWatch = null; + for (const name of flagNames) doc.documentElement?.removeAttribute(flagAttribute(name)); + } + }; // Open shadow roots the site renders a part of itself in (domHub `shadowHosts`; X's chat embed since // 2026-10-01): the document's sheets do not reach inside, so each root adopts the theme built from // its own rules plus the static sheet, kept last among its sheets, rebuilt when its rules change and @@ -283,7 +333,7 @@ export function installThemeRuntime(win: Window, site: Them try { item = { sheet: new Sheet(), key: '' }; } catch { continue; } rootSheets.set(root, item); } - const key = `${snapshotKey}|${rootRuleCount(root, item.sheet)}|${staticText.length}`; + const key = `${snapshotKey}|${flagState.join(' ')}|${rootRuleCount(root, item.sheet)}|${staticText.length}`; if (force || item.key !== key) { item.key = key; // The site's primitives as the root sees them (its own sheets may declare them; the document may not), read with our sheet off. @@ -295,7 +345,7 @@ export function installThemeRuntime(win: Window, site: Them item.sheet.disabled = false; } let css = ''; - try { css = site.css(collectRootRules(root, item.sheet, (win as Window & typeof globalThis).CSS), choice, mode, vars); } catch (error) { console.error(`[${name}] theme (shadow root) failed`, error); } + try { css = site.css(collectRootRules(root, item.sheet, (win as Window & typeof globalThis).CSS), choice, mode, vars, flagState); } catch (error) { console.error(`[${name}] theme (shadow root) failed`, error); } try { item.sheet.replaceSync(staticText ? `${css}\n${staticText}` : css); } catch { /* Keeps the last good rules. */ } } // Last, so equal-specificity `!important` rules win over the site's; the site may re-set its list. @@ -312,8 +362,9 @@ export function installThemeRuntime(win: Window, site: Them let style = doc.getElementById(styleId) as HTMLStyleElement | null; let fixed = doc.getElementById(staticId) as HTMLStyleElement | null; if (doc.body) { watchMode(); syncResolved(); } - if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); syncRoots(false, '', false); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; } + if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); syncRoots(false, '', false); flagsOn(false); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; } if (!doc.body) return; + flagsOn(true); const snapshotKey = `${JSON.stringify(choice)}|${mode}`; if (early && snapshot?.key !== snapshotKey) dropEarly(); // The static sheet follows the theme and the mode only (and `refresh()`), never the site's rules. @@ -327,7 +378,7 @@ export function installThemeRuntime(win: Window, site: Them if (fixed.textContent !== text) fixed.textContent = text; } else { fixed?.remove(); fixed = null; } } - const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`; + const key = `${JSON.stringify(choice)}|${mode}|${flagState.join(' ')}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`; if (!force && key === lastKey) { placeStatic(fixed, style); syncRoots(true, snapshotKey, false); return; } lastKey = key; if (!style) { style = doc.createElement('style'); style.id = styleId; } @@ -340,7 +391,7 @@ export function installThemeRuntime(win: Window, site: Them } if (style.sheet) style.sheet.disabled = false; siteVars = vars; - const css = site.css(collectRules(doc, [style, fixed]), choice, mode, vars); + const css = site.css(collectRules(doc, [style, fixed]), choice, mode, vars, flagState); if (style.textContent !== css) style.textContent = css; // Last in so equal-specificity `!important` rules win over the site's; the static sheet after it. const last = fixed?.isConnected && doc.head?.lastElementChild === fixed ? fixed.previousElementSibling : doc.head?.lastElementChild; diff --git a/packages/runtime/tests/themeEngine.test.ts b/packages/runtime/tests/themeEngine.test.ts index e145ce3..a6808a1 100644 --- a/packages/runtime/tests/themeEngine.test.ts +++ b/packages/runtime/tests/themeEngine.test.ts @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { FONT_ROLE_NAMES, MONO_FONT, contrastRatio } from '../src/themeApi.ts'; import { choiceForId, createThemeCatalog, serializeChoice, MAX_USER_THEMES } from '../src/themeChoice.ts'; -import { SNAPSHOT_LOCAL_MAX, collectRootRules, collectRules, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts'; +import { SNAPSHOT_LOCAL_MAX, collectRootRules, collectRules, flagAttribute, pageFlags, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts'; import { BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, FONT_CHOICES, ROLE_LIMITS, applyOverrides, backgroundLayers, ensureContrast, fontChoiceOf, fontStack, isNeutral, pageBackgroundCss, parseThemeJson, resolveFontRoles, sanitizeSpec, withFamily, withRoles, type ThemeSpec, @@ -262,3 +262,12 @@ test('collectRootRules reads a shadow root\'s adopted sheets and