diff --git a/Cargo.lock b/Cargo.lock index f4f81afa..8928003c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -779,6 +779,17 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-window" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +dependencies = [ + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "wayland-client", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -3780,10 +3791,13 @@ dependencies = [ "egui", "image", "log", + "ron", "serde_json", "texturecraft-engine", "texturecraft-ui-egui", + "winit", "winresource", + "winsafe", ] [[package]] @@ -3941,6 +3955,7 @@ version = "0.1.0" dependencies = [ "base64 0.22.1", "craft-ui", + "craft-window", "eframe", "egui", "egui-phosphor", @@ -5090,6 +5105,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "winsafe" +version = "0.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" + [[package]] name = "winx" version = "0.36.4" diff --git a/Cargo.toml b/Cargo.toml index fe21198a..755e677e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,8 @@ getrandom = "0.3" # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] } +# Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/ROADMAP.md b/ROADMAP.md index 0019498c..b739669d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -20,7 +20,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | | Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | -| UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution), saved UI layouts, **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **9 UI languages** with CJK fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | +| UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **9 UI languages** with CJK fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 75% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | | **Total** | **100** | **≈ 93%** | | | diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 66964286..059c559d 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -18,6 +18,14 @@ egui = { workspace = true } image = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# Reads the saved System title bar setting before the window opens (eframe's settings format). +ron = "0.12" + +# The window's big (taskbar) icon, and the guard that keeps the app-drawn title bar's window +# borderless (src/window_frame.rs; winsafe is MIT, User32 only). +[target.'cfg(windows)'.dependencies] +winit = { version = "0.30", default-features = false } +winsafe = { version = "0.0.29", default-features = false, features = ["user"] } [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 7e6bedb4..e1cbb6c2 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -6,9 +6,14 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod control_server; +mod window_frame; use texturecraft_engine::Session; -use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::titlebar::TitleBar; +use texturecraft_ui_egui::{TextureCraftApp, UiState}; + +/// The app name eframe keeps the settings under (`eframe::storage_dir`). +const APP_NAME: &str = "TextureCraft"; const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png"); @@ -81,6 +86,63 @@ fn icon() -> Option { Some(egui::IconData { rgba: img.into_raw(), width: w, height: h }) } +/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the +/// small one, so the taskbar would show a generic icon. Set the big one too. +#[cfg(windows)] +fn set_taskbar_icon(w: &winit::window::Window) { + use winit::platform::windows::WindowExtWindows as _; + // An icon that can't be made leaves the generic one: nothing else depends on it. + if let Some(i) = icon().and_then(|i| winit::window::Icon::from_rgba(i.rgba, i.width, i.height).ok()) { + w.set_taskbar_icon(Some(i)); + } +} + +/// Settings › Interface › System title bar, read from the saved settings before the window opens +/// (eframe hands the app its storage only afterwards). Missing or unreadable: off. +fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool { + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron"))); + let saved = file.and_then(|f| std::fs::read_to_string(f).ok()); + let kv = saved.and_then(|s| ron::from_str::>(&s).ok()); + kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) +} + +/// The app with the window chrome that needs the native window: the Windows borderless guard, and +/// on macOS the traffic lights and AppKit's `movable` flag. +struct Shell { + app: TextureCraftApp, + window_frame: Option, + #[cfg(target_os = "macos")] + movable: Option, +} + +impl eframe::App for Shell { + fn auto_save_interval(&self) -> std::time::Duration { + self.app.auto_save_interval() + } + + fn save(&mut self, storage: &mut dyn eframe::Storage) { + self.app.save(storage); + } + + fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw: &mut egui::RawInput) { + // winit gives the window its caption back when it changes the window's flags (maximize, + // restore, …): take it off again before the frame is laid out. + if let Some(guard) = self.window_frame.as_mut() { + guard(); + } + } + + fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { + self.app.logic(ctx, frame); + } + + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + self.app.ui(ui, frame); + #[cfg(target_os = "macos")] + texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable); + } +} + fn main() { let args = match parse_args() { Ok(Some(a)) => a, @@ -96,25 +158,38 @@ fn main() { prev(info); })); let session = initial_session(&args); - let mut viewport = egui::ViewportBuilder::default().with_title("TextureCraft").with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); - if let Some(i) = icon() { - viewport = viewport.with_icon(i); - } // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor // overwrite the user's saved UI layout and settings: state goes to a throwaway folder. let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); + let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref())); + let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); + if let Some(i) = icon() { + viewport = viewport.with_icon(i); + } + let viewport = title_bar.viewport(viewport); let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; let control = args.control; let r = eframe::run_native( - "TextureCraft", + APP_NAME, options, Box::new(move |cc| { + #[cfg(windows)] + if let Some(w) = cc.winit_window() { + set_taskbar_icon(w); + } + let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); + app.title_bar = title_bar; if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } - Ok(Box::new(app)) + Ok(Box::new(Shell { + app, + window_frame, + #[cfg(target_os = "macos")] + movable: None, + })) }), ); if let Err(e) = r { @@ -122,3 +197,25 @@ fn main() { std::process::exit(1); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_system_title_bar_setting_is_read_from_eframes_settings_file() { + let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + for on in [false, true] { + let mut ui = UiState::default(); + ui.prefs.system_title_bar = on; + // Written as eframe writes it: a pretty RON map of RON strings. + let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]); + std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(Some(&path)), on); + } + std::fs::write(&path, "not ron").unwrap(); + assert!(!saved_system_title_bar(Some(&path))); + std::fs::remove_file(&path).unwrap(); + assert!(!saved_system_title_bar(Some(&path))); + } +} diff --git a/apps/texturecraft/src/window_frame.rs b/apps/texturecraft/src/window_frame.rs new file mode 100644 index 00000000..c45b4fd0 --- /dev/null +++ b/apps/texturecraft/src/window_frame.rs @@ -0,0 +1,351 @@ +//! Keeps the app-drawn title bar's undecorated window truly borderless on Windows (ported from +//! VectorCraft's `apps/vectorcraft/src/window_frame.rs`). +//! +//! winit 0.30 gives an undecorated window the `WS_CAPTION | WS_BORDER` styles and hides the +//! non-client area by spreading the client rect over it (`WM_NCCALCSIZE`). On some systems the +//! desktop compositor still reserves that frame for the window surface: the content is drawn +//! offset by the caption and border while the pointer keeps the un-offset client coordinates, so +//! it no longer points at what is drawn under it (rust-windowing/winit#2419). [`service`] strips +//! the two styles and has Windows recalculate the frame; winit puts them back whenever it changes +//! the window flags (maximize, restore, …), so the returned guard runs every frame. +//! +//! Windows sizes a maximize by the frame its styles describe, so a window maximized while its +//! caption is gone is sized without one: its rect covers the whole monitor, taskbar included, and +//! the shell reads a caption-less window covering its monitor as a full-screen app. With the +//! taskbar on the top or a side edge, the strip between the window's edge and the client area that +//! winit pins to the work area is drawn as a classic title bar. The guard therefore also moves a +//! parked maximize's rect back inside the work area on every edge, plus its own frame, clear of the +//! taskbar wherever it is, and repaints the window. +//! +//! An auto-hidden taskbar reserves no work area, so that move leaves a maximize covering the whole +//! monitor, and the taskbar would not show when the pointer reaches its edge. On each edge with an +//! auto-hidden taskbar the guard stops the window one pixel short of the monitor instead. + +/// Run once per frame; a no-op once the window is borderless. +pub type WindowFrameFn = Box; + +pub use platform::service; + +#[cfg(windows)] +mod platform { + use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle}; + use winsafe::prelude::Handle; + use winsafe::{AtomStr, HWND, HwndPlace, POINT, SIZE, co}; + + /// A guard that keeps the window borderless each frame, or `None` when the system draws the + /// title bar (the window is decorated) or the window's handle can't be found. + pub fn service(cc: &eframe::CreationContext<'_>, app_frame: bool) -> Option { + if !app_frame { + return None; + } + let target = match cc.window_handle().ok()?.as_raw() { + RawWindowHandle::Win32(h) => h.hwnd.get(), + _ => return None, + }; + let hwnd = find_window(target)?; + reapply(&hwnd); + Some(Box::new(move || reapply(&hwnd))) + } + + /// One pass of the per-frame guard: the styles winit put back come off again, and a parked + /// maximize stays clear of the taskbar. + fn reapply(hwnd: &HWND) { + strip(hwnd); + keep_clear_of_the_taskbar(hwnd); + } + + /// The top-level window with the given raw handle: `EnumWindows` hands out real `HWND`s, so + /// this needs no `unsafe` to wrap a raw one. + fn find_window(target: isize) -> Option { + let mut found = None; + let _ = winsafe::EnumWindows(|hwnd| { + if hwnd.ptr() as isize == target { + found = Some(hwnd); + false + } else { + true + } + }); + found + } + + /// Removes `WS_CAPTION` (which includes `WS_BORDER`) and has Windows recalculate the frame; + /// the sizing border stays, so edge resizing and snapping keep working. + fn strip(hwnd: &HWND) { + let style = hwnd.style(); + let without = style & !(co::WS::CAPTION | co::WS::BORDER); + if without.raw() == style.raw() { + return; + } + hwnd.set_style(without); + let _ = hwnd.SetWindowPos( + HwndPlace::None, + POINT::new(), + SIZE::new(), + co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE, + ); + } + + /// [`super::clamped_rect`] for this frame's window: move a maximized window whose rect runs + /// under a taskbar on any edge back inside the work area plus its frame, and repaint it. A + /// maximized window that covers its whole monitor instead stops one pixel short of each edge + /// with an auto-hidden taskbar ([`super::short_of_autohide_taskbars`]). No-op otherwise. + fn keep_clear_of_the_taskbar(hwnd: &HWND) { + if !hwnd.IsZoomed() { + return; + } + let (Ok(r), Ok(mi)) = (hwnd.GetWindowRect(), hwnd.MonitorFromWindow(co::MONITOR::DEFAULTTONEAREST).GetMonitorInfo()) else { + return; + }; + let (m, w) = (mi.rcMonitor, mi.rcWork); + let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom)); + // The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its + // whole monitor, which it no longer does once trimmed. + let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work) + .or_else(|| super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten()) + else { + return; + }; + let (Some(width), Some(height)) = (right.checked_sub(left), bottom.checked_sub(top)) else { + return; + }; + // The frame moves while winit keeps the client rect on the work area: `NOCOPYBITS` and the + // invalidation have the whole window drawn again instead of the old frame's pixels being + // copied into the title bar. + let _ = hwnd.SetWindowPos( + HwndPlace::None, + POINT { x: left, y: top }, + SIZE { cx: width, cy: height }, + co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOZORDER | co::SWP::NOACTIVATE, + ); + let _ = hwnd.InvalidateRect(None, false); + } + + /// The edges of `monitor` that have a taskbar, shown or auto-hidden: the primary monitor's + /// `Shell_TrayWnd` window and the other monitors' `Shell_SecondaryTrayWnd` windows. + fn taskbar_edges(monitor: super::Rect) -> Vec { + let mut edges = Vec::new(); + for class in ["Shell_TrayWnd", "Shell_SecondaryTrayWnd"] { + let mut after: Option = None; + // A monitor has at most one taskbar; the bound ends the walk if the shell keeps + // returning windows. + for _ in 0..64 { + let Ok(Some(tray)) = HWND::NULL.FindWindowEx(after.as_ref(), AtomStr::from_str(class), None) else { + break; + }; + if let Ok(r) = tray.GetWindowRect() { + edges.extend(super::taskbar_edge((r.left, r.top, r.right, r.bottom), monitor)); + } + after = Some(tray); + } + } + edges + } +} + +#[cfg(not(windows))] +mod platform { + pub fn service(_cc: &eframe::CreationContext<'_>, _app_frame: bool) -> Option { + None + } +} + +/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about +/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being +/// dragged or snapped, and is left alone. +const FRAME: i32 = 32; + +/// A rect in desktop coordinates: `(left, top, right, bottom)`, right and bottom exclusive. +#[cfg_attr(not(windows), allow(dead_code))] +type Rect = (i32, i32, i32, i32); + +/// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize +/// border it was parked with, or `None` when it already does or `rect` is not parked at its +/// maximize place. `monitor` is the monitor's full rect and `work` its work area (the monitor less +/// the taskbar). The border is read from the edges that have no taskbar, and every edge must sit +/// that far outside either the monitor (where Windows puts a caption-less maximize) or the work +/// area (where the guard puts it), so a rect it already moved is left alone. Platform-neutral so +/// it is tested everywhere. +#[cfg_attr(not(windows), allow(dead_code))] +fn clamped_rect(rect: Rect, monitor: Rect, work: Rect) -> Option { + let (l, t, r, b) = rect; + let (ml, mt, mr, mb) = monitor; + let (wl, wt, wr, wb) = work; + if ml >= mr || mt >= mb || wl < ml || wt < mt || wr > mr || wb > mb || wl >= wr || wt >= wb { + return None; + } + // On an edge with a taskbar, the offsets from the monitor and from the work area can both + // look like a border, so only the edges without one are read. + let border = [ + (ml == wl).then(|| ml.checked_sub(l)).flatten(), + (mt == wt).then(|| mt.checked_sub(t)).flatten(), + (mr == wr).then(|| r.checked_sub(mr)).flatten(), + (mb == wb).then(|| b.checked_sub(mb)).flatten(), + ] + .into_iter() + .flatten() + .filter(|n| (0..=FRAME).contains(n)) + .min()?; + let parked = |monitor: Option, work: Option| monitor == Some(border) || work == Some(border); + if !parked(ml.checked_sub(l), wl.checked_sub(l)) + || !parked(mt.checked_sub(t), wt.checked_sub(t)) + || !parked(r.checked_sub(mr), r.checked_sub(wr)) + || !parked(b.checked_sub(mb), b.checked_sub(wb)) + { + return None; + } + let corrected = (wl.checked_sub(border)?, wt.checked_sub(border)?, wr.checked_add(border)?, wb.checked_add(border)?); + (corrected != rect).then_some(corrected) +} + +/// A monitor edge. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(windows), allow(dead_code))] +enum Edge { + Left, + Top, + Right, + Bottom, +} + +/// Whether `rect` reaches every edge of `monitor`, which the shell treats as a full-screen app. +#[cfg_attr(not(windows), allow(dead_code))] +fn covers(rect: Rect, monitor: Rect) -> bool { + rect.0 <= monitor.0 && rect.1 <= monitor.1 && rect.2 >= monitor.2 && rect.3 >= monitor.3 +} + +/// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the +/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden +/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie +/// outside the monitor. +#[cfg_attr(not(windows), allow(dead_code))] +fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option { + let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3)); + let (ml, mt, mr, mb) = (i64::from(monitor.0), i64::from(monitor.1), i64::from(monitor.2), i64::from(monitor.3)); + if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb { + return None; + } + // The center and the distances are doubled, so nothing is rounded. + let (cx, cy) = (tl + tr, tt + tb); + [(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)] + .into_iter() + .min_by_key(|&(_, distance)| distance) + .map(|(edge, _)| edge) +} + +/// A maximize that covers its monitor, trimmed to stop one pixel short of the monitor on each of +/// the `taskbars` edges where the work area reaches the monitor's edge (the taskbar there is +/// auto-hidden). `None` when `rect` does not cover the monitor or nothing is trimmed. +#[cfg_attr(not(windows), allow(dead_code))] +fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &[Edge]) -> Option { + if !covers(rect, monitor) { + return None; + } + let (mut l, mut t, mut r, mut b) = rect; + for edge in taskbars { + match edge { + Edge::Left if work.0 == monitor.0 => l = monitor.0.checked_add(1)?, + Edge::Top if work.1 == monitor.1 => t = monitor.1.checked_add(1)?, + Edge::Right if work.2 == monitor.2 => r = monitor.2.checked_sub(1)?, + Edge::Bottom if work.3 == monitor.3 => b = monitor.3.checked_sub(1)?, + _ => {} + } + } + let trimmed = (l, t, r, b); + (l < r && t < b && trimmed != rect).then_some(trimmed) +} + +#[cfg(test)] +mod tests { + use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + + #[test] + fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() { + // 1920 × 1080 with a 34 px taskbar: a caption-less maximize covers the whole monitor, + // taskbar included. Trimmed so the rect ends at the work area plus the frame the window + // was parked with. + let monitor = (0, 0, 1920, 1080); + let work = (0, 0, 1920, 1046); + assert_eq!(clamped_rect((-7, -7, 1927, 1087), monitor, work), Some((-7, -7, 1927, 1046 + 7))); + } + + #[test] + fn a_maximize_already_clear_of_the_taskbar_is_left_alone() { + // What Windows sizes a framed maximize to: the work area plus the frame. + assert_eq!(clamped_rect((-8, -8, 1928, 1054), (0, 0, 1920, 1080), (0, 0, 1920, 1046)), None); + } + + #[test] + fn a_maximize_stays_clear_of_a_taskbar_on_any_edge() { + // A taskbar on the top or a side edge: the rect moves inside the work area there and + // keeps its frame on the other edges. Once moved, it is left alone. + let monitor = (0, 0, 1920, 1080); + let rect = (-8, -8, 1928, 1088); + for (work, expected) in [ + ((0, 0, 1920, 1046), (-8, -8, 1928, 1054)), + ((0, 48, 1920, 1080), (-8, 40, 1928, 1088)), + ((0, 2, 1920, 1080), (-8, -6, 1928, 1088)), + ((0, 0, 1920, 1078), (-8, -8, 1928, 1086)), + ((48, 0, 1920, 1080), (40, -8, 1928, 1088)), + ((0, 0, 1872, 1080), (-8, -8, 1880, 1088)), + ] { + assert_eq!(clamped_rect(rect, monitor, work), Some(expected), "work area {work:?}"); + assert_eq!(clamped_rect(expected, monitor, work), None, "already moved, work area {work:?}"); + } + } + + #[test] + fn a_top_taskbar_is_cleared_on_any_monitor_and_at_any_frame_size() { + // A monitor above and left of the primary one, at frame sizes up to the limit. + let monitor = (-1920, -1080, 0, 0); + let work = (-1920, -1032, 0, 0); + for border in [0, 8, 16, 32] { + let rect = (-1920 - border, -1080 - border, border, border); + let expected = (-1920 - border, -1032 - border, border, border); + assert_eq!(clamped_rect(rect, monitor, work), Some(expected), "border {border}"); + assert_eq!(clamped_rect(expected, monitor, work), None, "border {border}"); + } + } + + #[test] + fn a_maximize_without_a_reserved_taskbar_or_being_dragged_is_left_alone() { + let monitor = (0, 0, 1920, 1080); + assert_eq!(clamped_rect((-8, -8, 1928, 1088), monitor, monitor), None); + let work = (0, 0, 1920, 1046); + assert_eq!(clamped_rect((100, 200, 1100, 900), monitor, work), None, "moved"); + assert_eq!(clamped_rect((-500, -7, 1427, 1087), monitor, work), None, "resized"); + let work = (0, 48, 1920, 1080); + assert_eq!(clamped_rect((-500, -8, 1428, 1088), monitor, work), None, "resized under a top taskbar"); + assert_eq!(clamped_rect((0, 48, 960, 1080), monitor, work), None, "snapped to half the screen"); + } + + #[test] + fn a_maximize_stops_a_pixel_short_of_an_auto_hidden_taskbar_edge() { + // An auto-hidden taskbar reserves no work area, so the work area is the whole monitor. + let monitor = (0, 0, 1920, 1080); + let rect = (-8, -8, 1928, 1088); + for (edge, expected) in + [(Edge::Bottom, (-8, -8, 1928, 1079)), (Edge::Top, (-8, 1, 1928, 1088)), (Edge::Left, (1, -8, 1928, 1088)), (Edge::Right, (-8, -8, 1919, 1088))] + { + assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[edge]), Some(expected), "{edge:?}"); + assert_eq!(short_of_autohide_taskbars(expected, monitor, monitor, &[edge]), None, "already trimmed, {edge:?}"); + assert_eq!(clamped_rect(expected, monitor, monitor), None, "left alone on the next frame, {edge:?}"); + } + assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[]), None, "no taskbar"); + // A taskbar that reserves its work area is moved clear of by `clamped_rect` instead. + assert_eq!(short_of_autohide_taskbars(rect, monitor, (0, 0, 1920, 1032), &[Edge::Bottom]), None, "shown taskbar"); + assert_eq!(short_of_autohide_taskbars((0, 0, 960, 1080), monitor, monitor, &[Edge::Bottom]), None, "half-screen"); + } + + #[test] + fn a_taskbar_sits_on_the_monitor_edge_nearest_its_center() { + let monitor = (0, 0, 1920, 1080); + assert_eq!(taskbar_edge((0, 1032, 1920, 1080), monitor), Some(Edge::Bottom), "shown"); + assert_eq!(taskbar_edge((0, 1078, 1920, 1126), monitor), Some(Edge::Bottom), "auto-hidden"); + assert_eq!(taskbar_edge((0, -46, 1920, 2), monitor), Some(Edge::Top)); + assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left)); + assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right)); + assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor"); + assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow"); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 2130c6d0..07351074 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -30,7 +30,7 @@ artwork. Licence: see `LICENSE.txt`. | `texturecraft-1024.png` | full tile, 1024 px | docs, store listings | | `texturecraft.icns` | macOS icon set, 16 to 1024 px | `packaging/macos/package.sh` (`CFBundleIconFile`) | | `texturecraft.ico` | Windows icon, 16 to 256 px | `apps/texturecraft/build.rs` (embedded in the `.exe`), the MSI (`packaging/windows/package.ps1`) | -| `hicolor//apps/ai.storyteller.texturecraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime window icon (`apps/texturecraft/src/main.rs`) and the README icon | `packaging/linux/ai.storyteller.texturecraft.desktop` | +| `hicolor//apps/ai.storyteller.texturecraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime window and taskbar icon (`apps/texturecraft/src/main.rs`) and the README icon, and the 16 to 64 px ones the icon at the left of the title bar (`crates/ui-egui/src/titlebar.rs`) | `packaging/linux/ai.storyteller.texturecraft.desktop` | | `hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | Linux scalable icon | as above | ## How it reaches each OS @@ -38,8 +38,8 @@ artwork. Licence: see `LICENSE.txt`. - **macOS:** the app sets the Dock / app-switcher icon at runtime (`ViewportBuilder::with_icon`); the `.app` from `packaging/macos/package.sh` carries `texturecraft.icns`. - **Windows:** `build.rs` embeds `texturecraft.ico` and VERSIONINFO with `winresource` (taskbar, Start - menu, Explorer, Alt-Tab); the runtime icon covers the title bar, and the MSI uses the same `.ico` - for its shortcuts. + menu, Explorer, Alt-Tab); the runtime icon covers the window and taskbar, and the MSI uses the + same `.ico` for its shortcuts. - **Linux and FreeBSD:** the packages install `packaging/linux/ai.storyteller.texturecraft.desktop` to `share/applications/` and `hicolor/` to `share/icons/`; the AppImage and Flatpak carry the same files. diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 1ed4413a..85de5c3b 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -14,6 +14,7 @@ texturecraft-render = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] } egui = { workspace = true } craft-ui = { workspace = true } +craft-window = { workspace = true } egui-phosphor = { version = "0.14", features = ["regular", "fill"] } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 83ab93a6..167b9754 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -5,7 +5,7 @@ //! - `command.run {id, params?}`: run an engine command (programmatic: never opens a dialog). //! - `command.list {filter?}`: every command with params docs and enabled state. //! - `session.inspect`: project, texture sets, layer stack, tool, camera, display, history. -//! - `ui.inspect`: the UI state (panels, windows, mode, layout, viewport rect). +//! - `ui.inspect`: the UI state (panels, windows, mode, layout, viewport rect, who draws the title bar). //! - `ui.menu.list`: the menu catalog with ids, shortcuts and whether each is live. //! - `ui.menu.invoke {id}`: behave like a menu click (may open a window). //! - `ui.set {...}`: merge fields into the UI state (e.g. `{"layout":"Only3D"}`). @@ -108,6 +108,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & "viewport": [r.min.x, r.min.y, r.width(), r.height()], "fps": app.fps, "uiMs": app.ui_ms, + "titleBar": app.title_bar.name(), "baking": app.bake_progress(), "toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::>(), })) diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 9fe9dbc6..ce534a6f 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -970,4 +970,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Green", "Grün"), ("Amber", "Bernstein"), ("Pink", "Pink"), + ("Minimize", "Minimieren"), + ("Maximize", "Maximieren"), + ("Restore", "Wiederherstellen"), + ("Title bar", "Titelleiste"), + ("System title bar (applies on restart)", "Titelleiste des Systems (ab dem nächsten Start)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index f345a459..2b57afd8 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -955,4 +955,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Green", "Verde"), ("Amber", "Ámbar"), ("Pink", "Rosa"), + ("Minimize", "Minimizar"), + ("Maximize", "Maximizar"), + ("Restore", "Restaurar"), + ("Title bar", "Barra de título"), + ("System title bar (applies on restart)", "Barra de título del sistema (se aplica al reiniciar)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index d79c6d0c..0e72b031 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -970,4 +970,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Green", "Vert"), ("Amber", "Ambre"), ("Pink", "Rose"), + ("Minimize", "Réduire"), + ("Maximize", "Agrandir"), + ("Restore", "Restaurer"), + ("Title bar", "Barre de titre"), + ("System title bar (applies on restart)", "Barre de titre du système (au prochain démarrage)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 2cc2f0b0..9260b188 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -964,4 +964,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Green", "Verde"), ("Amber", "Ambra"), ("Pink", "Rosa"), + ("Minimize", "Riduci a icona"), + ("Maximize", "Ingrandisci"), + ("Restore", "Ripristina"), + ("Title bar", "Barra del titolo"), + ("System title bar (applies on restart)", "Barra del titolo di sistema (si applica al riavvio)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 45735566..2e333ab9 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -937,4 +937,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Green", "グリーン"), ("Amber", "アンバー"), ("Pink", "ピンク"), + ("Minimize", "最小化"), + ("Maximize", "最大化"), + ("Restore", "元のサイズに戻す"), + ("Title bar", "タイトルバー"), + ("System title bar (applies on restart)", "システムのタイトルバー (再起動後に適用)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 45741a87..3945c9a9 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -922,4 +922,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Green", "초록"), ("Amber", "호박색"), ("Pink", "분홍"), + ("Minimize", "최소화"), + ("Maximize", "최대화"), + ("Restore", "이전 크기로 복원"), + ("Title bar", "제목 표시줄"), + ("System title bar (applies on restart)", "시스템 제목 표시줄 (다시 시작하면 적용)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 60fb8b9c..788df7f9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -952,4 +952,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Green", "Verde"), ("Amber", "Âmbar"), ("Pink", "Rosa"), + ("Minimize", "Minimizar"), + ("Maximize", "Maximizar"), + ("Restore", "Restaurar"), + ("Title bar", "Barra de título"), + ("System title bar (applies on restart)", "Barra de título do sistema (aplicada ao reiniciar)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 359cafcb..3de5246c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -868,4 +868,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Green", "绿色"), ("Amber", "琥珀色"), ("Pink", "粉色"), + ("Minimize", "最小化"), + ("Maximize", "最大化"), + ("Restore", "还原"), + ("Title bar", "标题栏"), + ("System title bar (applies on restart)", "系统标题栏(重启后生效)"), + ( + "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", + "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", + ), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 28b33de8..22da8a3d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -23,6 +23,7 @@ pub mod shelf; pub mod state; pub mod theme; pub mod thumbs; +pub mod titlebar; pub mod toolbar; pub mod viewport; pub mod web_files; @@ -93,6 +94,8 @@ pub struct TextureCraftApp { pub fonts: fonts::UiFonts, /// A notice across the top of the window until dismissed (English key, shown translated). pub banner: Option<&'static str>, + /// Who draws the window's title bar (decided at startup, before the window opens). + pub title_bar: titlebar::TitleBar, last_time: f64, /// When the next autosave is due (seconds of app time; desktop only). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -135,6 +138,7 @@ impl TextureCraftApp { render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, + title_bar: titlebar::TitleBar::default(), last_time: 0.0, next_autosave, styled: None, @@ -386,7 +390,7 @@ impl eframe::App for TextureCraftApp { let ctx = ui.ctx().clone(); let t0 = now_ms(); if !self.ui.hide_ui { - menus::menu_bar(self, ui); + titlebar::show(self, ui); banner(self, ui); toolbar::top_bar(self, ui); toolbar::status_bar(self, ui); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 703ca3b9..bad5be7a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -170,45 +170,44 @@ pub fn parse_shortcut(s: &str) -> Option { key.map(|k| KeyboardShortcut::new(mods, k)) } +/// The menus, then the mode label at the right of `ui` (the strip `titlebar::show` lays out). pub fn menu_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tk = Tokens::get(ui.ctx()); - egui::Panel::top("menu_bar").exact_size(24.0).frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(6, 0))).show(ui, |ui| { - egui::MenuBar::new().ui(ui, |ui| { - let ctx = ui.ctx().clone(); - for top in TOP { - ui.menu_button(tr(top), |ui| { - ui.set_min_width(220.0); - let mut current_sub: Option<&str> = None; - let items: Vec = CATALOG.iter().filter(|i| i.menu == top).copied().collect(); - for item in &items { - if let Some(s) = item.sub { - if current_sub == Some(s) { - continue; + egui::MenuBar::new().ui(ui, |ui| { + let ctx = ui.ctx().clone(); + for top in TOP { + ui.menu_button(tr(top), |ui| { + ui.set_min_width(220.0); + let mut current_sub: Option<&str> = None; + let items: Vec = CATALOG.iter().filter(|i| i.menu == top).copied().collect(); + for item in &items { + if let Some(s) = item.sub { + if current_sub == Some(s) { + continue; + } + current_sub = Some(s); + ui.menu_button(tr(s), |ui| { + for x in items.iter().filter(|x| x.sub == Some(s)) { + menu_item(app, &ctx, ui, x); } - current_sub = Some(s); - ui.menu_button(tr(s), |ui| { - for x in items.iter().filter(|x| x.sub == Some(s)) { - menu_item(app, &ctx, ui, x); - } - }); - continue; - } - if item.label == "-" { - ui.separator(); - continue; - } - menu_item(app, &ctx, ui, item); + }); + continue; } - }); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mode = match app.ui.mode { - Mode::Painting => tr("Painting"), - Mode::Baking => tr("Baking"), - Mode::Rendering => tr("Rendering"), - }; - ui.label(egui::RichText::new(mode).size(11.0).color(tk.text_dim)); + if item.label == "-" { + ui.separator(); + continue; + } + menu_item(app, &ctx, ui, item); + } }); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mode = match app.ui.mode { + Mode::Painting => tr("Painting"), + Mode::Baking => tr("Baking"), + Mode::Rendering => tr("Rendering"), + }; + ui.label(egui::RichText::new(mode).size(11.0).color(tk.text_dim)); }); }); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e9cb4933..4d15d9e4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -80,6 +80,8 @@ pub struct Prefs { pub brightness: crate::theme::Brightness, /// The colour of what is on, chosen or focused. pub accent: crate::theme::Accent, + /// The system draws the window's title bar instead of TextureCraft (desktop; read at startup). + pub system_title_bar: bool, } impl Default for Prefs { @@ -91,6 +93,7 @@ impl Default for Prefs { viewport_texture: 0, brightness: crate::theme::Brightness::default(), accent: crate::theme::Accent::default(), + system_title_bar: false, } } } diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs new file mode 100644 index 00000000..818c14ac --- /dev/null +++ b/crates/ui-egui/src/titlebar.rs @@ -0,0 +1,353 @@ +//! The strip at the top of the window: the app icon at the very left, the menus and the mode label, +//! and the window's title bar unless the system draws one. As the title bar its empty space moves +//! the window and follows the system's double-click setting (craft-window's `title_bar`), and on a +//! window without an OS frame it also has the minimize, maximize/restore and close buttons and +//! invisible resize zones along the window's edges. +//! +//! Who draws the frame is decided once at startup ([`TitleBar::decide`]): Windows draws no OS +//! frame, macOS keeps its traffic lights over the strip (a full-size content view with a hidden +//! title), Linux and the BSDs follow craft-window's probe (the app draws the frame where the +//! compositor leaves it to the app, as GNOME does). `TEXTURECRAFT_TITLEBAR=app` or `=system` +//! overrides that, and Settings › Interface › System title bar brings the OS frame back on the +//! next start. The web build has no window frame: the strip is the menu bar. + +use craft_window::{Button, Frame, Layout}; +use egui::emath::GuiRounding as _; +use egui::{Align, Color32, CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; + +/// Who draws the window's title bar. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum TitleBar { + /// The system (or the browser) draws it: the strip is the menu bar. + #[default] + System, + /// macOS: the traffic lights sit over the strip, which keeps room for them at its left. + Integrated, + /// No OS frame: the strip is the title bar, with the window buttons in this layout. + App(Layout), +} + +/// One caption button: as wide as Windows' own. +pub const BUTTON_WIDTH: f32 = 46.0; +/// The room at the strip's left for the macOS traffic lights (their width and the gaps around them). +const TRAFFIC_LIGHTS: f32 = 78.0; +/// The app icon's side, in points. +const ICON: f32 = 16.0; +/// The space between the strip's edges (or its caption buttons) and its content. +const PAD: f32 = 8.0; +/// Resize zone thickness along an edge, and the side of a corner zone. +const EDGE: f32 = 5.0; +const CORNER: f32 = 12.0; + +/// The app icon's PNGs (`assets/app-icon/hicolor`), smallest first: the strip draws the one that +/// fills [`ICON`] points at the screen's scale without being stretched. +const ICONS: [(f32, &[u8]); 5] = [ + (16.0, include_bytes!("../../../assets/app-icon/hicolor/16x16/apps/ai.storyteller.texturecraft.png")), + (24.0, include_bytes!("../../../assets/app-icon/hicolor/24x24/apps/ai.storyteller.texturecraft.png")), + (32.0, include_bytes!("../../../assets/app-icon/hicolor/32x32/apps/ai.storyteller.texturecraft.png")), + (48.0, include_bytes!("../../../assets/app-icon/hicolor/48x48/apps/ai.storyteller.texturecraft.png")), + (64.0, include_bytes!("../../../assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png")), +]; + +impl TitleBar { + /// Decide who draws the title bar; call once at startup, before the window is created. + /// `system` is Settings › Interface › System title bar. + pub fn decide(system: bool) -> TitleBar { + let choice = craft_window::Choice::probe(craft_window::Prefix::new("TEXTURECRAFT")); + Self::from_choice(choice.frame(), choice.overridden(), system) + } + + /// `TEXTURECRAFT_TITLEBAR` (`overridden`) wins, then the System title bar setting. Otherwise + /// Windows draws its own caption, macOS integrates the traffic lights and the other systems + /// take craft-window's `frame`. + fn from_choice(frame: &Frame, overridden: Option, system: bool) -> TitleBar { + if overridden.is_none() && system { + return TitleBar::System; + } + match frame { + Frame::App(layout) => TitleBar::App(layout.clone()), + Frame::Desktop if overridden.is_some() => TitleBar::System, + Frame::Desktop if cfg!(windows) => TitleBar::App(Layout::default()), + Frame::Desktop if cfg!(target_os = "macos") => TitleBar::Integrated, + Frame::Desktop => TitleBar::System, + } + } + + /// `builder` with this frame: decorations off for the app's own, and on macOS the content + /// under a transparent title bar without its title. + pub fn viewport(&self, builder: egui::ViewportBuilder) -> egui::ViewportBuilder { + let frame = match self { + TitleBar::App(layout) => Frame::App(layout.clone()), + _ => Frame::Desktop, + }; + let builder = craft_window::decorate(builder, &frame); + if *self == TitleBar::Integrated { builder.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false) } else { builder } + } + + /// The name `ui.inspect` reports: `app`, `integrated` or `system`. + pub fn name(&self) -> &'static str { + match self { + TitleBar::System => "system", + TitleBar::Integrated => "integrated", + TitleBar::App(_) => "app", + } + } +} + +/// The strip's height: the body text with room around it, 28 to 32 points (so the macOS traffic +/// lights and Windows-sized caption buttons fit it). +pub fn height(ui: &Ui) -> f32 { + (ui.text_style_height(&egui::TextStyle::Body) + 14.0).clamp(28.0, 32.0) +} + +/// The strip: menus between the app icon and the mode label, the window buttons at the ends the +/// layout names, and as the title bar its empty space moving the window. +pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + let tk = Tokens::get(ui.ctx()); + let bar = app.title_bar.clone(); + let (left, right) = match &bar { + TitleBar::App(layout) => (layout.left.as_slice(), layout.right.as_slice()), + _ => (&[][..], &[][..]), + }; + egui::Panel::top("menu_bar").exact_size(height(ui)).show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| { + let rect = ui.max_rect(); + // First, so the strip's controls drawn over it keep their own clicks. + if bar != TitleBar::System { + craft_window::title_bar::empty_area(ui, rect); + } + let ends = |n: usize| n as f32 * BUTTON_WIDTH; + let inset = if bar == TitleBar::Integrated { TRAFFIC_LIGHTS } else { ends(left.len()) + PAD }; + let content = Rect::from_min_max(pos2(rect.left() + inset, rect.top()), pos2(rect.right() - ends(right.len()) - PAD, rect.bottom())); + ui.scope_builder(egui::UiBuilder::new().max_rect(content).layout(egui::Layout::left_to_right(Align::Center)), |ui| { + paint_icon(ui); + crate::menus::menu_bar(app, ui); + }); + caption_buttons(ui, left, rect.left(), rect); + caption_buttons(ui, right, rect.right() - ends(right.len()), rect); + }); + if matches!(bar, TitleBar::App(_)) { + resize_zones(ui); + } +} + +/// The app icon at the cursor, [`ICON`] points square, centred on the row and on whole pixels. +fn paint_icon(ui: &mut Ui) { + let ppp = ui.ctx().pixels_per_point(); + let Some(&(px, png)) = ICONS.iter().find(|(px, _)| *px >= ICON * ppp - 0.5).or(ICONS.last()) else { return }; + let id = Id::unique(("app_icon", px as u32)); + let texture = match ui.data(|d| d.get_temp::>(id)) { + Some(t) => t, + None => { + // Decoded once per size; a PNG that doesn't decode leaves the space empty. + let t = image::load_from_memory(png).ok().map(|img| { + let img = img.into_rgba8(); + let size = [img.width() as usize, img.height() as usize]; + ui.ctx().load_texture("app_icon", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR) + }); + ui.data_mut(|d| d.insert_temp(id, t.clone())); + t + } + }; + let row = ui.max_rect(); + let min = pos2(ui.cursor().min.x, row.center().y - ICON / 2.0).round_to_pixels(ppp); + if let Some(t) = texture { + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + ui.painter().image(t.id(), Rect::from_min_size(min, vec2(ICON, ICON)), uv, Color32::WHITE); + } + // The menu titles have no padding of their own: the gap the strip keeps at its edges. + ui.add_space(ICON + PAD); +} + +fn maximized(ctx: &egui::Context) -> bool { + ctx.input(|i| i.viewport().maximized.unwrap_or(false)) +} + +/// Caption button ids (stable, so tests and agents can find them). +fn caption_id(b: Button) -> Id { + Id::unique(("titlebar_caption", b as u8)) +} + +/// `buttons` from `x` rightwards, the strip's full height, flush with its top so a maximized +/// window's corner hits the outermost one. +fn caption_buttons(ui: &mut Ui, buttons: &[Button], x: f32, bar: Rect) { + let tk = Tokens::get(ui.ctx()); + let max = maximized(ui.ctx()); + let focused = ui.input(|i| i.viewport().focused.unwrap_or(true)); + for (i, &b) in buttons.iter().enumerate() { + let r = Rect::from_min_size(pos2(x + i as f32 * BUTTON_WIDTH, bar.top()), vec2(BUTTON_WIDTH, bar.height())); + let resp = ui.interact(r, caption_id(b), Sense::click()); + let tip = match b { + Button::Minimize => tr("Minimize"), + Button::Maximize if max => tr("Restore"), + Button::Maximize => tr("Maximize"), + Button::Close => tr("Close"), + }; + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + let close = b == Button::Close; + let fill = match (resp.is_pointer_button_down_on(), resp.hovered()) { + (true, _) if close => tk.danger.gamma_multiply(0.8), + (_, true) if close => tk.danger, + (true, _) => tk.button, + (_, true) => tk.row_hover, + _ => Color32::TRANSPARENT, + }; + ui.painter().rect_filled(r, 0.0, fill); + // White on the red, as every system's close button; dimmed while the window is inactive. + let ink = if close && resp.hovered() { + Color32::WHITE + } else if focused { + tk.text + } else { + tk.text_dim + }; + paint_glyph(ui, b, max, r.center(), ink); + if resp.on_hover_text(tip).clicked() { + ui.ctx().send_viewport_cmd(match b { + Button::Minimize => ViewportCommand::Minimized(true), + Button::Maximize => ViewportCommand::Maximized(!max), + // The same request as the system's close button. + Button::Close => ViewportCommand::Close, + }); + } + } +} + +/// The 10-point line glyphs, one physical pixel wide per whole step of the screen's scale and on +/// pixel centres, so they stay crisp at any scale. +fn paint_glyph(ui: &Ui, b: Button, maximized: bool, at: egui::Pos2, ink: Color32) { + let ppp = ui.ctx().pixels_per_point(); + let px = ppp.round().max(1.0); + let stroke = Stroke::new(px / ppp, ink); + // An odd width centres the line in a pixel, an even one on a pixel edge. + let snap = |v: f32| if px as u32 % 2 == 1 { v.round_to_pixel_center(ppp) } else { v.round_to_pixels(ppp) }; + let g = Rect::from_min_max(pos2(snap(at.x - 5.0), snap(at.y - 5.0)), pos2(snap(at.x + 5.0), snap(at.y + 5.0))); + let p = ui.painter(); + match b { + Button::Minimize => { + p.line_segment([g.left_center(), g.right_center()].map(|q| pos2(q.x, snap(q.y))), stroke); + } + // Restore: a front square with the corner of the one behind it. + Button::Maximize if maximized => { + let front = Rect::from_min_max(pos2(g.left(), snap(g.top() + 2.0)), pos2(snap(g.right() - 2.0), g.bottom())); + p.rect_stroke(front, 0.0, stroke, egui::StrokeKind::Middle); + let (l, t) = (snap(g.left() + 2.0), front.top()); + p.line( + vec![pos2(l, t), pos2(l, g.top()), g.right_top(), pos2(g.right(), snap(g.bottom() - 2.0)), pos2(front.right(), snap(g.bottom() - 2.0))], + stroke, + ); + } + Button::Maximize => { + p.rect_stroke(g, 0.0, stroke, egui::StrokeKind::Middle); + } + Button::Close => { + p.line_segment([g.left_top(), g.right_bottom()], stroke); + p.line_segment([g.right_top(), g.left_bottom()], stroke); + } + } +} + +/// The edge and corner zones of a window with content rect `w`: (zone, direction, cursor). Corners +/// come last so they win where they overlap the edges. +fn zones(w: Rect) -> [(Rect, ResizeDirection, CursorIcon); 8] { + use ResizeDirection::*; + let (e, c) = (EDGE, CORNER); + [ + (Rect::from_min_max(w.left_top(), pos2(w.right(), w.top() + e)), North, CursorIcon::ResizeVertical), + (Rect::from_min_max(pos2(w.left(), w.bottom() - e), w.right_bottom()), South, CursorIcon::ResizeVertical), + (Rect::from_min_max(w.left_top(), pos2(w.left() + e, w.bottom())), West, CursorIcon::ResizeHorizontal), + (Rect::from_min_max(pos2(w.right() - e, w.top()), w.right_bottom()), East, CursorIcon::ResizeHorizontal), + (Rect::from_min_size(w.left_top(), vec2(c, c)), NorthWest, CursorIcon::ResizeNwSe), + (Rect::from_min_size(w.right_top() - vec2(c, 0.0), vec2(c, c)), NorthEast, CursorIcon::ResizeNeSw), + (Rect::from_min_size(w.left_bottom() - vec2(0.0, c), vec2(c, c)), SouthWest, CursorIcon::ResizeNeSw), + (Rect::from_min_size(w.right_bottom() - vec2(c, c), vec2(c, c)), SouthEast, CursorIcon::ResizeNwSe), + ] +} + +/// Invisible zones along the window's edges, above everything else; a press in one starts the +/// system's resize in that direction. None while the window is maximized or full screen. +fn resize_zones(ui: &mut Ui) { + let ctx = ui.ctx().clone(); + if maximized(&ctx) || ctx.input(|i| i.viewport().fullscreen.unwrap_or(false)) { + return; + } + let w = ctx.content_rect(); + let zui = ui.new_child(egui::UiBuilder::new().layer_id(LayerId::new(Order::Foreground, Id::unique("titlebar_resize"))).max_rect(w)); + for (i, (r, dir, cursor)) in zones(w).into_iter().enumerate() { + // Drag only (not focusable): Tab does not stop on the zones. + let resp = zui.interact(r, Id::unique(("titlebar_resize", i)), Sense::DRAG).on_hover_cursor(cursor); + if resp.drag_started_by(PointerButton::Primary) { + ctx.send_viewport_cmd(ViewportCommand::BeginResize(dir)); + // The window manager runs the resize and, on X11 and Wayland, keeps the button + // release: end egui's drag now, or the next press would start nothing. + ctx.stop_dragging(); + ctx.input_mut(|i| i.pointer = Default::default()); + } + } +} + +/// Once per frame after the UI, on macOS with the integrated strip: the traffic lights centred on +/// the strip, inset from its left as far as from its top, and AppKit's `movable` flag following +/// what is under the pointer (`movable` keeps the value last set). +#[cfg(target_os = "macos")] +pub fn sync_native(bar: &TitleBar, ui: &Ui, frame: &eframe::Frame, movable: &mut Option) { + if *bar != TitleBar::Integrated { + return; + } + let h = height(ui); + // AppKit's buttons are 14 points tall. + frame.set_traffic_lights_position(ui.ctx(), egui::Rangef::new(0.0, h), (h - 14.0) / 2.0); + craft_window::title_bar::sync_movable(ui.ctx(), movable); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_override_wins_then_the_setting_then_the_platform() { + let gnome = Frame::App(Layout::parse("appmenu:close")); + // TEXTURECRAFT_TITLEBAR=app / =system, whatever the setting. + for system in [false, true] { + assert_eq!(TitleBar::from_choice(&gnome, Some(true), system), TitleBar::App(Layout::parse("appmenu:close"))); + assert_eq!(TitleBar::from_choice(&Frame::Desktop, Some(false), system), TitleBar::System); + } + // The setting brings the system's frame back. + assert_eq!(TitleBar::from_choice(&gnome, None, true), TitleBar::System); + assert_eq!(TitleBar::from_choice(&Frame::Desktop, None, true), TitleBar::System); + // The platform: a compositor that leaves the frame to the app gets the app's. + assert_eq!(TitleBar::from_choice(&gnome, None, false), TitleBar::App(Layout::parse("appmenu:close"))); + let desktop = TitleBar::from_choice(&Frame::Desktop, None, false); + let expected = if cfg!(windows) { + TitleBar::App(Layout::default()) + } else if cfg!(target_os = "macos") { + TitleBar::Integrated + } else { + TitleBar::System + }; + assert_eq!(desktop, expected); + } + + #[test] + fn only_the_app_frame_turns_decorations_off() { + let b = TitleBar::App(Layout::default()).viewport(egui::ViewportBuilder::default()); + assert_eq!(b.decorations, Some(false)); + let b = TitleBar::Integrated.viewport(egui::ViewportBuilder::default()); + assert_eq!((b.decorations, b.fullsize_content_view, b.title_shown), (Some(true), Some(true), Some(false))); + let b = TitleBar::System.viewport(egui::ViewportBuilder::default()); + assert_eq!((b.decorations, b.fullsize_content_view), (Some(true), None)); + } + + #[test] + fn resize_corners_win_over_edges() { + let w = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 600.0)); + let at = |p: egui::Pos2| zones(w).into_iter().rev().find(|(r, ..)| r.contains(p)).map(|(_, d, _)| d); + assert_eq!(at(pos2(2.0, 2.0)), Some(ResizeDirection::NorthWest)); + assert_eq!(at(pos2(500.0, 1.0)), Some(ResizeDirection::North)); + assert_eq!(at(pos2(998.0, 300.0)), Some(ResizeDirection::East)); + assert_eq!(at(pos2(500.0, 300.0)), None); + } +} diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 27de96d2..cde04b11 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -401,6 +401,13 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); ui.end_row(); + #[cfg(not(target_arch = "wasm32"))] + { + ui.label(tr("Title bar")); + ui.checkbox(&mut p.system_title_bar, tr("System title bar (applies on restart)")) + .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar")); + ui.end_row(); + } }); ui.add_space(8.0); ui.label(caption(tr("Viewport"))); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 2edc5bf9..803d6d05 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -5,8 +5,9 @@ //! TC_UI_SNAPSHOTS= cargo test -p texturecraft-ui-egui --release --test ui_snapshots -- --ignored //! ``` //! -//! Writes `/.png` at 1600x960: the default layout in each brightness, a floating -//! panel and the main windows. Ignored by default: it needs a GPU adapter and takes a few +//! Writes `/.png` at 1600x960: the default layout in each brightness, the strip as the +//! app-drawn title bar (Windows) and with the macOS traffic lights' inset, a floating panel and the +//! main windows. Ignored by default: it needs a GPU adapter and takes a few //! seconds. use std::path::{Path, PathBuf}; @@ -15,6 +16,7 @@ use egui_kittest::Harness; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::theme::Brightness; +use texturecraft_ui_egui::titlebar::TitleBar; fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { h.run_steps(6); @@ -39,6 +41,18 @@ fn window_snapshots() { save(&mut h, &dir, name); } h.state_mut().ui.prefs.brightness = Brightness::MediumDark; + h.state_mut().title_bar = TitleBar::Integrated; + save(&mut h, &dir, "titlebar-macos"); + h.state_mut().title_bar = TitleBar::App(craft_window::Layout::default()); + save(&mut h, &dir, "titlebar-app"); + // The close button under the pointer, and the glyphs at a fractional scale. + h.hover_at(egui::pos2(1600.0 - 23.0, 14.0)); + save(&mut h, &dir, "titlebar-app-close-hover"); + h.hover_at(egui::pos2(800.0, 500.0)); + h.set_pixels_per_point(1.5); + save(&mut h, &dir, "titlebar-app-150"); + h.set_pixels_per_point(1.0); + h.state_mut().title_bar = TitleBar::System; h.state_mut().ui.dock.focus(Panel::Display); save(&mut h, &dir, "panel-display"); h.state_mut().ui.dock.close(Panel::Display); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 45017e70..56b2155b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -45,10 +45,10 @@ keeps its state in a throwaway file. | `command.run` | `{id, params?}` | the command's JSON result | | `command.list` | `{filter?}` | `[{id, label, menu, shortcut, params, enabled}]` | | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | -| `ui.inspect` | | UI state, viewport rect, fps, bake progress, toasts | +| `ui.inspect` | | UI state, viewport rect, fps, bake progress, toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled}` | | `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window) | -| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History` and `Log`; `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds) | `null` | +| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History` and `Log`; `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | | `ui.resize` | `{width, height}` | Sets the window's inner size in points (640–7680), leaving maximized state; for recordings and screenshots at a fixed size | diff --git a/docs/features.md b/docs/features.md index eb7dca1b..02cfd08c 100644 --- a/docs/features.md +++ b/docs/features.md @@ -96,6 +96,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - A modern look in **four brightness levels** (dark, medium dark, medium light and light) with **seven accent colors**, set in Settings › Interface. +- **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux + desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same + strip, and Settings › Interface › System title bar for the system's frame instead. - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed them. - A **shortcut editor** with conflict detection, and every shortcut shown in its tooltip.