shell-w7: net change of 3 commits

- shell-w7: written from its sheet
- shell-w7: written by an agent
- shell-w7: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor committed 2026-11-27 14:51:29 +00:00
1 parent f285bc5bc9
commit 5e8a1c825b
3 files changed
+691 -1188

No files matched your search

+117 -278
View File
@@ -1,22 +1,20 @@
//! The File tab (Backstage, #76): a full-window view that replaces the ribbon, slides and status
//! bar until Esc or the back arrow returns to the presentation. With nothing open it is the start
//! screen: PowerPoint's start screen and File › Home are the same page.
//! The File tab replaces the editor until the user returns to the presentation.
//! With no document it is the start screen, showing the same Home page.
//!
//! A side menu on the left picks a page (Home, New, Open, Info, Save As, Print, Export, About);
//! Save, Close and Options act at once. Every action runs an existing command through
//! [`SlideApp::run`] or one of the app's file helpers ([`SlideApp::export_as`],
//! [`SlideApp::print_pdf`], [`SlideApp::save_as_dialog`]); the state here is UI-only and never
//! saved. Recent presentations are listed by path: nothing on disk is read until one is picked.
//!
//! Laid out after PowerPoint for Windows (observed black-box): a 160-point side menu darker than
//! the page, 40-point entries with an outline icon, the current page in the accent colour.
use egui::{Align2, Color32, CornerRadius, Key, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use craft::menu::ribbon::{BackstageEntry, BackstageEvent, BackstageView};
use craft::ui::contract::{BodyCx, Show as _};
use craft::ui::display::Text;
use egui::Ui;
use serde_json::{Value, json};
use crate::SlideApp;
use crate::icons::{self, Icon};
use crate::theme::{self, Tokens};
use crate::icons::Icon;
mod files;
mod info;
@@ -24,33 +22,34 @@ mod print;
pub use files::split_path;
use files::{home, new_page, open_page};
pub use info::SAVE_TYPES;
use info::{PROPERTIES, about, commit_props, info, save_as};
pub use info::{SAVE_TYPES, format_bytes};
use print::{export, print};
pub use print::{print_page_size, print_params, print_slides};
/// Width of the side menu.
pub const NAV_W: f32 = 160.0;
/// Height of a side-menu entry (the back arrow's row is a little taller).
const ITEM_H: f32 = 40.0;
const BACK_H: f32 = 46.0;
/// The widest a page's content grows.
const CONTENT_W: f32 = 1180.0;
/// A page of the File tab.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Page {
/// Start page and recent presentations.
Home,
/// Blank presentations, themes and templates.
New,
/// File browsing and recent presentations.
Open,
/// Presentation metadata and properties.
Info,
/// A destination and format for saving.
SaveAs,
/// Print settings and page previews.
Print,
/// Copies in other formats.
Export,
/// Product information and appearance settings.
About,
}
impl Page {
/// Every File page accepted by the automation command.
pub const ALL: [Page; 8] = [Page::Home, Page::New, Page::Open, Page::Info, Page::SaveAs, Page::Print, Page::Export, Page::About];
/// The id `app.backstage {page}` takes.
@@ -67,9 +66,10 @@ impl Page {
}
}
/// Resolve a File page id, including its compatibility alias.
pub fn parse(id: &str) -> Option<Page> {
let id = id.trim();
// Keep existing control-channel callers working after the visible page rename.
// The compatibility alias keeps saved automation requests valid.
if id.eq_ignore_ascii_case("account") {
return Some(Page::About);
}
@@ -112,9 +112,13 @@ impl Page {
/// A side-menu entry: a page, or an action that runs at once.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Nav {
/// Shows a File page.
Page(Page),
/// Saves the active presentation.
Save,
/// Requests closing the active presentation.
Close,
/// Opens preferences above the File view.
Options,
}
@@ -127,6 +131,7 @@ impl Nav {
Nav::Options => "Options",
}
}
fn icon(self) -> Icon {
match self {
Nav::Page(p) => p.icon(),
@@ -137,29 +142,36 @@ impl Nav {
}
}
/// The side menu, top group then bottom group, in keyboard order. PowerPoint's Share (cloud) is
/// left out; with nothing open only Home, New and Open stay at the top.
pub fn entries(has_doc: bool) -> (Vec<Nav>, Vec<Nav>) {
let mut top = vec![Nav::Page(Page::Home), Nav::Page(Page::New), Nav::Page(Page::Open)];
if has_doc {
top.extend([Nav::Page(Page::Info), Nav::Save, Nav::Page(Page::SaveAs), Nav::Page(Page::Print), Nav::Page(Page::Export), Nav::Close]);
}
(top, vec![Nav::Page(Page::About), Nav::Options])
/// The side menu's visual groups, in their keyboard order.
pub fn entries(has_doc: bool) -> (Vec<Nav>, Vec<Nav>, Vec<Nav>) {
let first = vec![Nav::Page(Page::Home), Nav::Page(Page::New), Nav::Page(Page::Open)];
let document = if has_doc {
vec![Nav::Page(Page::Info), Nav::Save, Nav::Page(Page::SaveAs), Nav::Page(Page::Print), Nav::Page(Page::Export), Nav::Close]
} else {
Vec::new()
};
(first, document, vec![Nav::Page(Page::About), Nav::Options])
}
/// Print page: which slides.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrintScope {
/// Every eligible slide.
All,
/// The active slide, including a hidden slide.
Current,
/// Slides named by the range field.
Custom,
}
/// Export page: the chosen task on the left.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExportTask {
/// A PDF copy of the presentation.
Pdf,
/// A PDF with several slides per page.
Handouts,
/// A copy in a selected presentation, text or picture format.
FileType,
}
@@ -167,34 +179,40 @@ pub enum ExportTask {
#[derive(Clone, Debug)]
pub struct Backstage {
/// Identity of this File view, preserved across page changes.
#[allow(dead_code)] // P3(shell-w7): sh.A24
pub(crate) instance: std::sync::Arc<()>,
/// The page displayed in this view.
pub page: Page,
/// The open presentations (count, active) when it opened: a change closes it.
pub docs: (usize, Option<u64>),
/// Keyboard focus in the side menu (an index into [`entries`], top then bottom).
pub focus: Option<usize>,
/// Requests focus on the shown entry for the next File view pass.
#[allow(dead_code)] // P3(shell-w7): sh.A24
/// Requests focus on the shown entry for one pass; a second pass keeps only the resulting framework focus.
pub(crate) focus_shown: bool,
/// Search text on Home, New and Open.
pub query: String,
/// Info: property drafts while a field is being edited.
props: Vec<String>,
/// Which slides the print preview and output include.
pub print_scope: PrintScope,
/// A one-based slide range when the scope is custom.
pub print_range: String,
/// `slides`, `notes`, or `h1`…`h9` (handouts with that many slides a page).
pub print_layout: &'static str,
/// Includes hidden slides when printing a range or the whole deck.
pub print_hidden: bool,
/// Draws a frame around slides in printed output.
pub print_frame: bool,
/// Notes and handouts: a paper id from [`deckcraft_engine::cmd::file::PAPERS`] and its orientation.
pub print_paper: &'static str,
/// Uses landscape paper for notes and handouts.
pub print_landscape: bool,
/// Zero-based page displayed by the print preview.
pub preview_page: usize,
/// The selected export task.
pub export: ExportTask,
/// Export › Change File Type / Save As: the chosen type (an [`SAVE_TYPES`] id).
pub file_type: &'static str,
/// Slides per page for an exported handout.
pub handouts_per_page: u8,
/// Includes hidden slides in exported PDFs.
pub pdf_hidden: bool,
/// Export › Change File Type › PNG: leave the slide background out (#784).
pub png_transparent: bool,
@@ -205,13 +223,10 @@ impl Backstage {
/// can be detected.
pub fn new(page: Page, docs: (usize, Option<u64>)) -> Backstage {
Backstage {
// P3(shell-w7): sh.A24
instance: Default::default(),
instance: std::sync::Arc::new(()),
page,
docs,
focus: None,
// P3(shell-w7): sh.A24
focus_shown: Default::default(),
focus_shown: false,
query: String::new(),
props: vec![String::new(); PROPERTIES.len()],
print_scope: PrintScope::All,
@@ -247,23 +262,17 @@ struct Outcome {
page: Option<Page>,
}
/// Colours of the side menu and the page, from the theme: the menu sits a step darker than the
/// page, as in PowerPoint.
fn colours(t: &Tokens) -> (Color32, Color32) {
(t.chrome, t.card)
}
/// Runs a side-menu action. Returns the page to show, or None to close the view (Some(current)
/// leaves it as it is).
fn act(app: &mut SlideApp, nav: Nav, current: Page) -> Option<Page> {
match nav {
Nav::Page(p) => Some(p),
Nav::Save => {
// A page that keeps the files (`host_save`) saves as the desktop does.
let web = app.services.pick_save.is_none() && app.services.download.is_some() && app.services.host_save.is_none();
let files = app.host.files();
let web = files.browser_saves() && !files.saves_to_page();
let has_path = app.session.active().is_some_and(|d| d.path.is_some());
if !has_path && !web {
// A presentation that was never saved goes to Save As first, as in PowerPoint.
// An untitled presentation needs a destination before an in-place save is possible.
return Some(Page::SaveAs);
}
app.save();
@@ -281,254 +290,84 @@ fn act(app: &mut SlideApp, nav: Nav, current: Page) -> Option<Page> {
}
}
/// The File tab's own keys: Esc goes back to the presentation; Up and Down walk the side menu
/// (a page shows as soon as it has the focus, as in PowerPoint); Enter or Space runs the focused
/// action. True when the key was used.
pub fn key(app: &mut SlideApp, key: Key, mods: deckcraft_engine::Mods) -> bool {
if mods.cmd || mods.alt || mods.shift {
return false;
}
let has_doc = app.session.active().is_some();
let (top, bottom) = entries(has_doc);
let all: Vec<Nav> = top.into_iter().chain(bottom).collect();
let Some(bs) = app.backstage.as_mut() else { return false };
match key {
Key::Escape => {
app.close_backstage();
true
}
Key::ArrowDown | Key::ArrowUp => {
let cur = bs.focus.or_else(|| all.iter().position(|n| *n == Nav::Page(bs.page)));
let n = all.len();
let next = match (cur, key == Key::ArrowDown) {
(None, _) => 0,
(Some(i), true) => (i + 1) % n,
(Some(i), false) => (i + n - 1) % n,
};
bs.focus = Some(next);
if let Some(Nav::Page(p)) = all.get(next) {
bs.go(*p);
}
true
}
Key::Enter | Key::Space => {
let Some(nav) = bs.focus.and_then(|i| all.get(i)).copied() else { return false };
let current = bs.page;
match act(app, nav, current) {
None => app.close_backstage(),
Some(p) => {
if let Some(bs) = app.backstage.as_mut() {
bs.go(p);
}
}
}
true
}
_ => false,
}
fn view_entries(group: Vec<Nav>) -> Vec<BackstageEntry<'static, Nav>> {
group
.into_iter()
.map(|nav| match nav {
Nav::Page(_) => BackstageEntry::page(nav, nav.label(), nav.icon().id()),
_ => BackstageEntry::action(nav, nav.label(), nav.icon().id()),
})
.collect()
}
/// Draws the File tab in place of the ribbon, slides and status bar.
pub fn show(app: &mut SlideApp, ui: &mut Ui) {
let Some(mut bs) = app.backstage.take() else { return };
let t = Tokens::get(ui.ctx());
/// Shows the File view as the shell's page body.
pub(crate) fn page(app: &mut SlideApp, ui: &mut Ui, cx: &mut BodyCx<'_>) {
let Some(mut bs) = app.backstage.take() else {
return;
};
let has_doc = app.session.active().is_some();
if !has_doc && bs.page.needs_doc() {
bs.page = Page::Home;
bs.go(Page::Home);
}
let (first, document, bottom) = entries(has_doc);
let first = view_entries(first);
let document = view_entries(document);
let bottom = view_entries(bottom);
let mut view = BackstageView::new(Nav::Page(bs.page))
.back(has_doc)
.group(&first)
.group(&document)
.bottom(&bottom)
.focus_shown(std::mem::take(&mut bs.focus_shown));
if bs.page != Page::Home {
view = view.heading(bs.page.label());
}
let (nav_bg, page_bg) = colours(&t);
let mut out = Outcome::default();
let (top, bottom) = entries(has_doc);
egui::Panel::left("backstage_nav").exact_size(NAV_W).resizable(false).frame(egui::Frame::NONE.fill(nav_bg)).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
if has_doc {
let (r, resp) = ui.allocate_exact_size(vec2(NAV_W, BACK_H), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Back"));
let hovered = resp.hovered();
if hovered {
ui.painter().rect_filled(Rect::from_center_size(pos2(r.left() + 26.0, r.center().y), vec2(34.0, 34.0)), 17.0, t.hover);
}
icons::paint(
ui.painter(),
Rect::from_center_size(pos2(r.left() + 26.0, r.center().y), vec2(22.0, 22.0)),
Icon::BackCircle,
t.text,
false,
);
if resp.on_hover_text("Back (Esc)").clicked() {
out.close = true;
}
} else {
ui.add_space(BACK_H);
let shown = view.show(ui, cx, |ui, cx| {
if let Some(message) = app.fresh_status() {
let _ = Text::new(message.to_owned()).tone(craft::theme::variant::Tone::Accent).show(ui);
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
}
let mut index = 0;
for (k, nav) in top.iter().enumerate() {
if k == 3 {
separator(ui, &t);
}
if nav_item(ui, *nav, &bs, index, &t).clicked() {
bs.focus = None;
commit_props(app, &bs);
match act(app, *nav, bs.page) {
None => out.close = true,
Some(p) => out.page = Some(p),
}
}
index += 1;
match bs.page {
Page::Home => home(app, ui, cx, &mut bs, &mut out),
Page::New => new_page(app, ui, cx, &mut bs),
Page::Open => open_page(app, ui, cx, &mut bs),
// PLAN: assumed info(app, ui, cx, bs) (shell-w8)
Page::Info => info(app, ui, cx, &mut bs),
// PLAN: assumed save_as(app, ui, cx, bs, out) (shell-w8)
Page::SaveAs => save_as(app, ui, cx, &mut bs, &mut out),
// PLAN: assumed print(app, ui, cx, bs) (shell-w8)
Page::Print => print(app, ui, cx, &mut bs),
// PLAN: assumed export(app, ui, cx, bs) (shell-w8)
Page::Export => export(app, ui, cx, &mut bs),
// PLAN: assumed about(app, ui, cx) (shell-w8)
Page::About => about(app, ui, cx),
}
let first_bottom = index;
ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| {
ui.add_space(8.0);
// Bottom-up: draw the last entry first.
for (k, nav) in bottom.iter().enumerate().rev() {
if nav_item(ui, *nav, &bs, first_bottom + k, &t).clicked() {
bs.focus = None;
commit_props(app, &bs);
match act(app, *nav, bs.page) {
None => out.close = true,
Some(p) => out.page = Some(p),
}
}
});
match shown.event {
Some(BackstageEvent::Show(Nav::Page(page))) => bs.go(page),
Some(BackstageEvent::Act(nav)) => {
commit_props(app, &bs);
match act(app, nav, bs.page) {
Some(page) => out.page = Some(page),
None => out.close = true,
}
separator(ui, &t);
});
});
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(page_bg)).show(ui, |ui| {
// Fields, boxes and buttons sit on the page's own colour: outline them, as PowerPoint does.
ui.visuals_mut().text_edit_bg_color = Some(t.field_bg);
let w = &mut ui.visuals_mut().widgets;
w.inactive.bg_fill = t.field_bg;
w.inactive.weak_bg_fill = t.field_bg;
w.inactive.bg_stroke = Stroke::new(1.0, t.border);
w.hovered.bg_stroke = Stroke::new(1.0, t.accent);
w.active.bg_stroke = Stroke::new(1.0, t.accent);
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
egui::Frame::NONE.inner_margin(egui::Margin { left: 48, right: 36, top: 22, bottom: 32 }).show(ui, |ui| {
// set_max_width can also widen: in a window narrower than CONTENT_W it would push the
// page past the right margin and clip the tiles (#1421).
ui.set_max_width(ui.available_width().min(CONTENT_W));
if bs.page != Page::Home {
ui.label(RichText::new(bs.page.label()).font(theme::bold(22.0)).color(t.text));
ui.add_space(16.0);
}
// Errors raised on a backstage page (a missing recent file, a failed open) would
// otherwise vanish: the status bar only draws once the backstage is closed (#172).
// A real label, not painted text, so screen readers see it too.
if let Some(msg) = app.fresh_status() {
// P3(shell-w7): sh.A12
ui.label(RichText::new(msg).font(theme::font(12.0)).color(t.accent));
ui.add_space(8.0);
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
}
match bs.page {
Page::Home => home(app, ui, &mut bs, &mut out),
Page::New => new_page(app, ui, &mut bs),
Page::Open => open_page(app, ui, &mut bs),
Page::Info => info(app, ui, &mut bs),
Page::SaveAs => save_as(app, ui, &mut bs, &mut out),
Page::Print => print(app, ui, &mut bs),
Page::Export => export(app, ui, &mut bs),
Page::About => about(app, ui),
}
});
});
});
}
Some(BackstageEvent::Back) => out.close = has_doc,
_ => {}
}
if let Some(page) = out.page {
bs.go(page);
}
// A command run from a page may have closed the view itself (a new presentation); keep that.
// A page command can replace the deck or open another File view during the callback.
if out.close && has_doc {
app.backstage = None;
} else if app.backstage.is_none() {
if app.backstage.as_ref().is_none_or(|current| std::sync::Arc::ptr_eq(&current.instance, &bs.instance)) {
app.close_backstage();
}
} else if app.backstage.is_none() && app.docs_key() == bs.docs {
app.backstage = Some(bs);
}
}
// ---------------------------------------------------------------- side menu
/// Draw one clickable Backstage navigation row and return its interaction response.
fn nav_item(ui: &mut Ui, nav: Nav, bs: &Backstage, index: usize, t: &Tokens) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(NAV_W, ITEM_H), Sense::click());
let selected = nav == Nav::Page(bs.page);
let label = nav.label();
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, label));
let p = ui.painter();
let row = rect.shrink2(vec2(6.0, 1.0));
if resp.hovered() {
p.rect_filled(row, CornerRadius::same(2), t.hover);
}
if bs.focus == Some(index) || selected {
// The current page (and the keyboard focus) is outlined, as in PowerPoint.
let ink = if bs.focus == Some(index) { t.text } else { t.border };
p.rect_stroke(row, CornerRadius::same(2), Stroke::new(1.0, ink), StrokeKind::Inside);
}
let ink = if selected { t.accent } else { t.text };
icons::paint(p, Rect::from_center_size(pos2(rect.left() + 26.0, rect.center().y), vec2(16.0, 16.0)), nav.icon(), ink, false);
p.text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, label, theme::font(13.0), ink);
resp
}
fn separator(ui: &mut Ui, t: &Tokens) {
let (rect, _) = ui.allocate_exact_size(vec2(NAV_W, 13.0), Sense::hover());
let y = rect.center().y;
ui.painter().line_segment([pos2(rect.left() + 20.0, y), pos2(rect.right() - 14.0, y)], Stroke::new(1.0, t.separator));
}
// ---------------------------------------------------------------- shared pieces
fn heading(ui: &mut Ui, text: &str) {
let t = Tokens::get(ui.ctx());
ui.label(RichText::new(text).font(theme::bold(16.0)).color(t.text));
ui.add_space(8.0);
}
fn dim(ui: &mut Ui, text: &str) {
let t = Tokens::get(ui.ctx());
ui.label(RichText::new(text).font(theme::font(12.5)).color(t.text_dim));
}
/// A link with an arrow (More themes →): true when clicked.
fn arrow_link(ui: &mut Ui, text: &str) -> bool {
let t = Tokens::get(ui.ctx());
ui.add(egui::Label::new(RichText::new(format!("{text} →")).font(theme::font(12.5)).color(t.accent)).sense(Sense::click()))
.on_hover_cursor(egui::CursorIcon::PointingHand)
.clicked()
}
/// A search box; true when its text changed.
fn search(ui: &mut Ui, query: &mut String, hint: &str, width: f32) -> bool {
ui.add(egui::TextEdit::singleline(query).hint_text(hint).desired_width(width)).changed()
}
/// Draw a labelled icon button and return whether it was clicked while enabled.
fn icon_button(ui: &mut Ui, icon: Icon, label: &str, enabled: bool) -> bool {
let t = Tokens::get(ui.ctx());
let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), if enabled { Sense::click() } else { Sense::hover() });
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label));
if resp.hovered() && enabled {
ui.painter().rect_filled(r, CornerRadius::same(3), t.hover);
}
icons::paint(ui.painter(), r.shrink(3.0), icon, t.text, !enabled);
resp.on_hover_text(label).clicked()
}
fn bullets(ui: &mut Ui, items: &[&str]) {
ui.add_space(4.0);
for b in items {
ui.horizontal(|ui| {
ui.add_space(6.0);
ui.label(RichText::new(format!("• {b}")).font(theme::font(12.5)));
});
}
ui.add_space(10.0);
}
#[cfg(test)]
mod tests;
/// Shows the File page as a shell page.
#[allow(dead_code)] // P3(shell-w7): sh.A24
pub(crate) fn page(app: &mut SlideApp, ui: &mut egui::Ui, cx: &mut craft::ui::contract::BodyCx<'_>) {
let _ = (app, ui, cx);
todo!("sh.A24")
}
+241 -288
View File
@@ -1,91 +1,133 @@
use super::{
Align2, Backstage, CONTENT_W, Color32, CornerRadius, Icon, Outcome, Page, Rect, RichText, Sense, SlideApp, Stroke, StrokeKind, Tokens, Ui, Value,
arrow_link, dim, heading, icons, json, pos2, search, theme, vec2,
use std::borrow::Cow;
use craft::behavior::{Selection, keyed};
use craft::ui::buttons::{Button, Link};
use craft::ui::contract::{
ActivateOn, Bind, BodyCx, CollectionEvent, LeastWidth, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
clicked,
};
use craft::ui::display::{Divider, Picture, Shade, Text};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize};
/// A new-presentation tile: a theme preview drawn in code (or a blank slide) over its name.
fn tile(ui: &mut Ui, label: &str, theme: Option<&deckcraft_model::Theme>, big: bool) -> egui::Response {
let t = Tokens::get(ui.ctx());
let thumb_w = if big { 200.0 } else { 160.0 };
let (rect, resp) = ui.allocate_exact_size(vec2(thumb_w + 16.0, thumb_w * 9.0 / 16.0 + 44.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let p = ui.painter();
if resp.hovered() {
p.rect_filled(rect, CornerRadius::same(4), t.hover);
}
let thumb = Rect::from_min_size(rect.min + vec2(8.0, 10.0), vec2(thumb_w, thumb_w * 9.0 / 16.0));
match theme {
// P3(shell-w7): rb.A20
Some(th) => crate::ribbon::paint_theme_tile_base(p, thumb, th),
None => {
p.rect_filled(thumb, CornerRadius::same(2), Color32::WHITE);
p.rect_stroke(thumb, CornerRadius::same(2), Stroke::new(1.0, Color32::from_gray(200)), StrokeKind::Inside);
}
}
if resp.hovered() {
p.rect_stroke(thumb, CornerRadius::same(2), Stroke::new(2.0, t.accent), StrokeKind::Outside);
}
let galley = p.layout(label.to_string(), theme::font(12.0), t.text, rect.width() - 8.0);
p.galley(pos2(rect.center().x - galley.size().x / 2.0, thumb.bottom() + 8.0), galley, t.text);
resp
use craft::ui::sections::Section;
use craft::ui::shell::{RecentFile, RecentList, StartAction};
use craft::ui::style::TypeRole;
use craft::ui::text::TextField;
use craft::ui::tile_grid::{CardText, Tile, TileGrid};
use super::{Backstage, Icon, Outcome, Page, SlideApp, Ui, Value, json};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum NewChoice {
Blank,
Theme(String),
Sample,
Template(String),
}
/// The built-in themes and the sample deck, filtered by `query` (after a blank presentation when
/// `blank`); at most `limit` theme tiles. False when nothing matched.
fn new_tiles(app: &mut SlideApp, ui: &mut Ui, query: &str, limit: usize, blank: bool) -> bool {
let q = query.trim().to_lowercase();
let themes: Vec<deckcraft_model::Theme> =
deckcraft_model::theme::builtin_themes().into_iter().filter(|th| q.is_empty() || th.name.to_lowercase().contains(&q)).collect();
let sample = q.is_empty() || "sample deck northern lights".contains(&q);
if themes.is_empty() && !sample {
return false;
struct NewTile {
key: NewChoice,
label: String,
detail: String,
theme: Option<deckcraft_model::Theme>,
}
impl NewTile {
fn blank() -> Self {
Self { key: NewChoice::Blank, label: "Blank Presentation".into(), detail: String::new(), theme: None }
}
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(10.0, 10.0);
if blank && tile(ui, "Blank Presentation", None, false).clicked() {
let _ = app.run("file.new", json!({}));
}
let mut shown = 0;
for th in themes {
if shown >= limit {
break;
}
fn theme_tiles(query: &str, limit: usize, blank: bool) -> Vec<NewTile> {
let query = query.trim().to_lowercase();
let mut tiles = Vec::new();
if blank {
tiles.push(NewTile::blank());
}
let themes = deckcraft_model::theme::builtin_themes();
tiles.extend(themes.iter().filter(|theme| query.is_empty() || theme.name.to_lowercase().contains(&query)).take(limit).map(|theme| NewTile {
key: NewChoice::Theme(theme.name.clone()),
label: theme.name.clone(),
detail: String::new(),
theme: Some(theme.clone()),
}));
if (query.is_empty() || "sample deck northern lights".contains(&query)) && tiles.len() - usize::from(blank) < limit {
tiles.push(NewTile {
key: NewChoice::Sample,
label: "Sample deck: Northern Lights".into(),
detail: String::new(),
theme: themes.into_iter().find(|theme| theme.name == "DeckCraft"),
});
}
tiles
}
fn template_tiles(query: &str, limit: usize) -> Vec<NewTile> {
let themes = deckcraft_model::theme::builtin_themes();
deckcraft_engine::templates::matching(query)
.into_iter()
.take(limit)
.map(|starter| NewTile {
key: NewChoice::Template(starter.name.to_owned()),
label: starter.name.to_owned(),
detail: starter.summary.to_owned(),
theme: themes.iter().find(|theme| theme.name == starter.theme).cloned(),
})
.collect()
}
fn show_tiles(app: &mut SlideApp, ui: &mut Ui, label: &'static str, tiles: &[NewTile], large: bool) {
let source = keyed(tiles, |tile: &NewTile| tile.key.clone()).with_text(|tile| Cow::Borrowed(tile.label.as_str()));
let grid = TileGrid::<NewChoice>::new(label)
.select(SelectMode::Single)
.activate(ActivateOn::Click)
.card()
.card_text(CardText::Preset)
.aspect(16.0 / 9.0)
.sizing(Sizing::FillWidth)
.natural_height(true);
let grid = if large { grid.thumb_size(ThumbSize::Large) } else { grid };
let out = grid.show_items(ui, &source, &mut |key, _| {
let Some(tile) = tiles.iter().find(|tile| &tile.key == key) else {
return Tile::new("");
};
let theme = tile.theme.as_ref();
let face = Tile::new(tile.label.clone()).thumb(ThumbAspect::new(16, 9), move |cx, rect| match theme {
Some(theme) => crate::ribbon::paint_theme_tile(cx, rect, theme),
None => {
// The thumbnail depicts document paper, independently of the interface theme.
cx.data_shapes([
egui::Shape::rect_filled(rect, 0.0, egui::Color32::WHITE),
egui::Shape::rect_stroke(rect, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(200)), egui::StrokeKind::Inside),
]);
}
if tile(ui, &th.name, Some(&th), false).clicked() {
let _ = app.run("file.new", json!({"theme": th.name}));
}
shown += 1;
}
if sample && shown < limit {
let th = deckcraft_model::theme::builtin_themes().into_iter().find(|t| t.name == "DeckCraft");
if tile(ui, "Sample deck: Northern Lights", th.as_ref(), false).clicked()
&& let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session)
{
app.set_status(e.to_string());
}
}
});
if matches!(&tile.key, NewChoice::Template(_)) { face.tooltip(tile.detail.clone()) } else { face }
});
true
}
/// Starter decks whose name, summary, theme or a slide title matches `query`, at most `limit` tiles.
fn template_tiles(app: &mut SlideApp, ui: &mut Ui, query: &str, limit: usize) -> bool {
let list = deckcraft_engine::templates::matching(query);
if list.is_empty() {
return false;
}
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(10.0, 10.0);
for starter in list.into_iter().take(limit) {
let theme = deckcraft_model::theme::builtin_themes().into_iter().find(|th| th.name == starter.theme);
if tile(ui, starter.name, theme.as_ref(), false).on_hover_text(starter.summary).clicked() {
let _ = app.run("file.new", json!({"template": starter.name}));
for event in out.response.events {
if let CollectionEvent::Activate(choice) = event {
match choice {
NewChoice::Blank => {
let _ = app.run("file.new", json!({}));
}
NewChoice::Theme(name) => {
let _ = app.run("file.new", json!({"theme": name}));
}
NewChoice::Template(name) => {
let _ = app.run("file.new", json!({"template": name}));
}
NewChoice::Sample => {
if let Err(error) = deckcraft_engine::sample::open_sample(&mut app.session) {
app.set_status(error.to_string());
}
}
}
}
});
true
}
}
/// File name and folder of a recent path, split as text (nothing on disk is read).
/// File name and folder of a recent path, split as text without reading the file.
pub fn split_path(path: &str) -> (String, String) {
let p = std::path::Path::new(path);
let name = p.file_name().and_then(std::ffi::OsStr::to_str).unwrap_or(path).to_string();
@@ -93,228 +135,139 @@ pub fn split_path(path: &str) -> (String, String) {
(name, folder)
}
/// Recent presentations whose name matches `query`, newest first, at most `limit`. Opening one is
/// the user's explicit choice.
fn recent_list(app: &mut SlideApp, ui: &mut Ui, query: &str, limit: usize) {
let t = Tokens::get(ui.ctx());
if app.ui.recent.is_empty() {
dim(ui, "Presentations you open show up here. Use Open to browse for one.");
return;
}
let q = query.trim().to_lowercase();
let list: Vec<String> =
app.ui.recent.iter().filter(|p| q.is_empty() || split_path(p).0.to_lowercase().contains(&q)).take(limit).cloned().collect();
if list.is_empty() {
dim(ui, &format!("No recent presentations match “{}”.", query.trim()));
return;
}
let width = ui.available_width().min(CONTENT_W);
for path in list {
let missing = !app.recent_exists(&path);
let (name, folder) = split_path(&path);
let (rect, resp) = ui.allocate_exact_size(vec2(width, 44.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name));
let p = ui.painter();
if resp.hovered() {
p.rect_filled(rect, CornerRadius::same(3), t.hover);
}
let ink = if missing { t.text_dim } else { t.text };
// The row is as wide as the page's content, which a narrow window clips: keep the mark
// and the remove button inside the visible part of the row.
let visible_right = rect.right().min(ui.clip_rect().right() - 6.0);
{
let p = ui.painter();
icons::paint(p, Rect::from_center_size(pos2(rect.left() + 20.0, rect.center().y), vec2(22.0, 22.0)), Icon::Slide, ink, false);
p.text(pos2(rect.left() + 44.0, rect.center().y - 8.0), Align2::LEFT_CENTER, &name, theme::font(13.0), ink);
p.text(pos2(rect.left() + 44.0, rect.center().y + 9.0), Align2::LEFT_CENTER, &folder, theme::font(11.0), t.text_dim);
// A missing file says so before it is clicked (#172).
if missing {
p.text(pos2(visible_right - 82.0, rect.center().y), Align2::RIGHT_CENTER, "(missing)", theme::font(11.0), t.text_dim);
}
}
let resp = if missing { resp.on_hover_text(format!("{path} — this file can't be found")) } else { resp.on_hover_text(&path) };
// Remove from the list: a real labelled widget on top of the row, with a code-drawn icon
// (a text glyph would need a font that has it).
let x = ui.allocate_rect(
Rect::from_min_max(pos2(visible_right - 32.0, rect.top() + 5.0), pos2(visible_right, rect.bottom() - 5.0)),
Sense::click(),
);
x.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Remove from Recent"));
if x.hovered() {
ui.painter().rect_filled(x.rect, CornerRadius::same(3), t.hover);
}
icons::paint(ui.painter(), Rect::from_center_size(x.rect.center(), vec2(14.0, 14.0)), Icon::Close, t.text_dim, false);
if x.on_hover_text("Remove from Recent").clicked() {
app.forget_recent(&path);
}
if resp.clicked() {
app.open_path_in_background(&path);
}
}
fn recent_files(app: &mut SlideApp, query: &str) -> Vec<RecentFile> {
let query = query.trim().to_lowercase();
// Filtering precedes RecentList's limit: alpha, beta, alpha2 with query alpha and limit two keeps both matches.
let paths: Vec<String> =
app.ui.recent.iter().filter(|path| query.is_empty() || split_path(path).0.to_lowercase().contains(&query)).cloned().collect();
paths
.into_iter()
.map(|path| {
let file = RecentFile::new(&path, split_path(&path).0);
if app.recent_exists(&path) { file } else { file.note("(missing)") }
})
.collect()
}
/// A large square command button (Print, Create PDF, Check for Issues…).
pub(super) fn square_button(ui: &mut Ui, icon: Icon, label: &str, enabled: bool) -> egui::Response {
let t = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(vec2(88.0, 80.0), if enabled { Sense::click() } else { Sense::hover() });
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label));
let p = ui.painter();
p.rect_filled(rect, CornerRadius::same(3), if resp.hovered() && enabled { t.hover } else { t.card });
p.rect_stroke(rect, CornerRadius::same(3), Stroke::new(1.0, if resp.hovered() && enabled { t.accent } else { t.border }), StrokeKind::Inside);
icons::paint(p, Rect::from_center_size(pos2(rect.center().x, rect.top() + 26.0), vec2(26.0, 26.0)), icon, t.text, !enabled);
let ink = if enabled { t.text } else { t.text_faint };
let galley = p.layout(label.to_string(), theme::font(12.0), ink, rect.width() - 8.0);
p.galley(pos2(rect.center().x - galley.size().x / 2.0, rect.top() + 46.0), galley, ink);
resp
}
/// A row of a page's own list on the left (Open's places, Export's tasks).
pub(super) fn place_row(ui: &mut Ui, icon: Icon, label: &str, selected: bool, width: f32) -> egui::Response {
let t = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(vec2(width, 44.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, label));
let p = ui.painter();
if selected {
p.rect_filled(rect, CornerRadius::same(2), t.selected);
p.rect_stroke(rect, CornerRadius::same(2), Stroke::new(1.0, t.border), StrokeKind::Inside);
} else if resp.hovered() {
p.rect_filled(rect, CornerRadius::same(2), t.hover);
}
icons::paint(p, Rect::from_center_size(pos2(rect.left() + 22.0, rect.center().y), vec2(24.0, 24.0)), icon, t.text, false);
p.text(pos2(rect.left() + 46.0, rect.center().y), Align2::LEFT_CENTER, label, theme::font(13.5), t.text);
resp
}
/// A square button with its title and description beside it (Info, Export).
pub(super) fn task(ui: &mut Ui, icon: Icon, button: &str, title: &str, detail: &str, enabled: bool) -> bool {
let t = Tokens::get(ui.ctx());
let mut clicked = false;
ui.horizontal_top(|ui| {
clicked = square_button(ui, icon, button, enabled).clicked();
ui.add_space(12.0);
ui.vertical(|ui| {
ui.add_space(4.0);
ui.label(RichText::new(title).font(theme::font(15.0)).color(t.text));
dim(ui, detail);
});
});
ui.add_space(14.0);
clicked
}
// ---------------------------------------------------------------- pages
/// Home: DeckCraft's mark, new presentations (the first themes, with a link to New) and recent
/// presentations (with a link to Open). The same page is the start screen.
pub(super) fn home(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) {
let t = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::hover());
crate::dialogs::paint_logo(ui.painter(), r);
ui.label(RichText::new("DeckCraft").font(theme::bold(24.0)).color(t.text));
});
ui.add_space(18.0);
ui.horizontal(|ui| {
ui.label(RichText::new("New").font(theme::bold(16.0)).color(t.text));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if arrow_link(ui, "More themes") {
out.page = Some(Page::New);
}
});
});
ui.add_space(6.0);
new_tiles(app, ui, "", 5, true);
ui.add_space(22.0);
ui.horizontal(|ui| {
ui.label(RichText::new("Templates").font(theme::bold(16.0)).color(t.text));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if arrow_link(ui, "More templates") {
out.page = Some(Page::New);
}
});
});
ui.add_space(6.0);
template_tiles(app, ui, "", 3);
ui.add_space(22.0);
ui.horizontal(|ui| {
ui.label(RichText::new("Recent").font(theme::bold(16.0)).color(t.text));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
search(ui, &mut bs.query, "Search for a file", 280.0);
});
});
ui.add_space(6.0);
recent_list(app, ui, &bs.query.clone(), 8);
if app.ui.recent.len() > 8 {
ui.add_space(6.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
if arrow_link(ui, "More presentations") {
out.page = Some(Page::Open);
}
});
}
ui.add_space(30.0);
ui.hyperlink_to("Join the ArtCraft community on Discord", deckcraft_engine::links::DISCORD);
}
/// New: a blank presentation, then every theme and starter template, with a search box.
pub(super) fn new_page(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
let t = Tokens::get(ui.ctx());
if tile(ui, "Blank Presentation", None, true).clicked() {
let _ = app.run("file.new", json!({}));
}
ui.add_space(8.0);
let w = ui.available_width();
let (r, _) = ui.allocate_exact_size(vec2(w, 1.0), Sense::hover());
ui.painter().line_segment([r.left_center(), r.right_center()], Stroke::new(1.0, t.separator));
ui.add_space(14.0);
search(ui, &mut bs.query, "Search for themes and templates", 380.0);
ui.add_space(14.0);
let q = bs.query.clone();
let themes = new_tiles(app, ui, &q, usize::MAX, false);
let templates = if q.trim().is_empty() || !deckcraft_engine::templates::matching(&q).is_empty() {
ui.add_space(18.0);
heading(ui, "Templates");
template_tiles(app, ui, &q, usize::MAX)
fn recent_empty(query: &str) -> String {
if query.trim().is_empty() {
"Presentations you open show up here. Use Open to browse for one.".into()
} else {
false
};
if !themes && !templates {
dim(ui, &format!("No themes or templates match “{}”.", q.trim()));
format!("No recent presentations match “{}”.", query.trim())
}
}
/// Open: Recent and Browse on the left; the recent presentations (with a search box) on the right.
pub(super) fn open_page(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
let t = Tokens::get(ui.ctx());
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(230.0);
place_row(ui, Icon::Recent, "Recent", true, 220.0);
if place_row(ui, Icon::OpenFolder, "Browse", false, 220.0).on_hover_text("Open a presentation from a folder (Ctrl+O)").clicked() {
let _ = app.run("app.openDialog", json!({}));
fn recent_actions(app: &mut SlideApp, actions: Vec<StartAction>) {
for action in actions {
match action {
StartAction::OpenRecent(path) => app.open_path_in_background(&path.to_string_lossy()),
StartAction::RemoveRecent(path) => app.forget_recent(&path.to_string_lossy()),
StartAction::ClearRecent => app.ui.recent.clear(),
#[cfg(not(target_arch = "wasm32"))]
StartAction::RevealRecent(path) if craft::platform::open::CAN_REVEAL => {
// PLAN: assumed SlideApp::reveal_file(&mut self, path: std::path::PathBuf) (shell-w11)
app.reveal_file(path);
}
if app.session.recovery_dir.is_some() {
ui.add_space(24.0);
if ui.button("Recover Unsaved Presentations").clicked() {
match app.run("file.recovery.open", json!({})) {
Ok(v) if v.get("opened").and_then(Value::as_array).is_some_and(|a| a.is_empty()) => {
app.set_status("There are no unsaved presentations to recover");
}
_ => {}
_ => {}
}
}
}
/// Home is also the start screen when no presentation is open.
pub(super) fn home(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &mut Backstage, out: &mut Outcome) {
Row::new().show(ui, |ui, _| {
// PLAN: assumed assets/app-icon/deckcraft-mark.svg (dialogs-w18)
let _ = Picture::svg("DeckCraft", include_bytes!("../../../../assets/app-icon/deckcraft-mark.svg")).show(ui);
let _ = Text::new("DeckCraft").role(TypeRole::Display).show(ui);
});
Section::new("New")
.controls(|ui, _| {
if clicked(&Link::new("More themes").show(ui)) {
out.page = Some(Page::New);
}
})
.show(ui, |ui, _| show_tiles(app, ui, "New presentations", &theme_tiles("", 5, true), false));
Section::new("Templates")
.controls(|ui, _| {
if clicked(&Link::new("More templates").show(ui)) {
out.page = Some(Page::New);
}
})
.show(ui, |ui, _| show_tiles(app, ui, "Starter templates", &template_tiles("", 3), false));
let files = recent_files(app, &bs.query);
let empty = recent_empty(&bs.query);
let shown = RecentList::new(&files)
.max_recent(8)
.empty(empty)
.controls(|ui, _| {
let _ = TextField::search("Search for a file", Bind::bound(&mut bs.query)).show(ui);
})
.show(ui);
recent_actions(app, shown.actions);
if app.ui.recent.len() > 8 && clicked(&Link::new("More presentations").show(ui)) {
out.page = Some(Page::Open);
}
let _ = Link::new("Join the ArtCraft community on Discord").url(deckcraft_engine::links::DISCORD).show(ui);
}
/// A blank presentation, every matching theme and the starter templates.
pub(super) fn new_page(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &mut Backstage) {
show_tiles(app, ui, "Blank presentation", &[NewTile::blank()], true);
let _ = Divider::horizontal().show(ui);
let _ = TextField::search("Search for themes and templates", Bind::bound(&mut bs.query)).show(ui);
let themes = theme_tiles(&bs.query, usize::MAX, false);
let templates = template_tiles(&bs.query, usize::MAX);
show_tiles(app, ui, "Themes", &themes, false);
if bs.query.trim().is_empty() || !templates.is_empty() {
Section::new("Templates").show(ui, |ui, _| show_tiles(app, ui, "Starter templates", &templates, false));
}
if themes.is_empty() && templates.is_empty() {
let _ = Text::new(format!("No themes or templates match “{}”.", bs.query.trim())).shade(Shade::Muted).show(ui);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Place {
Recent,
Browse,
}
/// The places to open from and the full list of matching recent presentations.
pub(super) fn open_page(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &mut Backstage) {
Row::new().fill_width().show(ui, |ui, _| {
Stack::new().least_width(LeastWidth::SideMenu).show(ui, |ui, _| {
let places = [Place::Recent, Place::Browse];
let source = keyed(&places, |place: &Place| *place);
let shown = List::new("Open from")
.select(SelectMode::Single)
.selection(Bind::given(Selection::single(Place::Recent)))
.activate(ActivateOn::Click)
.sizing(Sizing::FillWidth)
.natural_height(true)
.show_items(ui, &source, &mut |place, _| match place {
Place::Recent => ListRow::new("Recent").icon(Icon::Recent.id().into()),
Place::Browse => ListRow::new("Browse").icon(Icon::OpenFolder.id().into()),
});
for event in shown.events {
if matches!(event, CollectionEvent::Activate(Place::Browse)) {
let _ = app.run("app.openDialog", json!({}));
}
}
if app.session.recovery_dir.is_some() && clicked(&Button::new("Recover Unsaved Presentations").show(ui)) {
match app.run("file.recovery.open", json!({})) {
Ok(value) if value.get("opened").and_then(Value::as_array).is_some_and(|opened| opened.is_empty()) => {
app.set_status("There are no unsaved presentations to recover");
}
_ => {}
}
}
});
let h = ui.available_height().max(320.0);
let (r, _) = ui.allocate_exact_size(vec2(1.0, h), Sense::hover());
ui.painter().line_segment([r.center_top(), r.center_bottom()], Stroke::new(1.0, t.separator));
ui.add_space(24.0);
ui.vertical(|ui| {
search(ui, &mut bs.query, "Search for a file", 380.0);
ui.add_space(12.0);
heading(ui, "Presentations");
let q = bs.query.clone();
recent_list(app, ui, &q, usize::MAX);
let _ = Divider::vertical().show(ui);
Stack::new().fill_width().show(ui, |ui, _| {
let _ = TextField::search("Search for a file", Bind::bound(&mut bs.query)).show(ui);
let files = recent_files(app, &bs.query);
let shown = RecentList::new(&files).heading("Presentations").empty(recent_empty(&bs.query)).show(ui);
recent_actions(app, shown.actions);
});
});
}
File diff suppressed because it is too large. Load diff