From 5ac49d3d7bdd7128ff695d83c66431f339e05a13 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:46:38 +0000 Subject: [PATCH 1/6] fix(gui): a release build run from a terminal attaches to its console main.rs sets windows_subsystem = "windows" in release builds so an Explorer launch opens no console, but the app still parses a command line: from a terminal, --help, --version and clap's usage errors went nowhere (exit 0, nothing printed). With arguments (Explorer passes none) main() now calls win::console::attach_parent() before parsing: a one-call safe leaf around AttachConsole(ATTACH_PARENT_PROCESS), inside the existing src/win/ unsafe boundary. No parent console (Explorer) or an existing one (debug builds) leaves things as they were. windows-sys gains the Win32_System_Console feature. Closes #15 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQmV2uiGiqUHSfS6KUH --- CHANGELOG.md | 3 ++ templates/gui/deps.js | 5 ++-- templates/gui/files/src/main.rs | 24 ++++++++++++---- templates/gui/files/src/win/console.rs | 38 ++++++++++++++++++++++++++ templates/gui/files/src/win/mod.rs | 1 + 5 files changed, 64 insertions(+), 7 deletions(-) create mode 100644 templates/gui/files/src/win/console.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c5f334c..2d951a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- A release build of a GUI app run from a terminal prints its `--help`, `--version` and usage + errors: with arguments it attaches to the parent console first (`src/win/console.rs`). + Explorer launches are unchanged. - The review panel and the next-steps box fit narrow terminals: below about 60 columns their right edges used to wrap onto the next line. Title facts that don't fit move into the panel, and the box drops its notes, then its frame, rather than overflow. diff --git a/templates/gui/deps.js b/templates/gui/deps.js index 7ade5f5..89adc96 100644 --- a/templates/gui/deps.js +++ b/templates/gui/deps.js @@ -20,12 +20,13 @@ export default (ctx) => { features: ['wgpu', 'default_fonts', 'x11', 'wayland'], }); } - // src/win/: MessageBoxW for startup failures (dialog.rs) and the wide-string helpers. + // src/win/: MessageBoxW for startup failures (dialog.rs), the wide-string helpers, and + // AttachConsole so a release build run from a terminal can print (console.rs). deps.push({ name: 'windows-sys', version: '0.61', target: 'cfg(windows)', - features: ['Win32_Foundation', 'Win32_UI_WindowsAndMessaging'], + features: ['Win32_Foundation', 'Win32_System_Console', 'Win32_UI_WindowsAndMessaging'], }); // The theme catalog and the config file are TOML, the user theme directory and the config // path come from `dirs`. Declared here as well as by src/gen/deps.js so turning `serde` off in diff --git a/templates/gui/files/src/main.rs b/templates/gui/files/src/main.rs index 2375e1a..c6ecfaa 100644 --- a/templates/gui/files/src/main.rs +++ b/templates/gui/files/src/main.rs @@ -17,15 +17,28 @@ //! Deliberately thin: it parses the command line, loads the saved //! preferences and hands off. Everything else belongs to the library. //! -//! ## Failures are reported in a dialog on Windows +//! ## A release build borrows the terminal it was run from //! -//! A release build has no console, so anything written to stderr goes -//! nowhere and a startup failure would look like the program refusing to -//! open. See [`report`]. +//! A release build has no console of its own. Run with arguments from a +//! terminal, it attaches to that terminal's console before parsing, so +//! `--help`, `--version` and usage errors print there; launched from +//! Explorer there is nothing to attach to and nothing changes. +//! +//! ## Failures are also reported in a dialog on Windows +//! +//! Launched from Explorer, anything written to stderr goes nowhere and a +//! startup failure would look like the program refusing to open. See +//! [`report`]. use @@appCrateSnake@@::cli::Cli; fn main() -> std::process::ExitCode { + // Arguments mean a terminal (Explorer passes none): attach to its + // console before anything is printed, or it would print to nowhere. + #[cfg(windows)] + if std::env::args_os().len() > 1 { + @@appCrateSnake@@::win::console::attach_parent(); + } // @if clap let cli = { use clap::Parser as _; @@ -93,7 +106,8 @@ fn run(cli: Cli) -> anyhow::Result<()> { /// Reports a startup failure somewhere the user will actually see it. /// /// Written to stderr for a terminal, and on Windows also shown in a -/// message box, because a release build has no console at all. +/// message box, because a release build launched from Explorer has no +/// console at all. fn report(message: &str) { eprintln!("{message}"); #[cfg(windows)] diff --git a/templates/gui/files/src/win/console.rs b/templates/gui/files/src/win/console.rs new file mode 100644 index 0000000..20c0a28 --- /dev/null +++ b/templates/gui/files/src/win/console.rs @@ -0,0 +1,38 @@ +// ============================================================================ +// Module: @@module@@ +// Description: Borrowing the launching terminal's console, so a release build +// run from a shell can print its help, version and errors. +// +// Dependencies: windows-sys (AttachConsole) +// ============================================================================ + +//! The parent process's console. +//! +//! A release build uses the Windows subsystem (see `main.rs`), so it starts +//! with no console: launched from Explorer that is what you want, but run +//! from a terminal, clap's `--help`, `--version` and usage errors would be +//! written to nowhere. Attaching to the parent's console fixes that, and +//! does nothing when there is no parent console to attach to. +//! +//! One quirk of the platform remains: the shell does not wait for a +//! Windows-subsystem program, so its prompt can come back before the +//! output. Press Enter for a fresh prompt. + +use windows_sys::Win32::System::Console as sys; + +/// Attaches to the console of the process that launched this one, if any. +/// +/// Best effort: launched from Explorer there is no parent console, and a +/// debug build already has its own; both are fine and leave things as +/// they were. +pub fn attach_parent() { + // Failure only means there was nothing to attach to. + let _attached = attach_console(sys::ATTACH_PARENT_PROCESS); +} + +/// Calls `AttachConsole`; true when this process now has a console. +fn attach_console(process: u32) -> bool { + // SAFETY: AttachConsole takes a process id by value and reads or writes + // no memory of ours; failure is reported only through its return value. + unsafe { sys::AttachConsole(process) != 0 } +} diff --git a/templates/gui/files/src/win/mod.rs b/templates/gui/files/src/win/mod.rs index 9ae251d..109dc48 100644 --- a/templates/gui/files/src/win/mod.rs +++ b/templates/gui/files/src/win/mod.rs @@ -28,6 +28,7 @@ //! `src/win/`, in test code, or two of them in one function. // @end +pub mod console; pub mod dialog; // @if singleInstance pub mod single_instance; From 1a56b308858174102a52563ce86d38a7f8f42025 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:50:52 +0000 Subject: [PATCH 2/6] feat(gui): --without demo starts from one empty page Every desktop project started with demo content the first real commit had to remove: six CARDS on an Overview page, Palette and About pages, their glyphs, selected_card, a Ctrl+1..3 shortcut list and tests pinned to three pages and three cards. Removing it by hand touched four files and failed the dead-code lints until all of it was gone. features.demo (default on, so the showcase stays for first-timers) turns it off: Page has a single Home variant drawn by home(), with a heading, a pointer to the docs and an Open settings button. Pages are now additive in both modes: Ctrl+1..9 come from a PAGE_KEYS table zipped with Page::ALL (the command palette already followed it), and the shortcut test checks SHORTCUTS against Page::ALL.len() rather than a literal 3. docs/ARCHITECTURE.md's 'Adding a page' says what's left to do by hand. Answers gains features.demo (CONTRACTS.md updated). Closes #18 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQmV2uiGiqUHSfS6KUH --- CHANGELOG.md | 4 ++ docs/CONTRACTS.md | 2 +- docs/PLAN.md | 2 +- src/context.ts | 2 +- src/presets.ts | 2 +- src/types.ts | 2 +- src/ui/labels.ts | 1 + templates/gui/files/docs/ARCHITECTURE.md | 18 +++++- templates/gui/files/src/gui/app/mod.rs | 33 +++++++++++ templates/gui/files/src/gui/ui/mod.rs | 75 ++++++++++++++++++++++-- test/e2e.test.ts | 20 +++++++ 11 files changed, 148 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d951a5..7c2832b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `--without demo`: a GUI project starts from one empty page wired through the same page, shortcut + and command-palette machinery, instead of the overview cards, palette and about pages. Pages are + now additive: `Ctrl+1…9` and the palette follow `Page::ALL`, and `docs/ARCHITECTURE.md` explains + adding one. - `--with subcommands`: a `cli` built on a clap `Subcommand` enum (no wildcard dispatch) with matching integration tests, instead of the greeting demo. - `--bin `: an executable named differently from its crate. Writes `[[bin]]` and follows diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index f473f62..47bfd29 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -42,7 +42,7 @@ test/*.test.ts node --test serde: bool, async: 'none'|'tokio', http: 'none'|'ureq'|'reqwest', sqlite: bool, clap: bool }, features: { themes, brand, motion, icons, config, winres, tray, singleInstance, - commandPalette, screenshotExample, subcommands }, // all bool; subcommands: cli + clap only + commandPalette, screenshotExample, demo, subcommands }, // all bool; subcommands: cli + clap only tooling: { ci, release, cargoDeny, dependabot, toolchainPin, agentDocs, headerCheck, unsafeCheck, changelogGen, issueTemplates, codeowners, securityMd }, // all bool post: { git: bool, cargoCheck: bool, open: 'none'|'code'|'cursor' }, diff --git a/docs/PLAN.md b/docs/PLAN.md index 8f8569e..ac667dc 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -169,7 +169,7 @@ debug = "line-tables-only" | kind | `cli` / `gui` ★ / `tui` / `lib` / `workspace` | | gui stack | `eframe` ★ (rustaman: eframe + wgpu) / `winit-glow` (strobe) | | crates | errors: anyhow ★ (+ thiserror ★ for lib/workspace); logging: `log` ★gui / `env_logger` ★cli / `tracing`; serde+toml ★; async: none ★ / tokio; http: none ★ / ureq / reqwest; sqlite: off ★ / rusqlite bundled; clap ★ (everything but lib) | -| features (gui) | themes ★, brand ★, motion ★, icons ★, config ★, winres ★ (icon+manifest+version), tray, singleInstance, commandPalette, screenshotExample | +| features (gui) | themes ★, brand ★, motion ★, icons ★, config ★, winres ★ (icon+manifest+version), tray, singleInstance, commandPalette, screenshotExample, demo ★ (off: one empty page instead of the overview / palette / about showcase) | | features (cli) | subcommands (clap `Subcommand` enum, `tool …`, replaces the greeting demo; needs clap) | | tooling | ci ★, release ★, cargoDeny ★, dependabot ★, toolchainPin ★, agentDocs ★ (AGENTS.md + CLAUDE.md), headerCheck ★, unsafeCheck ★ (gui), changelogGen ★, issueTemplates ★, codeowners ★, securityMd ★ | | theme | accent ★`#00e5ff` | diff --git a/src/context.ts b/src/context.ts index d39e45f..9d1bad4 100644 --- a/src/context.ts +++ b/src/context.ts @@ -39,7 +39,7 @@ const LICENSE_FLAG = { /** App features only a desktop GUI generates (kind `gui`, or the `workspace` app crate). */ export const GUI_ONLY_FEATURES = ['themes', 'brand', 'motion', 'icons', 'winres', 'tray', 'singleInstance', - 'commandPalette', 'screenshotExample'] as const satisfies readonly (keyof Answers['features'])[]; + 'commandPalette', 'screenshotExample', 'demo'] as const satisfies readonly (keyof Answers['features'])[]; /** * The answers as they apply to this kind of project: options the kind never generates read diff --git a/src/presets.ts b/src/presets.ts index 1f52675..10fc3ae 100644 --- a/src/presets.ts +++ b/src/presets.ts @@ -17,7 +17,7 @@ export const DEFAULTS: Answers = Object.freeze({ kind: 'gui', guiStack: 'eframe', crates: { errors: 'anyhow', thiserror: false, logging: 'log', serde: true, async: 'none', http: 'none', sqlite: false, clap: true }, - features: { themes: true, brand: true, motion: true, icons: true, config: true, winres: true, tray: false, singleInstance: false, commandPalette: false, screenshotExample: false, subcommands: false }, + features: { themes: true, brand: true, motion: true, icons: true, config: true, winres: true, tray: false, singleInstance: false, commandPalette: false, screenshotExample: false, demo: true, subcommands: false }, tooling: { ci: true, release: true, cargoDeny: true, dependabot: true, toolchainPin: true, agentDocs: true, headerCheck: true, unsafeCheck: true, changelogGen: true, issueTemplates: true, codeowners: true, securityMd: true }, // fetch (seconds) by default; a full check of a GUI project compiles eframe/wgpu (minutes). post: { git: true, fetch: true, cargoCheck: false, open: 'none' }, diff --git a/src/types.ts b/src/types.ts index 048a3b4..b239f1b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -23,7 +23,7 @@ export interface Answers { features: { themes: boolean; brand: boolean; motion: boolean; icons: boolean; config: boolean; winres: boolean; tray: boolean; singleInstance: boolean; commandPalette: boolean; - screenshotExample: boolean; subcommands: boolean; + screenshotExample: boolean; demo: boolean; subcommands: boolean; }; tooling: { ci: boolean; release: boolean; cargoDeny: boolean; dependabot: boolean; diff --git a/src/ui/labels.ts b/src/ui/labels.ts index b406467..93a9a6b 100644 --- a/src/ui/labels.ts +++ b/src/ui/labels.ts @@ -20,6 +20,7 @@ export const FEATURES: Record = { commandPalette: { label: 'Command palette', hint: 'Ctrl+K fuzzy search over every action', group: 'behaviour' }, winres: { label: 'Windows resources', hint: 'exe icon, manifest, version info', group: 'packaging' }, screenshotExample: { label: 'Screenshot example', hint: 'renders the UI headlessly to PNG', group: 'packaging' }, + demo: { label: 'Demo pages', hint: 'overview cards, palette and about pages; off = one empty page', group: 'content' }, subcommands: { label: 'Subcommands', hint: 'clap subcommands instead of the greeting demo', group: 'cli' }, }; diff --git a/templates/gui/files/docs/ARCHITECTURE.md b/templates/gui/files/docs/ARCHITECTURE.md index a77374a..4c20bac 100644 --- a/templates/gui/files/docs/ARCHITECTURE.md +++ b/templates/gui/files/docs/ARCHITECTURE.md @@ -77,6 +77,18 @@ the module needs `unsafe` to use it. ## Adding a page -1. Add a variant to `Page` in `gui/app/mod.rs` (label, key, glyph). -2. Draw it in `gui/ui/mod.rs`'s `draw` match. -3. Bump the `Ctrl+1…N` shortcut and `SHORTCUTS`; the tests will remind you. +Pages are additive: one variant, one function, and the rest follows. + +1. Add a variant to `Page` in `gui/app/mod.rs`, to `Page::ALL` in sidebar order, and to + its `label`, `key` and `glyph` matches. The key is what the config saves, so never + rename one once shipped. +2. Write a `fn my_page(app: &App, ui: &mut Ui, actions: &mut Vec)` in + `gui/ui/mod.rs` and call it from the `match app.page` in `draw`. Draw only; anything + that changes state is pushed as an `Action` and carried out by `App::apply`. +3. That's all the wiring. The sidebar lists `Page::ALL`, `Ctrl+1…9` open pages in that + order, and the headless test draws every page. + + The command palette gets a "Go to" entry too. + + Update the `Ctrl+1…N` line in `SHORTCUTS`: `every_page_has_a_numbered_shortcut` fails + until you do. diff --git a/templates/gui/files/src/gui/app/mod.rs b/templates/gui/files/src/gui/app/mod.rs index 14ee18b..448637b 100644 --- a/templates/gui/files/src/gui/app/mod.rs +++ b/templates/gui/files/src/gui/app/mod.rs @@ -28,6 +28,7 @@ use crate::theme::Palette; /// A page of the app, in sidebar order. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)] pub enum Page { + // @if demo /// The landing page: a grid of cards. #[default] Overview, @@ -35,19 +36,33 @@ pub enum Page { Palette, /// The mark, the version and the shortcuts. About, + // @else + /// The one page the app starts with. Rename it, and add pages beside + /// it (see "Adding a page" in docs/ARCHITECTURE.md). + #[default] + Home, + // @end } impl Page { /// Every page, in sidebar order. + // @if demo pub const ALL: [Self; 3] = [Self::Overview, Self::Palette, Self::About]; + // @else + pub const ALL: [Self; 1] = [Self::Home]; + // @end /// The name the page is shown under. #[must_use] pub fn label(self) -> &'static str { match self { + // @if demo Self::Overview => "Overview", Self::Palette => "Palette", Self::About => "About", + // @else + Self::Home => "Home", + // @end } } @@ -55,9 +70,13 @@ impl Page { #[must_use] pub fn key(self) -> &'static str { match self { + // @if demo Self::Overview => "overview", Self::Palette => "palette", Self::About => "about", + // @else + Self::Home => "home", + // @end } } @@ -71,9 +90,13 @@ impl Page { #[must_use] pub fn glyph(self) -> ui::Glyph { match self { + // @if demo Self::Overview => glyph::OVERVIEW, Self::Palette => glyph::PALETTE, Self::About => glyph::ABOUT, + // @else + Self::Home => glyph::HOME, + // @end } } } @@ -106,6 +129,7 @@ pub enum Action { /// Close the window and quit. Quit, } +// @if demo /// One card on the overview page. #[derive(Clone, Copy, Debug)] @@ -164,6 +188,7 @@ pub const CARDS: &[Card] = &[ progress: 0.40, }, ]; +// @end /// The application state. pub struct App { @@ -173,8 +198,10 @@ pub struct App { pub sidebar_collapsed: bool, /// Whether the settings card is open. pub settings_open: bool, + // @if demo /// The selected overview card, by index into [`CARDS`]. pub selected_card: Option, + // @end /// The palette everything is drawn in. pub theme: Palette, // @if themes @@ -222,7 +249,9 @@ impl App { .unwrap_or_default(), sidebar_collapsed: config.sidebar_collapsed.unwrap_or(false), settings_open: false, + // @if demo selected_card: None, + // @end theme, // @if themes catalog, @@ -255,7 +284,9 @@ impl App { page: Page::default(), sidebar_collapsed: false, settings_open: false, + // @if demo selected_card: None, + // @end theme, // @if themes catalog, @@ -430,6 +461,7 @@ mod tests { app.apply(&ctx, Action::ToggleSidebar); assert_eq!(app.sidebar_collapsed, before); } + // @if demo #[test] fn every_card_has_something_to_say() { @@ -439,6 +471,7 @@ mod tests { assert!((0.0..=1.0).contains(&card.progress), "{}", card.title); } } + // @end // @if themes #[test] diff --git a/templates/gui/files/src/gui/ui/mod.rs b/templates/gui/files/src/gui/ui/mod.rs index b4c77ce..fc40cda 100644 --- a/templates/gui/files/src/gui/ui/mod.rs +++ b/templates/gui/files/src/gui/ui/mod.rs @@ -59,12 +59,17 @@ pub mod glyph { // @if icons use crate::icon::Icon; + // @if demo /// The overview page. pub const OVERVIEW: Glyph = Icon::Grid; /// The palette page. pub const PALETTE: Glyph = Icon::Palette; /// The about page. pub const ABOUT: Glyph = Icon::Info; + // @else + /// The home page. + pub const HOME: Glyph = Icon::Grid; + // @end /// Settings. pub const SETTINGS: Glyph = Icon::Settings; /// The sidebar toggle. @@ -73,6 +78,7 @@ pub mod glyph { pub const CLOSE: Glyph = Icon::Close; /// The command palette. pub const COMMAND: Glyph = Icon::Command; + // @if demo /// A card: speed. pub const BOLT: Glyph = Icon::Bolt; /// A card: structure. @@ -85,14 +91,20 @@ pub mod glyph { pub const FOLDER: Glyph = Icon::Folder; /// A card: you. pub const SUN: Glyph = Icon::Sun; + // @end // @else + // @if demo /// The overview page. pub const OVERVIEW: Glyph = 'O'; /// The palette page. pub const PALETTE: Glyph = 'P'; /// The about page. pub const ABOUT: Glyph = 'A'; + // @else + /// The home page. + pub const HOME: Glyph = 'H'; + // @end /// Settings. pub const SETTINGS: Glyph = 'S'; /// The sidebar toggle. @@ -101,6 +113,7 @@ pub mod glyph { pub const CLOSE: Glyph = '×'; /// The command palette. pub const COMMAND: Glyph = '>'; + // @if demo /// A card: speed. pub const BOLT: Glyph = 'F'; /// A card: structure. @@ -114,6 +127,7 @@ pub mod glyph { /// A card: you. pub const SUN: Glyph = 'Y'; // @end + // @end } /// The size a glyph is drawn at in the sidebar and on buttons. @@ -173,9 +187,13 @@ pub fn draw(app: &mut App, ui: &mut Ui) -> Vec { .show(ui, |ui| { enter_page(ui, app.page); match app.page { + // @if demo Page::Overview => overview(app, ui), Page::Palette => palette(app, ui, &mut actions), Page::About => about(app, ui), + // @else + Page::Home => home(app, ui, &mut actions), + // @end } }); }); @@ -202,7 +220,7 @@ fn shortcuts(ui: &Ui, actions: &mut Vec) { if command && input.key_pressed(Key::B) { actions.push(Action::ToggleSidebar); } - for (key, page) in [Key::Num1, Key::Num2, Key::Num3].into_iter().zip(Page::ALL) { + for (key, page) in PAGE_KEYS.into_iter().zip(Page::ALL) { if command && input.key_pressed(key) { actions.push(Action::Go(page)); } @@ -210,12 +228,30 @@ fn shortcuts(ui: &Ui, actions: &mut Vec) { }); } +/// Ctrl+1, Ctrl+2, … open the pages in sidebar order, so a new page gets +/// its shortcut (and its command palette entry) without further wiring. +const PAGE_KEYS: [Key; 9] = [ + Key::Num1, + Key::Num2, + Key::Num3, + Key::Num4, + Key::Num5, + Key::Num6, + Key::Num7, + Key::Num8, + Key::Num9, +]; + /// The shortcuts, as data, so the about page and the handler above cannot /// drift apart without the test below noticing. pub const SHORTCUTS: &[(&str, &str)] = &[ ("Ctrl+,", "Open settings"), ("Ctrl+B", "Collapse or expand the sidebar"), + // @if demo ("Ctrl+1…3", "Switch page"), + // @else + ("Ctrl+1", "Switch page"), + // @end // @if commandPalette ("Ctrl+K", "Open the command palette"), // @end @@ -249,6 +285,7 @@ fn heading(app: &App, ui: &mut Ui, title: &str, subtitle: &str) { widgets::muted(ui, &app.theme, subtitle); ui.add_space(SPACE_LG); } +// @if demo /// The overview page: a grid of cards. fn overview(app: &mut App, ui: &mut Ui) { @@ -410,6 +447,26 @@ fn about(app: &App, ui: &mut Ui) { } }); } +// @else + +/// The home page: the app's one page, and the place to start drawing it. +fn home(app: &App, ui: &mut Ui, actions: &mut Vec) { + let theme = &app.theme; + heading(app, ui, crate::NAME, crate::TAGLINE); + widgets::muted( + ui, + theme, + "This page is yours to fill. Add more beside it: docs/ARCHITECTURE.md shows how.", + ); + ui.add_space(SPACE_MD); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = SPACE_SM; + if widgets::button(ui, theme, "Open settings", widgets::Emphasis::Secondary).clicked() { + actions.push(Action::OpenSettings); + } + }); +} +// @end #[cfg(test)] mod tests { @@ -417,10 +474,18 @@ mod tests { #[test] fn every_page_has_a_numbered_shortcut() { - assert_eq!( - Page::ALL.len(), - 3, - "update the Ctrl+1…3 shortcut and SHORTCUTS" + assert!( + Page::ALL.len() <= PAGE_KEYS.len(), + "more pages than Ctrl+1…9 can reach" + ); + let expected = match Page::ALL.len() { + 1 => "Ctrl+1".to_string(), + count => format!("Ctrl+1…{count}"), + }; + assert!( + SHORTCUTS.iter().any(|(keys, _)| *keys == expected), + "SHORTCUTS should list {expected} for {} pages", + Page::ALL.len() ); } diff --git a/test/e2e.test.ts b/test/e2e.test.ts index d3fecdd..625f538 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -154,3 +154,23 @@ test('--bin names the executable everywhere it is named, and only there (#8)', a assert.ok(!p.some((e: PlanEntry) => 'content' in e && /\[\[bin\]\]/.test(e.content)), `${preset} --bin ${bin}: no [[bin]] needed`); } }); + +test('--without demo starts the GUI from one empty page (#18)', async () => { + const text = (entries: PlanEntry[], dest: string) => { + const e = entries.find((x: PlanEntry) => x.dest === dest); + return e && 'content' in e ? e.content : ''; + }; + const shell = await buildPlan(buildContext(resolveAnswers('rustaman', { name: 'shell', features: { demo: false, commandPalette: true } }))); + const app = text(shell, 'src/gui/app/mod.rs'); + const ui = text(shell, 'src/gui/ui/mod.rs'); + assert.match(app, /pub const ALL: \[Self; 1\] = \[Self::Home\];/, 'one page'); + assert.doesNotMatch(app + ui, /CARDS|selected_card|Overview|fn palette\(|fn about\(/, 'no demo content left'); + assert.match(ui, /Page::Home => home\(app, ui, &mut actions\)/, 'the page is drawn'); + assert.match(ui, /\("Ctrl\+1", "Switch page"\)/, 'shortcut list matches one page'); + assert.match(text(shell, 'docs/ARCHITECTURE.md'), /## Adding a page[\s\S]*command palette gets a "Go to" entry/, 'docs explain adding pages'); + + const demo = await buildPlan(buildContext(resolveAnswers('rustaman', { name: 'demo' }))); + assert.match(text(demo, 'src/gui/app/mod.rs'), /pub const CARDS: &\[Card\]/, 'the showcase stays the default'); + const cli = buildContext(resolveAnswers('cli', { name: 'c', features: { demo: true } })); + assert.ok(!cli.flags.has('demo'), 'demo is a desktop-only feature'); +}); From ca86f1d5f89dd43f593f6a55e2609a80d1fb915f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:54:51 +0000 Subject: [PATCH 3/6] feat(gui): --base picks the shipped theme the signature accent sits on The signature theme always used Midnight's blue-black surfaces; a media or editing app wanting neutral chrome had to hand-edit signature_spec and re-check the readability tests. --base (or 'Signature theme surfaces' under Customize > App) accepts any theme in the shipped themes.toml, read by the new src/gen/themes.ts so the catalog the app compiles in is the single source. Its mode, surfaces, text, status colours and rainbow span fill signature_spec through base* tokens, and its own accent becomes FALLBACK_ACCENT. On a light base the accent retries go darker instead of lighter (base_light flag). The default, midnight, reproduces the previous literals exactly; only comments change. Two things a light base exposed, now fixed: emergency() took its accent from FALLBACK_ACCENT though its surfaces are always Midnight's (it now uses Midnight's accent), and a gui test asserted the signature theme is dark (it now follows the theme's mode). Checked with the full gate on graphite, daylight (pink and yellow accents, the latter exercising the fallback), parchment without the catalog, void (workspace) and the default. Answers gains themeBase; Ctx gains the base* tokens and base_dark / base_light flags (CONTRACTS.md updated). Closes #19 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQmV2uiGiqUHSfS6KUH --- CHANGELOG.md | 3 ++ README.md | 2 + docs/CONTRACTS.md | 6 ++- docs/PLAN.md | 3 +- src/args.ts | 6 ++- src/context.ts | 20 ++++++++ src/gen/themes.ts | 64 +++++++++++++++++++++++++ src/presets.ts | 1 + src/prompts.ts | 7 ++- src/reproduce.ts | 1 + src/types.ts | 6 ++- templates/gui/files/assets/themes.toml | 10 ++-- templates/gui/files/src/gui/ui/theme.rs | 6 ++- templates/gui/files/src/theme/mod.rs | 51 ++++++++++++-------- test/args.test.ts | 5 ++ test/e2e.test.ts | 22 +++++++++ 16 files changed, 182 insertions(+), 31 deletions(-) create mode 100644 src/gen/themes.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c2832b..59b1cf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `--base `: lay the signature theme's accent on any shipped theme's surfaces, e.g. + `--base graphite` for neutral greys behind media. The default (`midnight`) is unchanged, and the + readability tests check the result in the generated project. - `--without demo`: a GUI project starts from one empty page wired through the same page, shortcut and command-palette machinery, instead of the overview cards, palette and about pages. Pages are now additive: `Ctrl+1…9` and the palette follow `Page::ALL`, and `docs/ARCHITECTURE.md` explains diff --git a/README.md b/README.md index 8e4c0c2..fc1aafb 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ create-rust-app [dir] [options] | `--preset

` | `rustaman` `strobe` `cli` `tui` `lib` `minimal`, or `custom` for no preset (the defaults) | | `--kind ` | `cli` `gui` `tui` `lib` `workspace` | | `--gui ` | `eframe` (wgpu) or `winit-glow` (winit + glutin + egui_glow) | +| `--base ` | Surfaces the signature theme lays your accent on: any shipped theme id, e.g. `graphite` for neutral greys (default `midnight`) | | `--edition ` | `2024` or `2021` | | `--msrv ` | `rust-version` in Cargo.toml (default `1.98`) | | `--toolchain ` | Exact channel pinned in `rust-toolchain.toml` and CI (default `1.99.1`) | @@ -99,6 +100,7 @@ create-rust-app [dir] [options] | `--github ` | GitHub handle for CODEOWNERS and repository links | | `--accent <#hex>` | Accent colour for GUI themes (default `#00e5ff`) | | `--with a,b` | Turn on features / tooling, e.g. `--with tray,commandPalette`, or `--with subcommands` for a CLI built on a clap `Subcommand` enum | +| `--without demo` | Start a desktop app from one empty page instead of the overview / palette / about showcase | | `--without a,b` | Turn them off, e.g. `--without release,dependabot` | | `--set ` | Set any answer directly (repeatable), e.g. `--set tagline="Fast grep"`, `--set crates.async=tokio`. The only way to set `tagline` / `displayName` without prompts. `true`/`false` become booleans | | `-y`, `--yes` | Accept defaults for anything not given; no prompts | diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index 47bfd29..e732181 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -38,6 +38,7 @@ test/*.test.ts node --test edition: '2024' | '2021', msrv: '1.98', toolchain: '1.99.1', accent: '#00e5ff', kind: 'cli' | 'gui' | 'tui' | 'lib' | 'workspace', guiStack: 'eframe' | 'winit-glow', + themeBase: string, // a shipped theme id from templates/gui/files/assets/themes.toml ('' without a GUI) crates: { errors: 'anyhow', thiserror: bool, logging: 'log'|'env_logger'|'tracing', serde: bool, async: 'none'|'tokio', http: 'none'|'ureq'|'reqwest', sqlite: bool, clap: bool }, @@ -66,13 +67,16 @@ It then adds: `crate` (snake), `Name` (Pascal), `NAME` (SCREAMING), - every true boolean in crates/features/tooling by its key: `thiserror`, `serde`, `sqlite`, `clap`, `themes`, `tray`, `ci`, `release`, … - `has_gui` (kind gui, or workspace — the workspace app crate is a GUI), `has_bin` (kind ≠ lib), + `base_dark` / `base_light` (the `--base` theme's mode; GUI kinds only), `custom_bin` (`--bin` names the executable differently from its crate; a `[[bin]]` table is written), `workspace` (kind workspace), `single` (not workspace) ### Tokens (`@@x@@`) `name bin crate Name NAME appCrate appCrateSnake displayName tagline author github email year license edition msrv -toolchain accent module`. `@@module@@` is computed per file by `moduleFor(dest, ctx)`. `@@bin@@` is the +toolchain accent module`, plus `baseName baseMode baseApp basePanel baseRaised baseHover baseBorder +baseText baseTextMuted baseDanger baseWarning baseSuccess baseSpan baseAccentRgb`: the `--base` theme's +fields as read from `themes.toml` by `src/gen/themes.ts`, filled into the signature theme. `@@module@@` is computed per file by `moduleFor(dest, ctx)`. `@@bin@@` is the command users type (`--bin`, else the project name); where the executable's file name matters (release packaging) templates use `@@bin@@` under `custom_bin` and `@@appCrate@@` otherwise. Unknown tokens throw (so a typo fails tests loudly). diff --git a/docs/PLAN.md b/docs/PLAN.md index ac667dc..5b02fb1 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -168,6 +168,7 @@ debug = "line-tables-only" | identity | name (kebab `^[a-z][a-z0-9-]*$`), displayName, tagline, author ★`Lawrence Norton`, github ★`lnorton89`, email, license ★`MIT` / `MIT+CommonsClause` / `Apache-2.0` / `MIT OR Apache-2.0`, edition ★`2024`/`2021`, msrv ★`1.98`, toolchain ★`1.99.1` | | kind | `cli` / `gui` ★ / `tui` / `lib` / `workspace` | | gui stack | `eframe` ★ (rustaman: eframe + wgpu) / `winit-glow` (strobe) | +| theme base | any shipped theme id: `midnight` ★ / `graphite` / … (the surfaces the signature theme lays the accent on) | | crates | errors: anyhow ★ (+ thiserror ★ for lib/workspace); logging: `log` ★gui / `env_logger` ★cli / `tracing`; serde+toml ★; async: none ★ / tokio; http: none ★ / ureq / reqwest; sqlite: off ★ / rusqlite bundled; clap ★ (everything but lib) | | features (gui) | themes ★, brand ★, motion ★, icons ★, config ★, winres ★ (icon+manifest+version), tray, singleInstance, commandPalette, screenshotExample, demo ★ (off: one empty page instead of the overview / palette / about showcase) | | features (cli) | subcommands (clap `Subcommand` enum, `tool …`, replaces the greeting demo; needs clap) | @@ -188,7 +189,7 @@ all tooling), `tui` (ratatui + crossterm), `lib` (thiserror, no bin, docs.rs met - Runtime deps: `@clack/core` (prompt state machines and key handling) and `picocolors`. Everything else is hand-rolled: arg parsing with `node:util` `parseArgs`, gradients in `src/ui/rainbow.ts`, the banner in `src/ui/banner.ts`, rendering in `src/ui/{rail,choose,motion}.ts`. -- Flags: `create-rust-app [dir] --name --bin --preset

--kind --gui --edition --msrv +- Flags: `create-rust-app [dir] --name --bin --preset

--kind --gui --base --edition --msrv --toolchain --license --author --github --accent --with a,b --without a,b --set key.path=value --yes/-y --no-git --no-fetch --cargo-check --no-cargo-check --open --dry-run --json --no-color --quiet --force --help --version`. Non-TTY implies `--yes`. diff --git a/src/args.ts b/src/args.ts index 45c57ad..81e907a 100644 --- a/src/args.ts +++ b/src/args.ts @@ -3,10 +3,11 @@ import { existsSync } from 'node:fs'; import { DEFAULTS, PRESETS } from './presets.ts'; import { validateBin, validateName } from './context.ts'; import type { PartialAnswers } from './types.ts'; +import { shippedThemes } from './gen/themes.ts'; /** @type {Record} */ const OPTIONS: NonNullable = {}; -for (const name of ['name', 'bin', 'preset', 'kind', 'gui', 'edition', 'msrv', 'toolchain', 'license', 'author', 'github', 'accent', 'open']) { +for (const name of ['name', 'bin', 'preset', 'kind', 'gui', 'base', 'edition', 'msrv', 'toolchain', 'license', 'author', 'github', 'accent', 'open']) { OPTIONS[name] = { type: 'string' }; } for (const name of ['with', 'without', 'set']) OPTIONS[name] = { type: 'string', multiple: true }; @@ -44,6 +45,7 @@ Object.assign(SHORT_NAMES, { const CHOICES: Record = { preset: [...Object.keys(PRESETS), 'custom'], kind: ['cli', 'gui', 'tui', 'lib', 'workspace'], guiStack: ['eframe', 'winit-glow'], + themeBase: shippedThemes().map((theme) => theme.id), license: ['MIT', 'MIT+CommonsClause', 'Apache-2.0', 'MIT OR Apache-2.0'], edition: ['2024', '2021'], 'crates.errors': ['anyhow'], 'crates.logging': ['log', 'env_logger', 'tracing'], 'crates.async': ['none', 'tokio'], @@ -146,6 +148,7 @@ export function parseArgv(argv: string[]) { else if (name === 'no-fetch') setAnswer(overrides, 'post.fetch', false); else if (name === 'open') setAnswer(overrides, 'post.open', String(value)); else if (name === 'gui') setAnswer(overrides, 'guiStack', String(value)); + else if (name === 'base') setAnswer(overrides, 'themeBase', String(value)); else if (Object.hasOwn(DEFAULTS, name)) setAnswer(overrides, name, String(value)); } return { dir: parsed.positionals[0], flags, overrides: overrides as PartialAnswers }; @@ -195,6 +198,7 @@ export async function renderHelp(caps: unknown) { ' --preset ' + Object.keys(PRESETS).join(' | ') + ' | custom', ' --kind cli | gui | tui | lib | workspace', ' --gui eframe | winit-glow', + ' --base Surfaces for the signature theme: ' + shippedThemes().map((theme) => theme.id).join(' | '), ' --author Author name --github GitHub owner', ' --license MIT | MIT+CommonsClause | Apache-2.0 | "MIT OR Apache-2.0"', ' --edition 2024 | 2021 --msrv Minimum Rust version', diff --git a/src/context.ts b/src/context.ts index 9d1bad4..7ed6051 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,4 +1,5 @@ import type { Answers, Ctx, TokenKey } from './types.ts'; +import { DEFAULT_BASE, shippedTheme } from './gen/themes.ts'; /** Answers → Ctx (see docs/CONTRACTS.md). */ export const NAME_RE = /^[a-z][a-z0-9-]*$/; @@ -52,6 +53,7 @@ export function effectiveAnswers(a: Answers): Answers { if (!hasGui) { for (const f of GUI_ONLY_FEATURES) out.features[f] = false; out.tooling.unsafeCheck = false; + out.themeBase = ''; } // The GUI kinds always ship a config file; the CLI only when serde is on to read it. A library // leaves config to the app embedding it, and the TUI template has none. @@ -72,6 +74,8 @@ export function buildContext(raw: Answers): Ctx { if (err) throw new Error(`invalid project name "${a.name}": ${err}`); const binErr = a.bin ? validateBin(a.bin) : null; if (binErr) throw new Error(`invalid binary name "${a.bin}": ${binErr}`); + const base = shippedTheme(a.themeBase || DEFAULT_BASE); + if (!base) throw new Error(`unknown theme base "${a.themeBase}"`); const workspace = a.kind === 'workspace'; const hasGui = a.kind === 'gui' || workspace; @@ -86,6 +90,7 @@ export function buildContext(raw: Answers): Ctx { } if (a.kind !== 'lib') flags.add('has_bin'); if (a.bin) flags.add('custom_bin'); + if (hasGui) flags.add(`base_${base.mode}`); const lf = LICENSE_FLAG[/** @type {keyof typeof LICENSE_FLAG} */ (a.license as keyof typeof LICENSE_FLAG)]; if (!lf) throw new Error(`unknown license ${a.license}`); flags.add(lf); @@ -122,6 +127,21 @@ export function buildContext(raw: Answers): Ctx { msrv: a.msrv, toolchain: a.toolchain, accent: a.accent, + // The --base theme's stated colours, for the signature theme (theme/mod.rs). + baseName: base.name, + baseMode: base.mode === 'light' ? 'Light' : 'Dark', + baseApp: base.app, + basePanel: base.panel, + baseRaised: base.raised, + baseHover: base.hover, + baseBorder: base.border, + baseText: base.text, + baseTextMuted: base.text_muted, + baseDanger: base.danger, + baseWarning: base.warning, + baseSuccess: base.success, + baseSpan: Number.isInteger(base.rainbow_span) ? `${base.rainbow_span}.0` : String(base.rainbow_span), + baseAccentRgb: [1, 3, 5].map((i) => `0x${base.accent.slice(i, i + 2).toLowerCase()}`).join(', '), }; return { diff --git a/src/gen/themes.ts b/src/gen/themes.ts new file mode 100644 index 0000000..9000250 --- /dev/null +++ b/src/gen/themes.ts @@ -0,0 +1,64 @@ +/** + * The built-in theme catalog (templates/gui/files/assets/themes.toml), read by the generator so + * `--base` can lay the signature theme's accent on any shipped theme's surfaces. The file the + * generated app compiles in is the single source: a theme added there is a valid `--base` at once. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { TEMPLATES } from '../engine/plan.ts'; + +/** One `[[theme]]` from the catalog: the eleven stated colours plus identity and band. */ +export interface ShippedTheme { + id: string; name: string; mode: 'dark' | 'light'; + app: string; panel: string; raised: string; hover: string; border: string; + accent: string; text: string; text_muted: string; + danger: string; warning: string; success: string; + rainbow_span: number; +} + +/** The base the signature theme uses unless `--base` says otherwise. */ +export const DEFAULT_BASE = 'midnight'; + +const COLOURS = ['app', 'panel', 'raised', 'hover', 'border', 'accent', 'text', 'text_muted', 'danger', 'warning', 'success'] as const; + +let cache: ShippedTheme[] | undefined; + +/** Every shipped theme, in catalog order. Throws if the catalog is malformed (a template bug). */ +export function shippedThemes(): ShippedTheme[] { + if (cache) return cache; + const text = readFileSync(join(TEMPLATES, 'gui', 'files', 'assets', 'themes.toml'), 'utf8'); + const blocks = text.split(/^\[\[theme\]\]\s*$/m).slice(1); + cache = blocks.map((block, index) => { + const fields: Record = {}; + for (const line of block.split('\n')) { + const m = /^([a-z_]+)\s*=\s*(?:"([^"]*)"|([\d.]+))\s*$/.exec(line.trim()); + if (m?.[1]) fields[m[1]] = m[2] ?? m[3] ?? ''; + } + const where = `themes.toml theme #${index + 1}`; + const need = (key: string) => { + const value = fields[key]; + if (value === undefined) throw new Error(`${where}: missing ${key}`); + return value; + }; + const mode = need('mode'); + if (mode !== 'dark' && mode !== 'light') throw new Error(`${where}: mode must be dark or light`); + for (const key of COLOURS) { + if (!/^#[\da-f]{6}$/i.test(need(key))) throw new Error(`${where}: ${key} is not a #rrggbb colour`); + } + const span = Number(need('rainbow_span')); + if (!Number.isFinite(span)) throw new Error(`${where}: rainbow_span is not a number`); + return { + id: need('id'), name: need('name'), mode, + app: need('app'), panel: need('panel'), raised: need('raised'), hover: need('hover'), border: need('border'), + accent: need('accent'), text: need('text'), text_muted: need('text_muted'), + danger: need('danger'), warning: need('warning'), success: need('success'), + rainbow_span: span, + }; + }); + return cache; +} + +/** The shipped theme with this id, or undefined. */ +export function shippedTheme(id: string): ShippedTheme | undefined { + return shippedThemes().find((theme) => theme.id === id); +} diff --git a/src/presets.ts b/src/presets.ts index 10fc3ae..bbba020 100644 --- a/src/presets.ts +++ b/src/presets.ts @@ -16,6 +16,7 @@ export const DEFAULTS: Answers = Object.freeze({ accent: '#00e5ff', kind: 'gui', guiStack: 'eframe', + themeBase: 'midnight', crates: { errors: 'anyhow', thiserror: false, logging: 'log', serde: true, async: 'none', http: 'none', sqlite: false, clap: true }, features: { themes: true, brand: true, motion: true, icons: true, config: true, winres: true, tray: false, singleInstance: false, commandPalette: false, screenshotExample: false, demo: true, subcommands: false }, tooling: { ci: true, release: true, cargoDeny: true, dependabot: true, toolchainPin: true, agentDocs: true, headerCheck: true, unsafeCheck: true, changelogGen: true, issueTemplates: true, codeowners: true, securityMd: true }, diff --git a/src/prompts.ts b/src/prompts.ts index f912b49..ea43d46 100644 --- a/src/prompts.ts +++ b/src/prompts.ts @@ -11,6 +11,7 @@ import { isCancel } from '@clack/core'; import { NOTE_FRAME, NOTE_TITLE_FRAME, cancel, note, text } from './ui/rail.ts'; import { glyphs } from './ui/glyphs.ts'; import { PRESETS, resolveAnswers } from './presets.ts'; +import { shippedThemes } from './gen/themes.ts'; import { effectiveAnswers, validateBin, validateName } from './context.ts'; import { dim, hex, bold } from './ui/rainbow.ts'; import { pick, pickMany } from './ui/choose.ts'; @@ -163,7 +164,7 @@ export async function ask(partial: PartialAnswers, caps: Caps, targetCheck: (nam async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => string | null, repick: () => Promise): Promise { const sections: Item[] = ([ { value: 'crates', label: 'Crates', hint: 'logging, async, HTTP, serde, SQLite…' }, - ...(isGui(a) ? [{ value: 'app', label: 'App', hint: 'GUI runtime, themes, tray, palette…' }] : []), + ...(isGui(a) ? [{ value: 'app', label: 'App', hint: 'GUI runtime, theme base, tray, palette…' }] : []), { value: 'tooling', label: 'Tooling', hint: 'CI, releases, guardrails, docs' }, { value: 'rust', label: 'Licence + Rust', hint: `${LICENSES[a.license].label} · edition ${a.edition} · MSRV ${a.msrv} · pin ${a.toolchain}` }, { value: 'after', label: 'After creating', hint: 'git, cargo fetch / check, open editor' }, @@ -200,6 +201,10 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => if (which === 'app') { out.guiStack = got(await pick(caps, { message: 'GUI runtime', initialValue: out.guiStack, options: items(STACKS, ['eframe', 'winit-glow']) })); + out.themeBase = got(await pick(caps, { + message: 'Signature theme surfaces (your accent on these)', initialValue: out.themeBase, + options: shippedThemes().map((t) => ({ value: t.id, label: t.name, hint: `${t.mode} · ${t.app} / ${t.panel}` })), + })); const keys = Object.values(grouped(DESKTOP)).flat(); const picked = got(await pickMany(caps, { message: 'App features', diff --git a/src/reproduce.ts b/src/reproduce.ts index 4d4098b..63fa34f 100644 --- a/src/reproduce.ts +++ b/src/reproduce.ts @@ -41,6 +41,7 @@ export function reproduceCommand(raw: Answers, dir?: string): string { if (a.crates[k] !== base.crates[k]) parts.push('--set', `crates.${k}=${a.crates[k]}`); } if (a.guiStack !== base.guiStack && (a.kind === 'gui' || a.kind === 'workspace')) parts.push('--gui', a.guiStack); + if (a.themeBase !== base.themeBase) parts.push('--base', a.themeBase); for (const k of ['edition', 'msrv', 'toolchain', 'license'] as const) { if (a[k] !== base[k]) parts.push(`--${k}`, quote(a[k])); } diff --git a/src/types.ts b/src/types.ts index b239f1b..48b9ad4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -15,6 +15,8 @@ export interface Answers { accent: string; kind: 'cli' | 'gui' | 'tui' | 'lib' | 'workspace'; guiStack: 'eframe' | 'winit-glow'; + /** Shipped theme whose surfaces the signature theme uses (`--base`); '' when there is no GUI. */ + themeBase: string; crates: { errors: 'anyhow'; thiserror: boolean; logging: 'log' | 'env_logger' | 'tracing'; serde: boolean; async: 'none' | 'tokio'; http: 'none' | 'ureq' | 'reqwest'; @@ -40,7 +42,9 @@ export type PartialAnswers = { export type TokenKey = 'name' | 'bin' | 'crate' | 'Name' | 'NAME' | 'appCrate' | 'appCrateSnake' | 'displayName' | 'tagline' | 'author' | 'github' | 'email' | 'year' | 'license' - | 'edition' | 'msrv' | 'toolchain' | 'accent'; + | 'edition' | 'msrv' | 'toolchain' | 'accent' + | 'baseName' | 'baseMode' | 'baseApp' | 'basePanel' | 'baseRaised' | 'baseHover' | 'baseBorder' + | 'baseText' | 'baseTextMuted' | 'baseDanger' | 'baseWarning' | 'baseSuccess' | 'baseSpan' | 'baseAccentRgb'; export interface Ctx extends Answers { crate: string; diff --git a/templates/gui/files/assets/themes.toml b/templates/gui/files/assets/themes.toml index aef4b88..b6f8138 100644 --- a/templates/gui/files/assets/themes.toml +++ b/templates/gui/files/assets/themes.toml @@ -21,14 +21,14 @@ # fails is a failing test; a user theme that fails is reported in Settings # and not loaded. # -# The signature theme (built from the colour the project was scaffolded -# with) is always first and is defined in code. `id` is persisted in the -# config file. Never rename one. +# The signature theme (the colour the project was scaffolded with, on the +# @@baseName@@ surfaces) is always first and is defined in code. `id` is +# persisted in the config file. Never rename one. # --------------------------------------------------------------- dark -# A deep blue-black with a cyan accent: the signature theme's base, with -# the accent it falls back to. +# A deep blue-black with a cyan accent. The signature theme's default base +# (`--base` picks another). [[theme]] id = "midnight" name = "Midnight" diff --git a/templates/gui/files/src/gui/ui/theme.rs b/templates/gui/files/src/gui/ui/theme.rs index 3f958f8..eee0f06 100644 --- a/templates/gui/files/src/gui/ui/theme.rs +++ b/templates/gui/files/src/gui/ui/theme.rs @@ -247,7 +247,11 @@ mod tests { let visuals = visuals(&theme); assert_eq!(visuals.panel_fill, rgb(theme.panel)); assert_eq!(visuals.override_text_color, Some(rgb(theme.text))); - assert!(visuals.dark_mode, "the signature theme is dark"); + assert_eq!( + visuals.dark_mode, + theme.mode == crate::theme::Mode::Dark, + "egui's dark mode follows the theme's" + ); } #[test] diff --git a/templates/gui/files/src/theme/mod.rs b/templates/gui/files/src/theme/mod.rs index e0237cb..42d06ea 100644 --- a/templates/gui/files/src/theme/mod.rs +++ b/templates/gui/files/src/theme/mod.rs @@ -23,8 +23,9 @@ //! //! ## The signature theme //! -//! [`signature`] is a dark theme whose accent is the colour this project -//! was scaffolded with ([`crate::ACCENT`]). An accent that would fail the +//! [`signature`] lays the colour this project was scaffolded with +//! ([`crate::ACCENT`]) on the surfaces of the built-in @@baseName@@ theme +//! (chosen with `--base` at scaffold time). An accent that would fail the //! readability rules is walked through a few lightnesses at the same hue, //! and if none of them reads, the theme keeps its own default — so the app //! cannot open unreadable, whatever colour was picked. @@ -361,32 +362,34 @@ impl Palette { } } -/// The base the signature theme is built on: a deep blue-black. +/// The base the signature theme is built on: the @@baseName@@ theme's +/// surfaces, text and status colours, with `accent` laid on them. fn signature_spec(accent: Rgb) -> ThemeSpec { ThemeSpec { id: "signature".to_string(), name: "Signature".to_string(), - mode: Mode::Dark, - app: "#0a0c11".to_string(), - panel: "#11141c".to_string(), - raised: "#1a1e28".to_string(), - hover: "#242936".to_string(), - border: "#333a4a".to_string(), + mode: Mode::@@baseMode@@, + app: "@@baseApp@@".to_string(), + panel: "@@basePanel@@".to_string(), + raised: "@@baseRaised@@".to_string(), + hover: "@@baseHover@@".to_string(), + border: "@@baseBorder@@".to_string(), accent: accent.to_hex(), - text: "#e9edf5".to_string(), - text_muted: "#98a3b8".to_string(), - danger: "#ff5c7a".to_string(), - warning: "#ffb347".to_string(), - success: "#4ade80".to_string(), - rainbow_span: Some(280.0), + text: "@@baseText@@".to_string(), + text_muted: "@@baseTextMuted@@".to_string(), + danger: "@@baseDanger@@".to_string(), + warning: "@@baseWarning@@".to_string(), + success: "@@baseSuccess@@".to_string(), + rainbow_span: Some(@@baseSpan@@), } } /// The accent the signature theme falls back to when the scaffolded one -/// cannot be made readable on its surfaces. -const FALLBACK_ACCENT: Rgb = Rgb::new(0x4c, 0xc9, 0xf0); +/// cannot be made readable on its surfaces: the @@baseName@@ theme's own. +const FALLBACK_ACCENT: Rgb = Rgb::new(@@baseAccentRgb@@); -/// The signature theme: the dark base with [`crate::ACCENT`] as its accent. +/// The signature theme: the @@baseName@@ base with [`crate::ACCENT`] as its +/// accent. /// /// See the module docs: an accent that fails the rules is tried at a few /// lightnesses of the same hue before the base's own accent is used. @@ -395,7 +398,12 @@ pub fn signature() -> Palette { let seed = Oklch::from_rgb(crate::ACCENT); let candidates = std::iter::once(crate::ACCENT) .chain( + // Lighter tries read on dark surfaces, darker ones on light. + // @if base_light + [0.48, 0.42, 0.36, 0.54] + // @else [0.72, 0.78, 0.84, 0.66] + // @end .into_iter() .map(|lightness| Oklch::new(lightness, seed.c, seed.h).to_rgb()), ) @@ -415,9 +423,12 @@ pub fn signature() -> Palette { last.unwrap_or_else(emergency) } -/// A palette built from literals, for the one path where deriving failed. +/// A palette built from literals (Midnight's, whatever the base), for the +/// one path where deriving failed: the tests above keep it unreachable. fn emergency() -> Palette { - let accent = FALLBACK_ACCENT; + // Midnight's own accent, not FALLBACK_ACCENT: that one belongs to the + // chosen base, and these surfaces are Midnight's whatever the base. + let accent = Rgb::new(0x4c, 0xc9, 0xf0); Palette { id: "signature".to_string(), name: "Signature".to_string(), diff --git a/test/args.test.ts b/test/args.test.ts index b182f98..784ff2b 100644 --- a/test/args.test.ts +++ b/test/args.test.ts @@ -70,3 +70,8 @@ test('parseArgv: --bin takes a command name and refuses bad ones (#8)', () => { assert.throws(() => parseArgv(['--bin', 'nul']), /reserved device name on Windows/); assert.equal(parseArgv(['--bin', 'console']).overrides.bin, 'console', 'only exact device names are refused'); }); + +test('parseArgv: --base takes a shipped theme id (#19)', () => { + assert.equal(parseArgv(['--base', 'graphite']).overrides.themeBase, 'graphite'); + assert.throws(() => parseArgv(['--base', 'nope']), /Invalid themeBase "nope". Choose: midnight, graphite/); +}); diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 625f538..e47980d 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -174,3 +174,25 @@ test('--without demo starts the GUI from one empty page (#18)', async () => { const cli = buildContext(resolveAnswers('cli', { name: 'c', features: { demo: true } })); assert.ok(!cli.flags.has('demo'), 'demo is a desktop-only feature'); }); + +test('--base lays the signature theme on a shipped theme\'s surfaces (#19)', async () => { + const { shippedThemes } = await import('../src/gen/themes.ts'); + const themes = shippedThemes(); + assert.ok(themes.length >= 2 && themes.some((t) => t.id === 'midnight'), 'the catalog parses'); + const theme = (base: string) => buildPlan(buildContext(resolveAnswers('rustaman', { name: 'b', themeBase: base }))) + .then((plan) => plan.find((e: PlanEntry) => e.dest === 'src/theme/mod.rs')) + .then((e) => (e && 'content' in e ? e.content : '')); + const graphite = themes.find((t) => t.id === 'graphite'); + assert.ok(graphite, 'graphite ships'); + const src = await theme('graphite'); + assert.match(src, new RegExp(`app: "${graphite.app}"\\.to_string\\(\\)`), 'surfaces come from the base'); + assert.match(src, /mode: Mode::Dark,/); + assert.match(src, /const FALLBACK_ACCENT: Rgb = Rgb::new\(0x62, 0xb6, 0xf5\);/, 'the base\'s own accent is the fallback'); + const light = await theme('daylight'); + assert.match(light, /mode: Mode::Light,/); + assert.match(light, /\[0\.48, 0\.42, 0\.36, 0\.54\]/, 'darker accent retries on a light base'); + // The default reproduces the literals the template used to hard-code. + const midnight = await theme('midnight'); + assert.match(midnight, /app: "#0a0c11"\.to_string\(\)[\s\S]*rainbow_span: Some\(280\.0\)/); + assert.match(midnight, /const FALLBACK_ACCENT: Rgb = Rgb::new\(0x4c, 0xc9, 0xf0\);/); +}); From 87fccb3698ef5556bc98750dbf1cf60cc3aefc4f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:58:20 +0000 Subject: [PATCH 4/6] feat(gui): --with subcommands adds headless jobs beside the window Desktop apps often need the same binary to run headless jobs for scripts, CI and agents, and open the window when run bare. That meant hand-merging the cli template's Subcommand skeleton into the GUI. With features.subcommands on a gui or workspace project (clap required): - Cli gains #[command(subcommand)] command: Option, with two jobs that are useful in any build: 'themes' (the themes it can draw) and 'paths' (where it keeps its files). Command::run(out) dispatches with no wildcard arm. - main() takes the command right after parsing and runs it headless, before the single-instance check so a job can run beside an open window. A failure goes to stderr only, with no dialog. Paired with the console attach from #15, a release build prints to the terminal. - tests/cli.rs covers both paths: a bare run means the window, a subcommand parses and runs against a buffer, an unknown one is refused. The interactive Crates step offers 'Window only' / 'Subcommands' for desktop kinds too. Closes #17 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQmV2uiGiqUHSfS6KUH --- CHANGELOG.md | 2 + README.md | 2 +- docs/CONTRACTS.md | 2 +- docs/PLAN.md | 2 +- src/args.ts | 2 +- src/context.ts | 5 ++- src/prompts.ts | 13 ++++-- src/ui/labels.ts | 2 +- templates/gui/files/src/cli.rs | 73 ++++++++++++++++++++++++++++++++ templates/gui/files/src/main.rs | 32 ++++++++++++++ templates/gui/files/tests/cli.rs | 63 +++++++++++++++++++++++++++ templates/gui/manifest.js | 1 + test/e2e.test.ts | 22 +++++++++- 13 files changed, 209 insertions(+), 12 deletions(-) create mode 100644 templates/gui/files/tests/cli.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 59b1cf1..b482217 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `--with subcommands` on desktop apps: `app ` runs a headless job (`themes`, `paths` to start + with) and exits, a bare run opens the window as before, and `tests/cli.rs` covers both paths. - `--base `: lay the signature theme's accent on any shipped theme's surfaces, e.g. `--base graphite` for neutral greys behind media. The default (`midnight`) is unchanged, and the readability tests check the result in the generated project. diff --git a/README.md b/README.md index fc1aafb..a8fe7d5 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ create-rust-app [dir] [options] | `--author ` | Author for Cargo.toml, LICENSE, headers | | `--github ` | GitHub handle for CODEOWNERS and repository links | | `--accent <#hex>` | Accent colour for GUI themes (default `#00e5ff`) | -| `--with a,b` | Turn on features / tooling, e.g. `--with tray,commandPalette`, or `--with subcommands` for a CLI built on a clap `Subcommand` enum | +| `--with a,b` | Turn on features / tooling, e.g. `--with tray,commandPalette`, or `--with subcommands` for a CLI built on a clap `Subcommand` enum (on a desktop app: headless jobs beside the window) | | `--without demo` | Start a desktop app from one empty page instead of the overview / palette / about showcase | | `--without a,b` | Turn them off, e.g. `--without release,dependabot` | | `--set ` | Set any answer directly (repeatable), e.g. `--set tagline="Fast grep"`, `--set crates.async=tokio`. The only way to set `tagline` / `displayName` without prompts. `true`/`false` become booleans | diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index e732181..25675fb 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -43,7 +43,7 @@ test/*.test.ts node --test serde: bool, async: 'none'|'tokio', http: 'none'|'ureq'|'reqwest', sqlite: bool, clap: bool }, features: { themes, brand, motion, icons, config, winres, tray, singleInstance, - commandPalette, screenshotExample, demo, subcommands }, // all bool; subcommands: cli + clap only + commandPalette, screenshotExample, demo, subcommands }, // all bool; subcommands: cli or GUI kinds, with clap tooling: { ci, release, cargoDeny, dependabot, toolchainPin, agentDocs, headerCheck, unsafeCheck, changelogGen, issueTemplates, codeowners, securityMd }, // all bool post: { git: bool, cargoCheck: bool, open: 'none'|'code'|'cursor' }, diff --git a/docs/PLAN.md b/docs/PLAN.md index 5b02fb1..8468930 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -171,7 +171,7 @@ debug = "line-tables-only" | theme base | any shipped theme id: `midnight` ★ / `graphite` / … (the surfaces the signature theme lays the accent on) | | crates | errors: anyhow ★ (+ thiserror ★ for lib/workspace); logging: `log` ★gui / `env_logger` ★cli / `tracing`; serde+toml ★; async: none ★ / tokio; http: none ★ / ureq / reqwest; sqlite: off ★ / rusqlite bundled; clap ★ (everything but lib) | | features (gui) | themes ★, brand ★, motion ★, icons ★, config ★, winres ★ (icon+manifest+version), tray, singleInstance, commandPalette, screenshotExample, demo ★ (off: one empty page instead of the overview / palette / about showcase) | -| features (cli) | subcommands (clap `Subcommand` enum, `tool …`, replaces the greeting demo; needs clap) | +| features (cli, gui) | subcommands (needs clap). cli: a clap `Subcommand` enum replaces the greeting demo. gui: optional headless jobs (`app themes`, `app paths`); a bare run opens the window | | tooling | ci ★, release ★, cargoDeny ★, dependabot ★, toolchainPin ★, agentDocs ★ (AGENTS.md + CLAUDE.md), headerCheck ★, unsafeCheck ★ (gui), changelogGen ★, issueTemplates ★, codeowners ★, securityMd ★ | | theme | accent ★`#00e5ff` | | post | git ★ (init + initial commit `feat: scaffold with create-rust-app`), cargoCheck ★ if cargo is on PATH, open: none ★ / code / cursor | diff --git a/src/args.ts b/src/args.ts index 81e907a..9114f09 100644 --- a/src/args.ts +++ b/src/args.ts @@ -172,7 +172,7 @@ async function choiceHelp(caps: unknown): Promise { const tint = (c: string, t: string) => rainbow.hex?.(caps, c, t) ?? t; const sections: [string, string, Record][] = [ ['crates', '#ff6ec7', { ...labels.CRATE_TOGGLES, tokio: { label: 'tokio', hint: labels.ASYNC.tokio.hint }, ureq: { label: 'ureq', hint: labels.HTTP.ureq.hint }, reqwest: { label: 'reqwest', hint: labels.HTTP.reqwest.hint }, tracing: { label: 'tracing', hint: labels.LOGGING.tracing.hint }, env_logger: { label: 'env_logger', hint: labels.LOGGING.env_logger.hint } }], - ['command line (cli kind, with clap)', '#b6ff6e', { subcommands: labels.FEATURES.subcommands }], + ['command line (cli and desktop kinds, with clap)', '#b6ff6e', { subcommands: labels.FEATURES.subcommands }], ['app features (desktop kinds)', '#ff9f6e', labels.DESKTOP], ['tooling', '#ffd36e', labels.TOOLING], ]; diff --git a/src/context.ts b/src/context.ts index 7ed6051..c81e64f 100644 --- a/src/context.ts +++ b/src/context.ts @@ -58,8 +58,9 @@ export function effectiveAnswers(a: Answers): Answers { // The GUI kinds always ship a config file; the CLI only when serde is on to read it. A library // leaves config to the app embedding it, and the TUI template has none. if (!hasGui && !(a.kind === 'cli' && a.crates.serde)) out.features.config = false; - // Subcommands shape a clap command line, so they need the cli kind with clap. - if (a.kind !== 'cli' || !a.crates.clap) out.features.subcommands = false; + // Subcommands shape a clap command line: the cli kind's commands, or a desktop app's headless + // jobs. A TUI or a library has no place for them, and without clap there is no parser. + if (!a.crates.clap || !(a.kind === 'cli' || hasGui)) out.features.subcommands = false; // A library has no binary, and a binary named like its crate needs no [[bin]] table. if (a.kind === 'lib' || a.bin === (a.kind === 'workspace' ? `${a.name}-app` : a.name)) out.bin = ''; return out; diff --git a/src/prompts.ts b/src/prompts.ts index ea43d46..cd7e3b5 100644 --- a/src/prompts.ts +++ b/src/prompts.ts @@ -59,7 +59,7 @@ export function reviewLines(caps: Caps, a: Answers): { title: string; body: stri (Object.keys(cat) as K[]).filter((k) => values[k] && (!group || cat[k].group === group)).map((k) => soft(cat[k].label)); const crates = ['anyhow']; - if (a.crates.clap && a.kind !== 'lib') crates.push(a.kind === 'cli' && a.features.subcommands ? 'clap subcommands' : 'clap'); + if (a.crates.clap && a.kind !== 'lib') crates.push(effectiveAnswers(a).features.subcommands ? 'clap subcommands' : 'clap'); crates.push(LOGGING[a.crates.logging].label); if (a.crates.serde) crates.push('serde + toml'); if (a.crates.thiserror) crates.push('thiserror'); @@ -185,12 +185,17 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => initialValues: toggles.filter((k) => out.crates[k]), })); for (const k of toggles) out.crates[k] = picked.includes(k); - if (a.kind === 'cli' && out.crates.clap) { + if ((a.kind === 'cli' || isGui(a)) && out.crates.clap) { + const gui = isGui(a); out.features.subcommands = got(await pick(caps, { message: 'Command line', initialValue: out.features.subcommands, options: ([ - { value: false, label: 'One command', hint: 'flags only, with a greeting to replace' }, - { value: true, label: FEATURES.subcommands.label, hint: 'tool …, one enum variant per job' }, + gui + ? { value: false, label: 'Window only', hint: 'a few flags, then the window' } + : { value: false, label: 'One command', hint: 'flags only, with a greeting to replace' }, + gui + ? { value: true, label: FEATURES.subcommands.label, hint: 'app runs headless; a bare run opens the window' } + : { value: true, label: FEATURES.subcommands.label, hint: 'tool …, one enum variant per job' }, ]), })); } diff --git a/src/ui/labels.ts b/src/ui/labels.ts index 93a9a6b..039e251 100644 --- a/src/ui/labels.ts +++ b/src/ui/labels.ts @@ -21,7 +21,7 @@ export const FEATURES: Record = { winres: { label: 'Windows resources', hint: 'exe icon, manifest, version info', group: 'packaging' }, screenshotExample: { label: 'Screenshot example', hint: 'renders the UI headlessly to PNG', group: 'packaging' }, demo: { label: 'Demo pages', hint: 'overview cards, palette and about pages; off = one empty page', group: 'content' }, - subcommands: { label: 'Subcommands', hint: 'clap subcommands instead of the greeting demo', group: 'cli' }, + subcommands: { label: 'Subcommands', hint: 'tool …: a CLI\'s commands, or a desktop app\'s headless jobs', group: 'cli' }, }; /** The desktop app features: every feature but the CLI's command-line shape. */ diff --git a/templates/gui/files/src/cli.rs b/templates/gui/files/src/cli.rs index 071754d..5ec2abb 100644 --- a/templates/gui/files/src/cli.rs +++ b/templates/gui/files/src/cli.rs @@ -16,6 +16,11 @@ //! flag added here is a flag that has to keep working. The ones that exist //! are the ones that cannot be reached any other way: an override for //! testing, and an escape hatch for a config that made the window unusable. +// @if subcommands +//! +//! A subcommand ([`Command`]) is a headless job instead: it runs, prints +//! and exits without a window, so scripts and CI can drive the app. +// @end /// The parsed command line. // @if clap @@ -44,10 +49,78 @@ pub struct Cli { #[arg(long)] // @end pub reset: bool, + // @if subcommands + /// A headless job to run instead of opening the window. + #[command(subcommand)] + pub command: Option, + // @end +} +// @elif subcommands +pub struct Cli { + /// A headless job to run instead of opening the window. + #[command(subcommand)] + pub command: Option, } // @else pub struct Cli {} // @end +// @if subcommands + +/// The headless jobs. Each runs, writes to stdout and exits without opening +/// a window, for scripts, CI and agents; a bare run opens the window. +/// +/// Add a variant per job and a matching arm in [`Command::run`]. There is no +/// wildcard arm, so a variant without one fails the build. +#[derive(clap::Subcommand, Clone, Debug, PartialEq, Eq)] +pub enum Command { + /// List the themes this build can draw in, one `idname` per line. + Themes, + /// Print where the app keeps its files, one `whatpath` per line. + Paths, +} + +impl Command { + /// Runs the job, writing its output to `out`. + /// + /// # Errors + /// + /// When `out` cannot be written to, or the job itself fails. + pub fn run(self, out: &mut impl std::io::Write) -> anyhow::Result<()> { + match self { + Self::Themes => { + // @if themes + for theme in crate::theme::Catalog::load().themes() { + writeln!(out, "{}\t{}", theme.id, theme.name)?; + } + // @else + let theme = crate::theme::signature(); + writeln!(out, "{}\t{}", theme.id, theme.name)?; + // @end + } + Self::Paths => { + // @if config | themes + let mut paths: Vec<(&str, std::path::PathBuf)> = Vec::new(); + // @else + let paths: Vec<(&str, std::path::PathBuf)> = Vec::new(); + // @end + // @if config + paths.extend(crate::config::config_path().map(|path| ("config", path))); + // @end + // @if themes + paths.extend(crate::theme::user_theme_dir().map(|dir| ("themes", dir))); + // @end + if paths.is_empty() { + writeln!(out, "(none: this build keeps no files)")?; + } + for (what, path) in paths { + writeln!(out, "{what}\t{}", path.display())?; + } + } + } + Ok(()) + } +} +// @end // @if !clap /// What a parse produced: options to run with, or text to print and exit. diff --git a/templates/gui/files/src/main.rs b/templates/gui/files/src/main.rs index c6ecfaa..a898433 100644 --- a/templates/gui/files/src/main.rs +++ b/templates/gui/files/src/main.rs @@ -40,7 +40,11 @@ fn main() -> std::process::ExitCode { @@appCrateSnake@@::win::console::attach_parent(); } // @if clap + // @if subcommands + let mut cli = { + // @else let cli = { + // @end use clap::Parser as _; Cli::parse() }; @@ -57,6 +61,15 @@ fn main() -> std::process::ExitCode { } }; // @end + // @if subcommands + + // A subcommand is a headless job: run it against the terminal and exit + // with no window, before the single-instance check so a job can run + // beside an open window. + if let Some(command) = cli.command.take() { + return headless(command); + } + // @end // @if singleInstance // A second launch hands focus to the first window and leaves, rather @@ -80,6 +93,20 @@ fn main() -> std::process::ExitCode { } } +// @if subcommands +/// Runs a headless job. A failure goes to stderr only: the caller is a +/// terminal or a script, not someone looking for a dialog. +fn headless(command: @@appCrateSnake@@::cli::Command) -> std::process::ExitCode { + match command.run(&mut std::io::stdout().lock()) { + Ok(()) => std::process::ExitCode::SUCCESS, + Err(error) => { + eprintln!("error: {error:#}"); + std::process::ExitCode::FAILURE + } + } +} + +// @end /// Applies the command line to the saved preferences and opens the window. fn run(cli: Cli) -> anyhow::Result<()> { // @if config @@ -98,7 +125,12 @@ fn run(cli: Cli) -> anyhow::Result<()> { } @@appCrateSnake@@::gui::run::run(config) // @else + // @if subcommands + // main() has taken any subcommand; only the window is left to open. + let Cli { command: _ } = cli; + // @else let Cli {} = cli; + // @end @@appCrateSnake@@::gui::run::run() // @end } diff --git a/templates/gui/files/tests/cli.rs b/templates/gui/files/tests/cli.rs new file mode 100644 index 0000000..b0470a0 --- /dev/null +++ b/templates/gui/files/tests/cli.rs @@ -0,0 +1,63 @@ +// ============================================================================ +// Module: @@module@@ +// Description: The command line's two paths: a bare run opens the window, +// a subcommand runs a headless job. +// +// Dependencies: @@appCrateSnake@@::cli, clap, anyhow +// ============================================================================ + +//! The command line's two paths. +//! +//! The window itself can't open in a test, so this checks the decision +//! `main` makes (no subcommand: window; a subcommand: headless) and runs +//! the headless jobs against an in-memory buffer. + +use @@appCrateSnake@@::cli::{Cli, Command}; + +/// Parses `args` after a program name. +fn parse(args: &[&str]) -> Result { + let argv = std::iter::once("@@bin@@").chain(args.iter().copied()); + ::try_parse_from(argv) +} + +/// Runs `command` and returns what it printed. +fn output(command: Command) -> anyhow::Result { + let mut out = Vec::new(); + command.run(&mut out)?; + Ok(String::from_utf8(out)?) +} + +#[test] +fn a_bare_run_opens_the_window() -> anyhow::Result<()> { + assert_eq!(parse(&[])?.command, None, "no subcommand means the window"); + Ok(()) +} + +#[test] +fn a_subcommand_runs_headless() -> anyhow::Result<()> { + assert_eq!(parse(&["themes"])?.command, Some(Command::Themes)); + assert_eq!(parse(&["paths"])?.command, Some(Command::Paths)); + Ok(()) +} + +#[test] +fn an_unknown_subcommand_is_refused() { + assert!( + parse(&["no-such-job"]).is_err(), + "a typo must not open the window instead" + ); +} + +#[test] +fn themes_lists_the_signature_theme_first() -> anyhow::Result<()> { + let out = output(Command::Themes)?; + assert!(out.starts_with("signature\t"), "signature leads: {out:?}"); + Ok(()) +} + +#[test] +fn paths_always_says_something() -> anyhow::Result<()> { + let out = output(Command::Paths)?; + assert!(!out.trim().is_empty(), "paths printed nothing"); + Ok(()) +} diff --git a/templates/gui/manifest.js b/templates/gui/manifest.js index 1630527..aa641a1 100644 --- a/templates/gui/manifest.js +++ b/templates/gui/manifest.js @@ -19,6 +19,7 @@ const OWNED = [ [/^assets\/[^/]+\.manifest$/, 'winres'], [/^assets\/[^/]+\.ico$/, 'winres'], [/^examples\/screenshot\.rs$/, 'screenshotExample'], + [/^tests\/cli\.rs$/, 'subcommands'], // The eframe runner; the gui-glow group ships its own file at this dest. [/^src\/gui\/run\.rs$/, 'gui_eframe'], ]; diff --git a/test/e2e.test.ts b/test/e2e.test.ts index e47980d..8e964fa 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -103,7 +103,7 @@ test('banners name the crates the project uses, not the options it could have (# } }); -test('--with subcommands swaps in the subcommand CLI, only for the cli kind with clap (#9)', async () => { +test('--with subcommands swaps in the subcommand CLI for the cli kind with clap, and leaves a TUI alone (#9)', async () => { const plan = async (preset: string, extra: Record) => buildPlan(buildContext(resolveAnswers(preset, { name: 'sub-' + preset, ...extra }))); const text = (entries: PlanEntry[], dest: string) => { @@ -196,3 +196,23 @@ test('--base lays the signature theme on a shipped theme\'s surfaces (#19)', asy assert.match(midnight, /app: "#0a0c11"\.to_string\(\)[\s\S]*rainbow_span: Some\(280\.0\)/); assert.match(midnight, /const FALLBACK_ACCENT: Rgb = Rgb::new\(0x4c, 0xc9, 0xf0\);/); }); + +test('--with subcommands on a desktop app adds headless jobs beside the window (#17)', async () => { + const text = (entries: PlanEntry[], dest: string) => { + const e = entries.find((x: PlanEntry) => x.dest === dest); + return e && 'content' in e ? e.content : ''; + }; + const gui = await buildPlan(buildContext(resolveAnswers('rustaman', { name: 'g', features: { subcommands: true } }))); + assert.match(text(gui, 'src/cli.rs'), /#\[command\(subcommand\)\]\n pub command: Option,/, 'optional subcommand'); + assert.match(text(gui, 'src/cli.rs'), /pub enum Command \{[\s\S]*Themes,[\s\S]*Paths,/, 'example jobs'); + const main = text(gui, 'src/main.rs'); + assert.match(main, /if let Some\(command\) = cli\.command\.take\(\) \{\n return headless\(command\);/, 'headless dispatch'); + assert.ok(main.indexOf('headless(command)') < main.indexOf('fn run('), 'dispatch happens before the window'); + assert.ok(gui.some((e: PlanEntry) => e.dest === 'tests/cli.rs'), 'both paths are tested'); + + const plain = await buildPlan(buildContext(resolveAnswers('rustaman', { name: 'g' }))); + assert.ok(!plain.some((e: PlanEntry) => e.dest === 'tests/cli.rs'), 'off by default'); + assert.doesNotMatch(text(plain, 'src/main.rs'), /headless/, 'no headless path by default'); + const noClap = buildContext(resolveAnswers('rustaman', { name: 'g', crates: { clap: false }, features: { subcommands: true } })); + assert.ok(!noClap.flags.has('subcommands'), 'needs clap'); +}); From e589df289661a1d6e9dfa1cdffc6fd30757239de Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:03:05 +0000 Subject: [PATCH 5/6] fix(gui): attach to the terminal's console only to print Review follow-up to the #15 fix. main() attached whenever it had arguments, so 'app --theme nebula' from a terminal opened a window tied to that console: closing the terminal, or Ctrl+C in it, closed the app. main() now parses with try_parse() first and calls borrow_console() only when there is output: clap's help, version and usage errors (exit codes as clap's exit() gives them), the hand-rolled parser's equivalents, and a headless subcommand. Opening the window never attaches. A window-start failure in a release build is therefore reported by the dialog alone, not twice. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQmV2uiGiqUHSfS6KUH --- CHANGELOG.md | 7 ++-- templates/gui/files/src/main.rs | 47 ++++++++++++++++++-------- templates/gui/files/src/win/console.rs | 4 +++ 3 files changed, 41 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b482217..0c105a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- A release build of a GUI app run from a terminal prints its `--help`, `--version` and usage - errors: with arguments it attaches to the parent console first (`src/win/console.rs`). - Explorer launches are unchanged. +- A release build of a GUI app run from a terminal prints its `--help`, `--version`, usage errors + and headless output: it attaches to the parent console just before printing + (`src/win/console.rs`). Opening the window never attaches, so closing the terminal doesn't close + the app, and Explorer launches are unchanged. - The review panel and the next-steps box fit narrow terminals: below about 60 columns their right edges used to wrap onto the next line. Title facts that don't fit move into the panel, and the box drops its notes, then its frame, rather than overflow. diff --git a/templates/gui/files/src/main.rs b/templates/gui/files/src/main.rs index a898433..ce4cd70 100644 --- a/templates/gui/files/src/main.rs +++ b/templates/gui/files/src/main.rs @@ -19,10 +19,12 @@ //! //! ## A release build borrows the terminal it was run from //! -//! A release build has no console of its own. Run with arguments from a -//! terminal, it attaches to that terminal's console before parsing, so -//! `--help`, `--version` and usage errors print there; launched from -//! Explorer there is nothing to attach to and nothing changes. +//! A release build has no console of its own. When it has something to +//! print (`--help`, `--version`, a usage error, a headless job) it attaches +//! to the console of the terminal it was run from, so the output lands +//! there; launched from Explorer there is nothing to attach to. It never +//! attaches just to open the window, which would tie the window's life to +//! the terminal. //! //! ## Failures are also reported in a dialog on Windows //! @@ -33,29 +35,36 @@ use @@appCrateSnake@@::cli::Cli; fn main() -> std::process::ExitCode { - // Arguments mean a terminal (Explorer passes none): attach to its - // console before anything is printed, or it would print to nowhere. - #[cfg(windows)] - if std::env::args_os().len() > 1 { - @@appCrateSnake@@::win::console::attach_parent(); - } // @if clap // @if subcommands - let mut cli = { + let mut cli = match ::try_parse() { // @else - let cli = { + let cli = match ::try_parse() { // @end - use clap::Parser as _; - Cli::parse() + Ok(cli) => cli, + Err(error) => { + // Help, version or a usage error: something to print, so borrow + // the terminal. Printing is best effort; the exit code carries + // the outcome either way, as clap's own exit() would. + borrow_console(); + let _ = error.print(); + return if error.use_stderr() { + std::process::ExitCode::from(2) + } else { + std::process::ExitCode::SUCCESS + }; + } }; // @else let cli = match Cli::parse_from(std::env::args().skip(1)) { Ok(@@appCrateSnake@@::cli::Parsed::Run(cli)) => cli, Ok(@@appCrateSnake@@::cli::Parsed::Print(text)) => { + borrow_console(); println!("{text}"); return std::process::ExitCode::SUCCESS; } Err(message) => { + borrow_console(); eprintln!("error: {message}"); return std::process::ExitCode::from(2); } @@ -67,6 +76,7 @@ fn main() -> std::process::ExitCode { // with no window, before the single-instance check so a job can run // beside an open window. if let Some(command) = cli.command.take() { + borrow_console(); return headless(command); } // @end @@ -93,6 +103,15 @@ fn main() -> std::process::ExitCode { } } +/// Borrows the launching terminal's console before printing: a release +/// build has none of its own (see `win::console`). Called only when there +/// is output, never before opening the window, because a process attached +/// to a console is closed with it and gets its Ctrl+C. +fn borrow_console() { + #[cfg(windows)] + @@appCrateSnake@@::win::console::attach_parent(); +} + // @if subcommands /// Runs a headless job. A failure goes to stderr only: the caller is a /// terminal or a script, not someone looking for a dialog. diff --git a/templates/gui/files/src/win/console.rs b/templates/gui/files/src/win/console.rs index 20c0a28..d625bdb 100644 --- a/templates/gui/files/src/win/console.rs +++ b/templates/gui/files/src/win/console.rs @@ -14,6 +14,10 @@ //! written to nowhere. Attaching to the parent's console fixes that, and //! does nothing when there is no parent console to attach to. //! +//! Attach only to print: an attached process is closed with the console +//! and receives its Ctrl+C, so `main` never attaches before opening the +//! window. +//! //! One quirk of the platform remains: the shell does not wait for a //! Windows-subsystem program, so its prompt can come back before the //! output. Press Enter for a fresh prompt. From 073fcd431d3e12e563b39275bc3918672ab4a23a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:04:04 +0000 Subject: [PATCH 6/6] test: follow main.rs's console borrowing in the GUI subcommand test The previous commit put borrow_console() before the headless run; the test's regex predated it. It now also checks that main() never attaches just because there are arguments. The main.rs docs mention headless jobs only when subcommands are on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQmV2uiGiqUHSfS6KUH --- templates/gui/files/src/main.rs | 4 ++++ test/e2e.test.ts | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/templates/gui/files/src/main.rs b/templates/gui/files/src/main.rs index ce4cd70..9949ea1 100644 --- a/templates/gui/files/src/main.rs +++ b/templates/gui/files/src/main.rs @@ -20,7 +20,11 @@ //! ## A release build borrows the terminal it was run from //! //! A release build has no console of its own. When it has something to +// @if subcommands //! print (`--help`, `--version`, a usage error, a headless job) it attaches +// @else +//! print (`--help`, `--version`, a usage error) it attaches +// @end //! to the console of the terminal it was run from, so the output lands //! there; launched from Explorer there is nothing to attach to. It never //! attaches just to open the window, which would tie the window's life to diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 8e964fa..a249f10 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -206,7 +206,8 @@ test('--with subcommands on a desktop app adds headless jobs beside the window ( assert.match(text(gui, 'src/cli.rs'), /#\[command\(subcommand\)\]\n pub command: Option,/, 'optional subcommand'); assert.match(text(gui, 'src/cli.rs'), /pub enum Command \{[\s\S]*Themes,[\s\S]*Paths,/, 'example jobs'); const main = text(gui, 'src/main.rs'); - assert.match(main, /if let Some\(command\) = cli\.command\.take\(\) \{\n return headless\(command\);/, 'headless dispatch'); + assert.match(main, /if let Some\(command\) = cli\.command\.take\(\) \{\n borrow_console\(\);\n return headless\(command\);/, 'headless dispatch, printing to the terminal'); + assert.doesNotMatch(main, /args_os\(\)\.len\(\)/, 'never attaches just because there are arguments'); assert.ok(main.indexOf('headless(command)') < main.indexOf('fn run('), 'dispatch happens before the window'); assert.ok(gui.some((e: PlanEntry) => e.dest === 'tests/cli.rs'), 'both paths are tested');