AI media harness for planning, generating, and editing locally
TypeScript
Frameless Mica window with native shell commands
Bitti406933200a34
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex df4a931..3d3a908 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -3374,8 +3374,10 @@ dependencies = ["tauri-plugin-dialog","tauri-plugin-process","tauri-plugin-updater",+ "tauri-plugin-window-state","tempfile","tokio",+ "webview2-com","windows","windows-sys 0.59.0",]@@ -3865,6 +3867,21 @@ dependencies = ["zip",]+[[package]]+name = "tauri-plugin-window-state"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73736611e14142408d15353e21e3cca2f12a3cfb523ad0ce85999b6d2ef1a704"+dependencies = [+ "bitflags 2.13.1",+ "log",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.20",+]+[[package]]name = "tauri-runtime"version = "2.11.3"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 2a524e5..dcb5929 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -30,9 +30,26 @@ jpeg-encoder = "0.6"# Keep image decoding compatible with the package's Rust 1.87 minimum.image = { version = "=0.25.8", default-features = false, features = ["jpeg", "png"] }tokio = { version = "1", features = ["rt", "time", "net", "macros"] }+tauri-plugin-window-state = "2"[target.'cfg(windows)'.dependencies]-windows = { version = "0.61", features = ["Win32_Graphics_Dxgi"] }+# Must stay on the same major as wry's, or with_webview hands back a controller+# of a different crate's type. Used for the browser-accelerator switch (app.rs).+webview2-com = "0.38"+# The native shell (native_shell.rs): UI_ViewManagement reads the Windows+# accent colours, the Wdk / SystemInformation pair reads the real OS build to+# decide whether Mica exists, Dwm asks for rounded corners on the frameless+# window, and KeyboardAndMouse replays Ctrl+X/C/V/A for the text context menu.+windows = { version = "0.61", features = [+ "Win32_Graphics_Dxgi",+ "Win32_Graphics_Dwm",+ "Win32_Foundation",+ "Win32_UI_Input_KeyboardAndMouse",+ "Foundation",+ "UI_ViewManagement",+ "Wdk_System_SystemServices",+ "Win32_System_SystemInformation",+] }windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_UI_Shell"] }[dev-dependencies]diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 0cfe218..5885c58 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -2,7 +2,23 @@"$schema": "../gen/schemas/desktop-schema.json","identifier": "default","description": "Default permissions for the Slopus desktop window",- "windows": ["main"],- "permissions": ["core:default", "updater:default", "process:allow-restart"]+ "windows": [+ "main"+ ],+ "permissions": [+ "core:default",+ "core:window:allow-start-dragging",+ "core:window:allow-minimize",+ "core:window:allow-toggle-maximize",+ "core:window:allow-internal-toggle-maximize",+ "core:window:allow-close",+ "core:window:allow-is-maximized",+ "core:window:allow-set-progress-bar",+ "core:window:allow-set-theme",+ "dialog:allow-ask",+ "dialog:allow-message",+ "dialog:allow-confirm",+ "updater:default",+ "process:allow-restart"+ ]}-diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rsindex a1c29ca..f565537 100644--- a/src-tauri/src/app.rs+++ b/src-tauri/src/app.rs@@ -1,7 +1,7 @@use crate::window::{CloseDecision, ExitGuard};use crate::{- agent, app_paths, app_settings, commands, cuda_support, diagnostics, export, slopfab, weights,- window,+ agent, app_paths, app_settings, commands, cuda_support, diagnostics, export, native_shell,+ slopfab, weights, window,};use std::io;/// Portable distributions carry a marker because Windows updates launch an@@ -31,9 +31,51 @@ pub fn run() {.windows.first().ok_or_else(|| io::Error::other("Missing main window configuration"))?;- tauri::WebviewWindowBuilder::from_config(app, window_config)?+ /* Built hidden and shown at the end of setup, so the restore of the+ remembered size/position (tauri-plugin-window-state, which runs as+ the window is created) never shows as a jump. */+ let mut builder = tauri::WebviewWindowBuilder::from_config(app, window_config)?.data_directory(data_directory)- .build()?;+ .visible(false)+ /* Needs WebView2 125+; older runtimes keep the classic bars. */+ .scroll_bar_style(tauri::webview::ScrollBarStyle::FluentOverlay)+ .general_autofill_enabled(false);+ if native_shell::window_state_missing(app.handle()) {+ if let Ok(Some(monitor)) = app.primary_monitor() {+ let area = monitor.work_area();+ let (width, height) = native_shell::first_launch_size(+ area.size.width,+ area.size.height,+ monitor.scale_factor(),+ (+ window_config.min_width.unwrap_or(900.0),+ window_config.min_height.unwrap_or(650.0),+ ),+ );+ builder = builder.inner_size(width, height).center();+ }+ }+ /* Mica on Windows 11: the window and the webview go transparent and+ the page is told before its first script runs (theme-boot.js+ reads the global). Windows 10 keeps the opaque ground. */+ let mica = native_shell::mica_supported();+ if mica {+ builder = builder+ .transparent(true)+ .background_color(tauri::window::Color(0, 0, 0, 0))+ .effects(tauri::utils::config::WindowEffectsConfig {+ effects: vec![tauri::window::Effect::Mica],+ ..Default::default()+ })+ .initialization_script(native_shell::backdrop_script());+ }+ app.state::<native_shell::Backdrop>()+ .mica+ .store(mica, std::sync::atomic::Ordering::Release);+ let window = builder.build()?;+ native_shell::round_corners(&window);+ native_shell::disable_browser_behaviour(&window);+ native_shell::watch_accent(app.handle());match diagnostics::initialize(app.handle()) {Ok(info) => diagnostics::info("app",@@ -48,9 +90,9 @@ pub fn run() {),Err(error) => eprintln!("Could not initialize diagnostic logging: {error}"),}- if let Some(window) = app.get_webview_window("main") {- window::apply_theme(&window);- }+ window::apply_theme(&window);+ window.show()?;+ let _ = window.set_focus();Ok(())}).manage(crate::media::access::MediaAccess::default())@@ -59,28 +101,73 @@ pub fn run() {.manage(slopfab::SlopfabRuntime::default()).manage(weights::WeightDownloads::default()).manage(ExitGuard::default())+ .manage(native_shell::Backdrop::default())+ .manage(native_shell::SystemAccent::default())+ .on_menu_event(|_app, event| {+ native_shell::handle_menu_event(event.id().as_ref());+ }).on_window_event(|window, event| {- use tauri::{Emitter as _, Manager as _};- let tauri::WindowEvent::CloseRequested { api, .. } = event else {- return;- };- let guard = window.state::<ExitGuard>();- match guard.on_close_requested() {- CloseDecision::Close => {}- CloseDecision::Waiting => api.prevent_close(),- CloseDecision::Ask => {- api.prevent_close();- // If the question cannot even be delivered there is nobody- // to answer it, and refusing to close would be worse than- // closing unasked.- if window.emit("app-close-requested", ()).is_err() {- guard.answered(true);- let _ = window.destroy();+ use tauri::Manager as _;+ use tauri_plugin_dialog::{DialogExt as _, MessageDialogButtons, MessageDialogKind};+ match event {+ /* The OS theme flipped: repaint the opaque ground (a no-op under+ Mica, whose tint follows the window theme by itself). */+ tauri::WindowEvent::ThemeChanged(_) => {+ if let Some(webview_window) = window.get_webview_window(window.label()) {+ window::apply_theme(&webview_window);+ }+ }+ tauri::WindowEvent::CloseRequested { api, .. } => {+ let guard = window.state::<ExitGuard>();+ match guard.on_close_requested() {+ CloseDecision::Close => {}+ CloseDecision::Waiting => api.prevent_close(),+ CloseDecision::Ask => {+ api.prevent_close();+ let jobs = guard+ .jobs+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .clone();+ let answering = window.clone();+ /* Non-blocking: the box runs its own modal loop,+ owned by (and disabling) this window, and the+ answer arrives on the callback. Esc and the box's+ own close button answer "Keep generating". */+ window+ .dialog()+ .message(window::exit_guard_message(&jobs))+ .title(window::EXIT_GUARD_TITLE)+ .kind(MessageDialogKind::Warning)+ .buttons(MessageDialogButtons::OkCancelCustom(+ window::EXIT_GUARD_CONFIRM.to_string(),+ window::EXIT_GUARD_CANCEL.to_string(),+ ))+ .parent(window)+ .show(move |confirmed| {+ answering.state::<ExitGuard>().answered(confirmed);+ if confirmed {+ let _ = answering.destroy();+ }+ });+ }}}+ _ => {}}}).plugin(tauri_plugin_dialog::init())+ /* Size, position and maximized only: decorations are always off and+ visibility is ours (the window is shown at the end of setup). */+ .plugin(+ tauri_plugin_window_state::Builder::new()+ .with_state_flags(+ tauri_plugin_window_state::StateFlags::SIZE+ | tauri_plugin_window_state::StateFlags::POSITION+ | tauri_plugin_window_state::StateFlags::MAXIMIZED,+ )+ .build(),+ ).plugin(tauri_plugin_updater::Builder::new().build()).plugin(tauri_plugin_process::init()).invoke_handler(tauri::generate_handler![@@ -130,6 +217,10 @@ pub fn run() {commands::generation::cancel_slopfab_generation,window::set_generation_active,window::answer_app_close,+ native_shell::system_accent_colors,+ native_shell::show_text_context_menu,+ native_shell::reveal_in_explorer,+ native_shell::pick_file,commands::artifacts::write_generated_video,commands::artifacts::write_scene_last_frame,commands::artifacts::write_timeline_thumbnail,diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 7c5d46c..659d631 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -9,6 +9,7 @@ mod diagnostics;mod export;mod generation;mod media;+mod native_shell;mod project;mod reference_icons;mod rendered;diff --git a/src-tauri/src/native_shell.rs b/src-tauri/src/native_shell.rsnew file mode 100644index 0000000..559d5e9--- /dev/null+++ b/src-tauri/src/native_shell.rs@@ -0,0 +1,459 @@+/* ── The native shell ────────────────────────────────────────────────────────+Everything that makes the Slopus window behave like a Windows 11 app rather+than a web page in a frame: the Mica backdrop, the frameless window's corners,+the WebView2 switches that turn off browser-only behaviour, the Windows accent+colour, the first-launch size, the text-field context menu, and two small+file-system helpers (reveal in Explorer, pick a file).++The page's half lives in src/lib/nativeShell.ts. Every command here has a+counterpart there that no-ops outside Tauri, so the web build and the jsdom+tests never have to care which host they are in.+-------------------------------------------------------------------------- */++use serde::{Deserialize, Serialize};+use tauri::{AppHandle, Emitter as _, Manager as _, Runtime};++/// Event the page listens to for a changed accent (src/lib/nativeShell.ts).+pub(crate) const ACCENT_EVENT: &str = "system-accent-changed";++/// Global the page's boot script reads to learn that Mica is behind it. Set+/// from an initialization script, which runs before any of the page's own+/// scripts — including public/theme-boot.js, which turns it into+/// `<html data-backdrop="mica">` before the first paint.+pub(crate) const BACKDROP_GLOBAL: &str = "__SLOPUS_BACKDROP__";++/* ── Mica ─────────────────────────────────────────────────────────────────── */++/// Windows 11 is build 22000 and up; Mica exists from there on (documented+/// DWMSBT_MAINWINDOW from 22523, the undocumented attribute before that — the+/// window-vibrancy crate Tauri uses covers both). Windows 10 reports major+/// version 10 too, so only the build number tells them apart, and only+/// RtlGetVersion reports it truthfully: GetVersionEx lies to unmanifested apps.+#[cfg(windows)]+pub(crate) fn mica_supported() -> bool {+ use windows::Wdk::System::SystemServices::RtlGetVersion;+ use windows::Win32::System::SystemInformation::OSVERSIONINFOW;+ let mut info = OSVERSIONINFOW {+ dwOSVersionInfoSize: std::mem::size_of::<OSVERSIONINFOW>() as u32,+ ..Default::default()+ };+ // SAFETY: `info` is a correctly sized, writable OSVERSIONINFOW.+ let status = unsafe { RtlGetVersion(&mut info) };+ status.is_ok() && info.dwMajorVersion >= 10 && info.dwBuildNumber >= 22000+}++#[cfg(not(windows))]+pub(crate) fn mica_supported() -> bool {+ false+}++/// The script that tells the page Mica is on. Kept as a function so the name+/// of the global is spelled once.+pub(crate) fn backdrop_script() -> String {+ format!("window.{BACKDROP_GLOBAL} = \"mica\";")+}++/// Whether this window was built with Mica behind it. Recorded once at+/// startup; window.rs reads it so its opaque ground never covers the backdrop.+#[derive(Default)]+pub(crate) struct Backdrop {+ pub(crate) mica: std::sync::atomic::AtomicBool,+}++impl Backdrop {+ pub(crate) fn is_mica(&self) -> bool {+ self.mica.load(std::sync::atomic::Ordering::Acquire)+ }+}++/// A frameless window keeps the Windows 11 rounded corners only if it asks for+/// them; without a caption DWM is free to square it off.+#[cfg(windows)]+pub(crate) fn round_corners<R: Runtime>(window: &tauri::WebviewWindow<R>) {+ use windows::Win32::Graphics::Dwm::{+ DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND,+ };+ let Ok(hwnd) = window.hwnd() else { return };+ let preference = DWMWCP_ROUND;+ // SAFETY: a valid HWND and a pointer to a live 4-byte value. On Windows 10+ // the attribute does not exist and the call simply fails.+ let _ = unsafe {+ DwmSetWindowAttribute(+ hwnd,+ DWMWA_WINDOW_CORNER_PREFERENCE,+ &preference as *const _ as *const core::ffi::c_void,+ std::mem::size_of_val(&preference) as u32,+ )+ };+}++#[cfg(not(windows))]+pub(crate) fn round_corners<R: Runtime>(_window: &tauri::WebviewWindow<R>) {}++/* ── WebView2: browser behaviour off ─────────────────────────────────────── */++/// Turns off what makes the webview act like a browser tab. Tauri and wry+/// already disable the status bar, pinch zoom and swipe navigation (both follow+/// `zoom_hotkeys_enabled` / `back_forward_navigation_gestures`, which default+/// off); what is left is set here on ICoreWebView2Settings directly.+///+/// Debug builds keep the browser accelerators and the default context menu so+/// F12 / "Inspect" still reach DevTools. The capture-phase keydown in+/// src/main.tsx covers the same reload/print/find keys in both builds.+pub(crate) fn disable_browser_behaviour<R: Runtime>(window: &tauri::WebviewWindow<R>) {+ #[cfg(windows)]+ let _ = window.with_webview(|webview| {+ use webview2_com::Microsoft::Web::WebView2::Win32::{+ ICoreWebView2Settings3, ICoreWebView2Settings4,+ };+ use windows::core::Interface as _;+ // SAFETY: plain COM calls on the live controller Tauri hands us, on the+ // thread it hands it to us on.+ unsafe {+ let Ok(core) = webview.controller().CoreWebView2() else { return };+ let Ok(settings) = core.Settings() else { return };+ let release = !cfg!(debug_assertions);+ if release {+ /* F5 / Ctrl+R reload (and lose unsaved edits), Ctrl+P prints,+ Ctrl+F opens the Edge find bar, Ctrl+U views source. */+ if let Ok(settings3) = settings.cast::<ICoreWebView2Settings3>() {+ let _ = settings3.SetAreBrowserAcceleratorKeysEnabled(false);+ }+ /* The page shows its own menus (src/main.tsx asks Rust for a+ native Cut/Copy/Paste menu over text). Edge's — Back, Reload,+ "Search the web", Inspect — never appears. */+ let _ = settings.SetAreDefaultContextMenusEnabled(false);+ }+ if let Ok(settings4) = settings.cast::<ICoreWebView2Settings4>() {+ /* A prompt box is not an address form. general_autofill_enabled+ on the builder covers this too; password autosave has no+ builder switch. */+ let _ = settings4.SetIsGeneralAutofillEnabled(false);+ let _ = settings4.SetIsPasswordAutosaveEnabled(false);+ }+ }+ });+ #[cfg(not(windows))]+ let _ = window;+}++/* ── First launch size ───────────────────────────────────────────────────── */++/// The window's first size when nothing has been remembered yet: 80 % of the+/// primary monitor's WORK AREA (the screen minus the taskbar), in logical+/// pixels, never below the configured minimum. A fixed 1440×920 was 2160×1380+/// physical at 150 % — taller than a 1080p laptop.+pub(crate) fn first_launch_size(+ work_width: u32,+ work_height: u32,+ scale: f64,+ min: (f64, f64),+) -> (f64, f64) {+ let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };+ let width = (f64::from(work_width) / scale * 0.8).round();+ let height = (f64::from(work_height) / scale * 0.8).round();+ (width.max(min.0), height.max(min.1))+}++/// True when tauri-plugin-window-state has no file yet, i.e. this is the first+/// launch (or the user deleted it). The plugin restores size, position and the+/// maximized flag itself whenever the file exists.+pub(crate) fn window_state_missing<R: Runtime>(app: &AppHandle<R>) -> bool {+ app.path()+ .app_config_dir()+ .map(|dir| !dir.join(tauri_plugin_window_state::DEFAULT_FILENAME).exists())+ .unwrap_or(true)+}++/* ── Accent colour ────────────────────────────────────────────────────────── */++/// The Windows accent palette as `#rrggbb`. `accent` is the user's colour;+/// the Light/Dark ramps are the shades Windows derives from it (WinUI uses+/// AccentDark1 as the fill in light theme and AccentLight2 in dark).+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct AccentColors {+ pub(crate) accent: String,+ pub(crate) light1: String,+ pub(crate) light2: String,+ pub(crate) light3: String,+ pub(crate) dark1: String,+ pub(crate) dark2: String,+ pub(crate) dark3: String,+}++pub(crate) fn hex(r: u8, g: u8, b: u8) -> String {+ format!("#{r:02x}{g:02x}{b:02x}")+}++/// Holds the current palette and keeps the WinRT settings object alive: its+/// ColorValuesChanged event stops firing the moment it is dropped.+#[derive(Default)]+pub(crate) struct SystemAccent {+ current: std::sync::Mutex<Option<AccentColors>>,+ #[cfg(windows)]+ settings: std::sync::Mutex<Option<windows::UI::ViewManagement::UISettings>>,+}++#[cfg(windows)]+fn read_accent(+ settings: &windows::UI::ViewManagement::UISettings,+) -> windows::core::Result<AccentColors> {+ use windows::UI::ViewManagement::UIColorType;+ let get = |kind: UIColorType| -> windows::core::Result<String> {+ let color = settings.GetColorValue(kind)?;+ Ok(hex(color.R, color.G, color.B))+ };+ Ok(AccentColors {+ accent: get(UIColorType::Accent)?,+ light1: get(UIColorType::AccentLight1)?,+ light2: get(UIColorType::AccentLight2)?,+ light3: get(UIColorType::AccentLight3)?,+ dark1: get(UIColorType::AccentDark1)?,+ dark2: get(UIColorType::AccentDark2)?,+ dark3: get(UIColorType::AccentDark3)?,+ })+}++/// Reads the accent once and subscribes to changes. A failure anywhere leaves+/// the page on the palette's own blue — tokens.css — which is the fallback.+pub(crate) fn watch_accent<R: Runtime>(app: &AppHandle<R>) {+ #[cfg(windows)]+ {+ use windows::Foundation::TypedEventHandler;+ use windows::UI::ViewManagement::UISettings;+ let Ok(settings) = UISettings::new() else { return };+ let state = app.state::<SystemAccent>();+ if let Ok(colors) = read_accent(&settings) {+ *state.current.lock().unwrap_or_else(|p| p.into_inner()) = Some(colors);+ }+ let handle = app.clone();+ /* Fires on a background thread, often several times for one change+ (once per derived shade). Only a real difference is sent on. */+ let handler = TypedEventHandler::new(move |_, _| {+ let Ok(fresh) = UISettings::new().and_then(|settings| read_accent(&settings)) else {+ return Ok(());+ };+ let state = handle.state::<SystemAccent>();+ let mut current = state.current.lock().unwrap_or_else(|p| p.into_inner());+ if current.as_ref() != Some(&fresh) {+ *current = Some(fresh.clone());+ drop(current);+ let _ = handle.emit(ACCENT_EVENT, fresh);+ }+ Ok(())+ });+ if settings.ColorValuesChanged(&handler).is_ok() {+ *state.settings.lock().unwrap_or_else(|p| p.into_inner()) = Some(settings);+ }+ }+ #[cfg(not(windows))]+ let _ = app;+}++/// The accent as last read, or `None` when the OS does not have one to give+/// (not Windows, or UISettings unavailable). The page asks once at startup+/// and then listens for ACCENT_EVENT, so a change between the two is not lost.+#[tauri::command]+pub(crate) fn system_accent_colors(state: tauri::State<'_, SystemAccent>) -> Option<AccentColors> {+ state.current.lock().unwrap_or_else(|p| p.into_inner()).clone()+}++/* ── Text context menu ───────────────────────────────────────────────────── */++const MENU_CUT: &str = "slopus-text-cut";+const MENU_COPY: &str = "slopus-text-copy";+const MENU_PASTE: &str = "slopus-text-paste";+const MENU_SELECT_ALL: &str = "slopus-text-select-all";++/// What the page knows about the text under the pointer.+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct TextMenuRequest {+ /// An input or textarea the user can type in (Cut and Paste make sense).+ pub(crate) editable: bool,+ /// Something is selected (Cut and Copy have something to act on).+ pub(crate) has_selection: bool,+}++/// Shows a native Cut / Copy / Paste / Select all menu at the pointer in place+/// of Edge's (which offers "Search the web", writing assistance and Inspect).+/// The items do not touch the clipboard themselves: they replay the keyboard+/// shortcut into the focused field, exactly as muda's own predefined edit items+/// do, so undo history, input events and React's onChange all behave as if the+/// user had pressed the keys.+#[tauri::command]+pub(crate) fn show_text_context_menu(+ window: tauri::Window,+ request: TextMenuRequest,+) -> Result<(), String> {+ use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};+ let handle = window.app_handle();+ let item = |id: &str, text: &str, enabled: bool, accelerator: &str| {+ MenuItem::with_id(handle, id, text, enabled, Some(accelerator))+ };+ let build = || -> tauri::Result<Menu<tauri::Wry>> {+ let menu = Menu::new(handle)?;+ if request.editable {+ menu.append(&item(MENU_CUT, "Cut", request.has_selection, "Ctrl+X")?)?;+ }+ menu.append(&item(MENU_COPY, "Copy", request.has_selection, "Ctrl+C")?)?;+ if request.editable {+ menu.append(&item(MENU_PASTE, "Paste", true, "Ctrl+V")?)?;+ }+ menu.append(&PredefinedMenuItem::separator(handle)?)?;+ menu.append(&item(MENU_SELECT_ALL, "Select all", true, "Ctrl+A")?)?;+ Ok(menu)+ };+ let menu = build().map_err(|error| format!("Could not build the text menu: {error}"))?;+ window+ .popup_menu(&menu)+ .map_err(|error| format!("Could not show the text menu: {error}"))+}++/// Routes a click on one of the text menu's items. Returns false for any other+/// menu, so the caller can keep one global handler.+pub(crate) fn handle_menu_event(id: &str) -> bool {+ let key = match id {+ MENU_CUT => b'X',+ MENU_COPY => b'C',+ MENU_PASTE => b'V',+ MENU_SELECT_ALL => b'A',+ _ => return false,+ };+ send_ctrl_shortcut(key);+ true+}++#[cfg(windows)]+fn send_ctrl_shortcut(key: u8) {+ use windows::Win32::UI::Input::KeyboardAndMouse::{+ SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYBD_EVENT_FLAGS, KEYEVENTF_KEYUP,+ VIRTUAL_KEY, VK_CONTROL,+ };+ let stroke = |vk: VIRTUAL_KEY, up: bool| INPUT {+ r#type: INPUT_KEYBOARD,+ Anonymous: INPUT_0 {+ ki: KEYBDINPUT {+ wVk: vk,+ dwFlags: if up { KEYEVENTF_KEYUP } else { KEYBD_EVENT_FLAGS(0) },+ ..Default::default()+ },+ },+ };+ let letter = VIRTUAL_KEY(u16::from(key));+ let inputs = [+ stroke(VK_CONTROL, false),+ stroke(letter, false),+ stroke(letter, true),+ stroke(VK_CONTROL, true),+ ];+ // SAFETY: a stack array of fully initialised keyboard INPUTs.+ unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };+}++#[cfg(not(windows))]+fn send_ctrl_shortcut(_key: u8) {}++/* ── Files ────────────────────────────────────────────────────────────────── */++/// Opens Explorer with `path` selected. Only an absolute path that exists is+/// accepted: the argument is handed to explorer.exe's own command-line parser,+/// and a relative or made-up string has no business reaching it.+#[tauri::command]+pub(crate) fn reveal_in_explorer(path: String) -> Result<(), String> {+ let path = std::path::PathBuf::from(path);+ if !path.is_absolute() || !path.exists() {+ return Err(format!("{} does not exist.", path.display()));+ }+ #[cfg(windows)]+ std::process::Command::new("explorer.exe")+ .arg("/select,")+ .arg(&path)+ .spawn()+ .map_err(|error| format!("Could not open File Explorer: {error}"))?;+ #[cfg(target_os = "macos")]+ std::process::Command::new("open")+ .arg("-R")+ .arg(&path)+ .spawn()+ .map_err(|error| format!("Could not reveal the file: {error}"))?;+ #[cfg(all(unix, not(target_os = "macos")))]+ std::process::Command::new("xdg-open")+ .arg(path.parent().unwrap_or(&path))+ .spawn()+ .map_err(|error| format!("Could not open the folder: {error}"))?;+ Ok(())+}++#[derive(Debug, Deserialize)]+pub(crate) struct FileFilter {+ pub(crate) name: String,+ pub(crate) extensions: Vec<String>,+}++/// The system Open dialog. `Ok(None)` is a cancel, not an error. Mirrors+/// `choose_export_destination` in export.rs, on a blocking thread so the+/// dialog's own message loop never waits on the one the webview needs.+#[tauri::command]+pub(crate) async fn pick_file(+ app: AppHandle,+ title: Option<String>,+ filters: Option<Vec<FileFilter>>,+) -> Result<Option<String>, String> {+ tauri::async_runtime::spawn_blocking(move || {+ use tauri_plugin_dialog::DialogExt;+ let mut dialog = app.dialog().file();+ if let Some(title) = title {+ dialog = dialog.set_title(title);+ }+ for filter in filters.unwrap_or_default() {+ let extensions: Vec<&str> = filter.extensions.iter().map(String::as_str).collect();+ dialog = dialog.add_filter(filter.name, &extensions);+ }+ let Some(selected) = dialog.blocking_pick_file() else {+ return Ok(None);+ };+ let path = selected+ .into_path()+ .map_err(|error| format!("Could not use the selected file: {error}"))?;+ Ok(Some(path.to_string_lossy().into_owned()))+ })+ .await+ .map_err(|error| format!("The file dialog failed: {error}"))?+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn first_launch_is_eighty_percent_of_the_work_area_in_logical_pixels() {+ // 1920×1040 work area (1080p minus the taskbar) at 150 %.+ assert_eq!(first_launch_size(1920, 1040, 1.5, (900.0, 650.0)), (1024.0, 650.0));+ // 2560×1400 at 100 %.+ assert_eq!(first_launch_size(2560, 1400, 1.0, (900.0, 650.0)), (2048.0, 1120.0));+ }++ #[test]+ fn first_launch_never_goes_below_the_minimum_or_divides_by_nothing() {+ assert_eq!(first_launch_size(800, 600, 1.0, (900.0, 650.0)), (900.0, 650.0));+ assert_eq!(first_launch_size(1000, 1000, 0.0, (100.0, 100.0)), (800.0, 800.0));+ }++ #[test]+ fn colours_are_lowercase_hash_hex() {+ assert_eq!(hex(0x00, 0x78, 0xd4), "#0078d4");+ assert_eq!(hex(255, 255, 255), "#ffffff");+ }++ #[test]+ fn only_the_text_menu_ids_are_claimed() {+ assert!(!handle_menu_event("something-else"));+ }++ #[test]+ fn the_backdrop_script_sets_the_global_the_boot_script_reads() {+ assert_eq!(backdrop_script(), "window.__SLOPUS_BACKDROP__ = \"mica\";");+ }+}diff --git a/src-tauri/src/window.rs b/src-tauri/src/window.rsindex 75adf5a..1c0e5de 100644--- a/src-tauri/src/window.rs+++ b/src-tauri/src/window.rs@@ -1,9 +1,14 @@use std::sync::atomic::Ordering;+use tauri::Manager as _;/* ── Exit guard ──────────────────────────────────────────────────────────────The video engine runs inside this process, so closing the window ends ageneration outright — and slopfab writes no file of its own, so an unfinished-run leaves nothing behind. The webview therefore has to be able to answer the-close request before the window goes away.+run leaves nothing behind. The user therefore has to be able to answer the+close request before the window goes away: app.rs puts the question in a native+Windows message box (see `exit_guard_message`), naming the jobs the webview+reported through `set_generation_active`. `answer_app_close` and the+`app-close-requested` event belonged to the old in-page dialog; the command stays+registered so an old frontend build cannot fail on it.The window is held open ONLY while the frontend has said something isgenerating (`set_generation_active`). A webview that never loaded, or one@@ -16,9 +21,22 @@ pub(crate) struct ExitGuard {/// Set by the frontend whenever the number of running or queued generations/// changes. False means "close without asking".pub(crate) generation_active: std::sync::atomic::AtomicBool,- /// True between putting the question to the webview and its answer, so a+ /// True between putting the question on screen and its answer, so a/// second click on the close button does not stack a second dialog.pub(crate) asking: std::sync::atomic::AtomicBool,+ /// What the webview last said is running, so the native message box can+ /// name it. Empty when the webview only sent the flag.+ pub(crate) jobs: std::sync::Mutex<Vec<GuardJob>>,+}++/// One generation as the exit question names it.+#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct GuardJob {+ pub(crate) title: String,+ /// Rendering right now, as opposed to waiting in the queue.+ #[serde(default)]+ pub(crate) running: bool,}#[derive(Debug, PartialEq, Eq)]@@ -53,9 +71,61 @@ impl ExitGuard {}}+/// `jobs` is optional so a caller that only reports the flag keeps working;+/// the question then says "generating" without naming anything.#[tauri::command]-pub(crate) fn set_generation_active(state: tauri::State<'_, ExitGuard>, active: bool) {+pub(crate) fn set_generation_active(+ state: tauri::State<'_, ExitGuard>,+ active: bool,+ jobs: Option<Vec<GuardJob>>,+) {state.generation_active.store(active, Ordering::Release);+ *state.jobs.lock().unwrap_or_else(|p| p.into_inner()) = if active {+ jobs.unwrap_or_default()+ } else {+ Vec::new()+ };+}++pub(crate) const EXIT_GUARD_TITLE: &str = "Close Slopus and stop generating?";+pub(crate) const EXIT_GUARD_CONFIRM: &str = "Stop and close";+pub(crate) const EXIT_GUARD_CANCEL: &str = "Keep generating";++/// The body of the native exit question. Same claims, in the same words, as+/// src/components/ExitGuardDialog.tsx, which it replaces: a message box is+/// what Windows apps show for a yes/no question like this one.+pub(crate) fn exit_guard_message(jobs: &[GuardJob]) -> String {+ let rendering = jobs.iter().filter(|job| job.running).count();+ let queued = jobs.len() - rendering;+ let count = |n: usize| if n == 1 { "1 shot is".to_string() } else { format!("{n} shots are") };+ let mut parts = Vec::new();+ if rendering > 0 {+ parts.push(format!("{} rendering now", count(rendering)));+ }+ if queued > 0 {+ parts.push(format!("{} waiting in the queue", count(queued)));+ }+ let mut message = if parts.is_empty() {+ "A video is still generating.".to_string()+ } else {+ format!("{}.", parts.join(" and "))+ };+ message.push_str(+ "\n\nThe video engine runs inside Slopus, so closing the window stops it. \+ No video file is written until a shot finishes, and Slopus can't pick an \+ unfinished one back up: it would have to run again from the beginning.",+ );+ if !jobs.is_empty() {+ message.push('\n');+ for job in jobs.iter().take(4) {+ let state = if job.running { "rendering now" } else { "waiting" };+ message.push_str(&format!("\n\u{2022} {} ({state})", job.title));+ }+ if jobs.len() > 4 {+ message.push_str(&format!("\n\u{2022} and {} more", jobs.len() - 4));+ }+ }+ message}#[tauri::command]@@ -85,11 +155,22 @@ pub(crate) fn answer_app_close(* wrong is an explicit choice that opposes the OS, and no value obtainable in* this process fixes that: it would need the preference duplicated into a* second store, which is precisely the drift this comment exists to record.- * theme-boot.js corrects it on the first frame the webview draws either way. */+ * theme-boot.js corrects it on the first frame the webview draws either way.+ *+ * On Windows 11 none of this runs: the window is transparent with Mica behind+ * it (native_shell.rs), and the backdrop takes its tint from the window's+ * theme, which the page keeps in step with the preference via setTheme — so+ * the opposed-choice frame above does not happen there at all. */pub(crate) const GROUND_DARK: tauri::window::Color = tauri::window::Color(0x08, 0x0a, 0x0f, 0xff);pub(crate) const GROUND_LIGHT: tauri::window::Color = tauri::window::Color(0xee, 0xf1, 0xf6, 0xff);pub(crate) fn apply_theme(window: &tauri::WebviewWindow) {+ /* With Mica behind the window there is no ground to paint: an opaque+ colour here would sit on top of the backdrop and hide it. The backdrop+ follows the window's own theme, which the page sets with setTheme. */+ if window.state::<crate::native_shell::Backdrop>().is_mica() {+ return;+ }let ground = if matches!(window.theme(), Ok(tauri::Theme::Light)) {GROUND_LIGHT} else {@@ -99,7 +180,7 @@ pub(crate) fn apply_theme(window: &tauri::WebviewWindow) {}#[cfg(test)]mod tests {- use super::{CloseDecision, ExitGuard};+ use super::{exit_guard_message, CloseDecision, ExitGuard, GuardJob};use std::sync::atomic::Ordering;fn generating() -> ExitGuard {@@ -145,6 +226,35 @@ mod tests {assert_eq!(guard.on_close_requested(), CloseDecision::Close);}+ #[test]+ fn the_question_counts_and_names_what_would_be_lost() {+ let jobs = vec![+ GuardJob { title: "Opening shot".into(), running: true },+ GuardJob { title: "Close-up".into(), running: false },+ GuardJob { title: "Wide".into(), running: false },+ ];+ let message = exit_guard_message(&jobs);+ assert!(message.starts_with("1 shot is rendering now and 2 shots are waiting in the queue."));+ assert!(message.contains("\u{2022} Opening shot (rendering now)"));+ assert!(message.contains("\u{2022} Close-up (waiting)"));+ }++ #[test]+ fn the_question_still_reads_when_only_the_flag_arrived() {+ assert!(exit_guard_message(&[]).starts_with("A video is still generating."));+ }++ #[test]+ fn a_long_queue_is_cut_to_four_and_a_count() {+ let jobs: Vec<GuardJob> = (0..6)+ .map(|index| GuardJob { title: format!("Shot {index}"), running: false })+ .collect();+ let message = exit_guard_message(&jobs);+ assert!(message.contains("Shot 3"));+ assert!(!message.contains("Shot 4"));+ assert!(message.ends_with("\u{2022} and 2 more"));+ }+#[test]fn a_run_that_finishes_first_takes_the_guard_back_out_of_the_way() {let guard = generating();diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 7a3a97b..2250d25 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -13,13 +13,14 @@"windows": [{"create": false,- "title": "Slopus - 0.1.1",- "width": 1440,- "height": 920,+ "title": "Slopus",+ "width": 1280,+ "height": 800,"minWidth": 900,"minHeight": 650,"center": true,- "decorations": true,+ "decorations": false,+ "shadow": true,"resizable": true,"backgroundColor": "#080a0f","dragDropEnabled": false