From 8c2363d92624e6fbaa3cdc6c90c9d6efdfb2e6be Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:25 -0500 Subject: [PATCH] pdf-chrome-w10: net change of 3 commits - pdf-chrome-w10: written from its sheet - pdf-chrome-w10: repair 1 - pdf-chrome-w10: review fixes (review-1) --- crates/ui-egui/src/chrome.rs | 1092 ++--------------- crates/ui-egui/src/chrome/mode_bar.rs | 108 ++ .../ui-egui/src/platform/window_controls.rs | 462 ------- crates/ui-egui/src/widgets.rs | 1079 ---------------- crates/ui-egui/src/widgets/icon_data.rs | 196 --- crates/ui-egui/src/widgets/icons.rs | 200 --- crates/ui-egui/tests/it/min_window.rs | 37 +- crates/ui-egui/tests/it/theme_button.rs | 55 - 8 files changed, 194 insertions(+), 3035 deletions(-) create mode 100644 crates/ui-egui/src/chrome/mode_bar.rs delete mode 100644 crates/ui-egui/src/platform/window_controls.rs delete mode 100644 crates/ui-egui/src/widgets.rs delete mode 100644 crates/ui-egui/src/widgets/icon_data.rs delete mode 100644 crates/ui-egui/src/widgets/icons.rs delete mode 100644 crates/ui-egui/tests/it/theme_button.rs diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 4cc264e7dc..f3ddd9945b 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -1,883 +1,82 @@ -//! Window chrome: tab strip (with the integrated macOS title bar), mode bar, right rail. +//! Window composition: the shell's title bar, mode bar, view rail, dock and page area. -use craft_ui::panes::{Rail, RailItem, RailRequest}; -use egui::{Align, Color32, CornerRadius, Layout, Rect, Sense, Stroke, vec2}; +use craft::behavior::IconId; +use craft::keymap::CommandRef; +use craft::menu::ThemeChoice; +use craft::theme::ModeChoice; +use craft::ui::buttons::{Button, IconButton}; +use craft::ui::contract::{Bind, Outcome as _, Props as _, Show as _, ShowContainer as _}; +use craft::ui::menu::{Menu, MenuItem}; +use craft::ui::runtime::env::WindowKey; +use craft::ui::shell::{AppShell, Slot, Title, TitleBar}; -use crate::canvas::{DocView, Fit, PageLayout}; -use crate::panes::{Place, TabDrop}; -use crate::tab_context::Action; -use crate::theme::{self, ThemePreference, Tokens}; -use crate::{Dialog, Mode, PdfCraftApp, PropsTab, RightPanel, icons, widgets, window_controls}; +use crate::panes::Place; +use crate::{PdfCraftApp, side_panels}; -/// Height of the tab strip when it doubles as the macOS title bar (#789). AppKit draws the traffic -/// lights itself, centred in the standard 28 pt title-bar band at the top of the window, and moving -/// them takes AppKit calls the workspace forbids (`unsafe`). So on macOS the strip is that band: -/// the lights sit vertically centred in it, and the controls beside them shrink to fit, as in -/// WordCraft (storytold/wordcraft#255). -pub const MAC_TITLE_BAR: f32 = 28.0; -/// The traffic lights as AppKit lays them out: button diameter, centre-to-centre pitch and the -/// first button's left edge (8–10 pt depending on the macOS version; the larger value keeps the -/// gap after them from shrinking). -const MAC_LIGHT: f32 = 12.0; -const MAC_LIGHT_PITCH: f32 = 20.0; -const MAC_LIGHTS_LEFT: f32 = 10.0; -/// Where the strip's content starts to the right of the traffic lights: the end of the three -/// lights plus the same gap the lights keep from the top of the window. -pub const MAC_CONTENT_LEFT: f32 = MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT + (MAC_TITLE_BAR - MAC_LIGHT) / 2.0; -/// The strip and its controls everywhere else. -const TAB_STRIP: f32 = 38.0; -const TAB_HEIGHT: f32 = 30.0; -const STRIP_BUTTON: f32 = 28.0; +mod mode_bar; -/// Draw the window's tab strip: home and open controls, shrinkable and scrollable document tabs with drag -/// reordering, and platform window controls. -pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - // macOS: the strip is the 28 pt title bar, so the traffic lights are centred in it; tabs and - // buttons shrink to keep a margin above and below. - let mac = cfg!(target_os = "macos") && app.integrated_titlebar; - let left = if mac { MAC_CONTENT_LEFT as i8 } else { 8 }; - let (tab_h, button) = if mac { (MAC_TITLE_BAR - 2.0, 24.0) } else { (TAB_HEIGHT, STRIP_BUTTON) }; - egui::Panel::top("tab_strip") - .exact_size(if mac { MAC_TITLE_BAR } else { TAB_STRIP }) - .frame(egui::Frame::NONE.fill(t.titlebar).inner_margin(egui::Margin { left, right: 10, top: 0, bottom: 0 })) - .show(ui, |ui| { - let full = ui.max_rect(); - app.panes.main_strip = Some(full); - let drag = ui.interact(full, ui.scope_id().with("titledrag"), Sense::click_and_drag()); - if drag.drag_started() { - window_controls::desktop_grab(ui.ctx(), egui::ViewportCommand::StartDrag); - } - if drag.double_clicked() { - let max = ui.ctx().input(|i| i.viewport().maximized.unwrap_or(false)); - ui.ctx().send_viewport_cmd(egui::ViewportCommand::Maximized(!max)); - } - // GNOME on Wayland: the strip is the header bar, with the window buttons at its ends. - let fullscreen = ui.ctx().input(|i| i.viewport().fullscreen.unwrap_or(false)); - let controls = app - .window_controls - .clone() - .filter(|_| app.draws_window_frame() && !fullscreen) - .unwrap_or_else(|| window_controls::Layout { left: Vec::new(), right: Vec::new() }); - ui.horizontal_centered(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - if !controls.left.is_empty() { - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - window_controls::buttons(ui, &controls.left); - }); - ui.add_space(window_controls::SIDE_GAP - 4.0); - } - if icons::button(ui, "house", button, app.active.is_none() && !app.combine_showing(), tl!("Home")).clicked() { - app.active = None; - app.combine_tab.focused = false; - } - // Reserve the three icon buttons, Discord and their gaps outside the scrolling tabs. - let controls_width = ui.fonts_mut(|f| f.layout_no_wrap("Discord".into(), theme::medium(13.0), t.text).size().x) - + 3.0 * button - + 54.0 - + window_controls::width(&controls.right); - // Open stays in sight after the tabs: its icon, text and padding, and the gaps around it. - let open_width = ui.fonts_mut(|f| f.layout_no_wrap(tl!("Open").into(), theme::medium(13.0), t.text).size().x) + 38.0 + 12.0; - let mut tabs_width = (ui.available_width() - controls_width - open_width).max(0.0); - // Tabs shrink to share the strip (names end in "…") and scroll only once they reach - // their narrowest; then arrows either side say so and step through them. - let mut natural: Vec = Vec::with_capacity(app.views.len() + 1); - // (The main pane's tabs: split view's second pane has a strip of its own.) - for i in app.tabs_in(Place::Main) { - if let Some(name) = crate::canvas::tab_label(app, i) { - natural.push(tab_natural_width(ui, &t, &name)); - } - } - if app.combine_tab.open { - natural.push(tab_natural_width(ui, &t, tl!("Combine files"))); - } - let gap = ui.spacing().item_spacing.x; - let overflow = tabs_overflow(&natural, tabs_width, gap, TAB_MIN_WIDTH); - if overflow { - tabs_width = (tabs_width - 2.0 * (TAB_ARROW + gap)).max(0.0); - } - let cap = tab_cap(&natural, tabs_width, gap, TAB_MIN_WIDTH); - // Where the tabs were scrolled to last frame, and how far they can go. - let scroll_id = ui.scope_id().with("tab_scroll"); - let (offset, max_offset) = ui.data(|d| d.get_temp::<(f32, f32)>(scroll_id)).unwrap_or((0.0, 0.0)); - let mut scroll_to = None; - if overflow && arrow(ui, "chevron-left", offset > 0.5, tl!("Scroll tabs left")) { - scroll_to = Some((offset - (TAB_MIN_WIDTH + gap)).max(0.0)); - } - // Keyed by document, not index: a tab dragged past the active one moves it without - // the strip jumping to it. - let state = (app.active_ids().map(|(_, id)| id), app.views.len(), app.combine_showing()); - let changed = ui.data_mut(|data| { - let id = ui.scope_id().with("active_tab"); - let changed = data.get_temp::<(Option, usize, bool)>(id) != Some(state); - data.insert_temp(id, state); - changed - }); - let mut action = None; - let mut close = None; - // The pointer's x while a tab is dragged, for scrolling at the strip's edges. - let mut drag_x = None; - ui.scope(|ui| { - ui.style_mut().always_scroll_the_only_direction = true; - let mut area = egui::ScrollArea::horizontal().id_salt("document_tabs").max_width(tabs_width).auto_shrink([true, true]); - if let Some(x) = ui.data_mut(|d| d.remove_temp::(scroll_id.with("to"))) { - area = area.horizontal_scroll_offset(x); - } - let out = area.show(ui, |ui| { - ui.horizontal_centered(|ui| { - // Each document tab's index and rect, and the one being dragged - // (with whether it was just released). - let mut slots = Vec::with_capacity(app.views.len()); - let mut dragged = None; - for i in app.tabs_in(Place::Main) { - let Some(doc) = app.session.get(app.views[i].id) else { continue }; - let Some(name) = crate::canvas::tab_label(app, i) else { continue }; - let dirty = doc.dirty; - // A tab showing the document's title names its file on hover. - let file = (name != doc.name).then_some(doc.name.as_str()); - let response = tab( - ui, - TabSpec { - id: ui.scope_id().with(("document-tab", app.views[i].id)), - theme: &t, - icon: "file-text", - name: &name, - file, - dirty, - active: app.pane_front(Place::Main) == Some(i), - index: i, - cap, - height: tab_h, - draggable: true, - }, - &mut close, - ); - slots.push((i, response.rect)); - if response.dragged() || response.drag_stopped() { - dragged = Some((i, response.drag_stopped())); - } - if changed && app.active == Some(i) && !app.combine_showing() { - response.scroll_to_me(Some(Align::Center)); - } - response.context_menu(|ui| tab_menu(app, ui, i, &mut action)); - if response.clicked() { - app.active = Some(i); - } - // A middle click closes the tab, as in Acrobat and browsers (#1853); - // unsaved changes ask first, as the close button does. - if response.middle_clicked() { - close = Some(i); - } - } - drag_x = tab_drag(app, ui, &slots, dragged, Place::Main, close.is_some() || action.is_some()); - if let Some(i) = close - && let Some(view) = app.views.get(i) - { - action.get_or_insert(Action::Close(view.view_key())); - } - if let Some(action) = action { - app.tab_action(action); - } - if app.combine_tab.open { - // After the document tabs; its index can't clash with theirs. - let mut close = None; - let response = tab( - ui, - TabSpec { - id: ui.scope_id().with("combine-tab"), - theme: &t, - icon: "files", - name: tl!("Combine files"), - file: None, - dirty: false, - active: app.combine_showing(), - index: usize::MAX, - cap, - height: tab_h, - draggable: false, - }, - &mut close, - ); - if changed && app.combine_showing() { - response.scroll_to_me(Some(Align::Center)); - } - if response.clicked() { - app.open_combine_tab(); - } - if close.is_some() || response.middle_clicked() { - app.close_combine_tab(); - } - } - }); - }); - let max = (out.content_size.x - out.inner_rect.width()).max(0.0); - ui.data_mut(|d| d.insert_temp(scroll_id, (out.state.clamped_offset().x, max))); - // A tab dragged to either edge of a strip that scrolls brings the hidden tabs in. - if let Some(x) = drag_x - && max > 0.0 - { - let step = if x < out.inner_rect.left() + TAB_DRAG_EDGE { - -TAB_DRAG_STEP - } else if x > out.inner_rect.right() - TAB_DRAG_EDGE { - TAB_DRAG_STEP - } else { - 0.0 - }; - if step != 0.0 { - ui.data_mut(|d| d.insert_temp(scroll_id.with("to"), (out.state.clamped_offset().x + step).clamp(0.0, max))); - ui.ctx().request_repaint(); - } - } - }); - if overflow && arrow(ui, "chevron-right", offset < max_offset - 0.5, tl!("Scroll tabs right")) { - scroll_to = Some((offset + TAB_MIN_WIDTH + gap).min(max_offset)); - } - if let Some(x) = scroll_to { - ui.data_mut(|d| d.insert_temp(scroll_id.with("to"), x)); - ui.ctx().request_repaint(); - } - ui.add_space(4.0); - let tip = crate::commands::command_tip(ui.ctx(), tl!("Open a PDF ({key})"), "file.open"); - if widgets::ghost_button_sized(ui, "plus", tl!("Open"), tab_h).on_hover_text(tip).clicked() { - app.open_dialog(); - } - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if !controls.right.is_empty() { - // Laid out left to right inside the right-to-left run, so they read in - // the desktop's order. - let size = egui::vec2(window_controls::width(&controls.right) - window_controls::SIDE_GAP, window_controls::BUTTON); - ui.allocate_ui_with_layout(size, Layout::left_to_right(Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = 0.0; - window_controls::buttons(ui, &controls.right); - }); - ui.add_space(window_controls::SIDE_GAP - 4.0); - } - if icons::button(ui, "settings", button, false, tl!("Preferences")).clicked() { - app.execute("app.preferences"); - } - let (icon, label) = match app.theme_preference { - ThemePreference::System => ("monitor", tl!("Use system setting")), - ThemePreference::Light => ("sun", tl!("Light gray")), - ThemePreference::Dark => ("moon", tl!("Dark gray")), - }; - let tip = format!("{}: {label}", tl!("Display theme")); - let response = icons::button(ui, icon, button, false, &tip); - // A click cycles System, Light, Dark; a right-click opens the menu. - if response.clicked() { - app.execute(match app.theme_preference { - ThemePreference::System => "view.theme.light", - ThemePreference::Light => "view.theme.dark", - ThemePreference::Dark => "view.theme.system", - }); - } - egui::Popup::context_menu(&response).id(response.id.with("theme_menu")).show(|ui| appearance_menu(app, ui)); - if icons::button(ui, "circle-help", button, false, tl!("Keyboard shortcuts")).clicked() { - app.dialog = Some(Dialog::Shortcuts); - } - // One click to the community, from anywhere in the app. - if widgets::ghost_button_sized(ui, "messages-square", "Discord", tab_h).on_hover_text(pdfcraft_engine::links::DISCORD).clicked() { - app.execute("help.discord"); - } - }); - }); - }); -} - -/// The right-click menu on the title bar's theme button. -fn appearance_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - if ui.button(tl!("Appearance settings…")).clicked() { - app.dialog = Some(Dialog::Preferences); - ui.close(); - } -} - -/// A document tab's right-click menu, in any strip: the choice is left in `action`. -fn tab_menu(app: &PdfCraftApp, ui: &mut egui::Ui, index: usize, action: &mut Option) { - let Some(view) = app.views.get(index) else { return }; - let (tab, id) = (view.view_key(), view.id); - if ui.button(tl!("Close Tab")).clicked() { - *action = Some(Action::Close(tab)); - ui.close(); - } - if ui.add_enabled(!app.closed_tabs.is_empty(), egui::Button::new(tl!("Reopen Closed Tab"))).clicked() { - *action = Some(Action::Reopen); - ui.close(); - } - ui.separator(); - // Split view (view.split-window). - if ui.button(tl!("Split right")).clicked() { - *action = Some(Action::Split { tab, down: false }); - ui.close(); - } - if ui.button(tl!("Split down")).clicked() { - *action = Some(Action::Split { tab, down: true }); - ui.close(); - } - ui.separator(); - let reveal = cfg!(not(target_arch = "wasm32")) && app.session.get(id).is_some_and(|d| d.path.is_some()); - let label = if cfg!(target_os = "macos") { tl!("Reveal in Finder") } else { tl!("Reveal in File Explorer") }; - if ui.add_enabled(reveal, egui::Button::new(label)).clicked() { - *action = Some(Action::Reveal(id)); - ui.close(); - } -} - -/// A tab of `place`'s strip (its tabs `slots`) being dragged (`dragged`: its index, and whether it -/// was let go this frame). It moves the tab along the strip (#1537): a line marks the gap it will -/// land in, and letting go drops it there. Over the right half of a page area that isn't split, or -/// over split view's other pane, a hint shows where it would go instead, and letting go puts it -/// there (`crate::panes`). `busy` is a close or menu choice this frame, which wins. Returns the -/// pointer's x while the tab moves along the strip, for scrolling at the strip's edges. -fn tab_drag(app: &mut PdfCraftApp, ui: &egui::Ui, slots: &[(usize, Rect)], dragged: Option<(usize, bool)>, place: Place, busy: bool) -> Option { - let (from, released) = dragged?; - let pos = ui.ctx().pointer_latest_pos()?; - match app.drop_target(pos, place) { - TabDrop::Strip => { - let x = pos.x; - let to = drop_index(slots, from, x); - if released { - if !busy { - app.move_tab_in_strip(from, slots, to); - } - return None; - } - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - if let Some(marker) = drop_marker(slots, from, to, ui.spacing().item_spacing.x) { - let t = Tokens::get(ui.ctx()); - let span = slots.first().map_or(ui.max_rect().y_range(), |(_, r)| r.y_range()); - // In front of the first tab the gap lies outside the scroll area's clip rect - // (#2225): keep the whole line inside it. - let clip = ui.clip_rect(); - let marker = marker.clamp(clip.left() + 1.0, (clip.right() - 1.0).max(clip.left() + 1.0)); - ui.painter().vline(marker, span.shrink(4.0), Stroke::new(2.0, t.accent)); - } - Some(x) - } - target => { - if !released { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - app.panes.drop_hint = app.drop_hint_rect(target); - } else if !busy { - app.drop_tab(from, target); - } - None - } - } -} - -/// The tab strip of split view's second pane, in `strip`: its tabs share the width (no scrolling), -/// and are clicked, closed, moved along and dragged to the other pane as in the main strip. -pub(crate) fn pane_tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, strip: Rect, place: Place) { - let t = Tokens::get(ui.ctx()); - ui.painter().rect_filled(strip, 0.0, t.titlebar); - ui.painter().hline(strip.x_range(), strip.bottom() - 0.5, Stroke::new(1.0, t.divider)); - let tabs = app.tabs_in(place); - let front = app.pane_front(place); - let inner = Rect::from_min_max(strip.min + vec2(6.0, 2.0), strip.max - vec2(6.0, 0.0)); - let mut row = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(Layout::left_to_right(Align::Max)).id_salt(("tab-row", place))); - row.spacing_mut().item_spacing.x = 4.0; - let natural: Vec = tabs.iter().filter_map(|&i| crate::canvas::tab_label(app, i)).map(|name| tab_natural_width(&row, &t, &name)).collect(); - let cap = tab_cap(&natural, row.available_width(), 4.0, TAB_MIN_WIDTH); - let mut close = None; - let mut action = None; - let mut slots = Vec::with_capacity(tabs.len()); - let mut dragged = None; - for &i in &tabs { - let Some(view) = app.views.get(i) else { continue }; - let Some(doc) = app.session.get(view.id) else { continue }; - let Some(name) = crate::canvas::tab_label(app, i) else { continue }; - let dirty = doc.dirty; - let file = (name != doc.name).then(|| doc.name.clone()); - let id = row.scope_id().with(("pane-tab", view.view_key())); - let spec = TabSpec { - id, - theme: &t, - icon: "file-text", - name: &name, - file: file.as_deref(), - dirty, - active: front == Some(i), - index: i, - cap, - height: inner.height(), - draggable: true, - }; - let response = tab(&mut row, spec, &mut close); - slots.push((i, response.rect)); - if response.dragged() || response.drag_stopped() { - dragged = Some((i, response.drag_stopped())); - } - response.context_menu(|ui| tab_menu(app, ui, i, &mut action)); - if response.clicked() { - app.active = Some(i); - app.combine_tab.focused = false; - } - // A middle click closes the tab, as in the main strip (#1853). - if response.middle_clicked() { - close = Some(i); - } - } - tab_drag(app, &row, &slots, dragged, place, close.is_some() || action.is_some()); - if let Some(i) = close - && let Some(view) = app.views.get(i) - { - action.get_or_insert(Action::Close(view.view_key())); - } - if let Some(action) = action { - app.tab_action(action); - } -} - -/// A tab's chrome around its name: the icon on the left, the close button on the right. -const TAB_CHROME: f32 = 64.0; -/// The narrowest a tab shrinks to before the strip scrolls: room for most of a name. -const TAB_MIN_WIDTH: f32 = 180.0; -/// The arrows either side of tabs that don't fit. -const TAB_ARROW: f32 = 24.0; - -/// Whether tabs of `natural` widths, `gap` apart, are wider than `budget` even at `min` each. -fn tabs_overflow(natural: &[f32], budget: f32, gap: f32, min: f32) -> bool { - let narrowest: f32 = natural.iter().map(|w| w.min(min)).sum(); - narrowest + gap * natural.len().saturating_sub(1) as f32 > budget -} - -/// How close to either end of a scrolling strip a dragged tab scrolls it, and how far per frame. -const TAB_DRAG_EDGE: f32 = 24.0; -const TAB_DRAG_STEP: f32 = 8.0; - -/// Where the tab at `from` lands when dropped with the pointer at `x`: past every other tab -/// whose centre is left of the pointer. `slots` are the tabs' indices and rects, in order. -fn drop_index(slots: &[(usize, Rect)], from: usize, x: f32) -> usize { - slots.iter().filter(|(i, r)| *i != from && r.center().x < x).count() -} - -/// The x of the line marking where the tab at `from` drops at `to`: in the gap before the other -/// tab it lands in front of, or after the last. `None` when it would stay where it is. -fn drop_marker(slots: &[(usize, Rect)], from: usize, to: usize, gap: f32) -> Option { - if slots.iter().position(|(i, _)| *i == from) == Some(to) { - return None; - } - let mut others = slots.iter().filter(|(i, _)| *i != from).map(|(_, r)| r); - match to.checked_sub(1) { - None => others.next().map(|r| r.left() - gap / 2.0), - Some(before) => others.nth(before).map(|r| r.right() + gap / 2.0), - } -} - -/// A scroll arrow beside the tabs; dimmed (and inert) at its end. True when clicked. -fn arrow(ui: &mut egui::Ui, icon: &str, enabled: bool, tip: &str) -> bool { - ui.add_enabled_ui(enabled, |ui| icons::button(ui, icon, TAB_ARROW, false, tip)).inner.clicked() -} - -/// A tab name, at most 28 characters (longer names end in "…"). -fn tab_name(name: &str) -> String { - if name.chars().count() > 28 { format!("{}…", name.chars().take(27).collect::()) } else { name.to_string() } -} - -/// The width a tab takes when nothing has to shrink. -fn tab_natural_width(ui: &egui::Ui, t: &Tokens, name: &str) -> f32 { - let label = tab_name(name); - ui.fonts_mut(|f| f.layout_no_wrap(label, theme::regular(13.0), t.text).size().x) + TAB_CHROME -} - -/// The widest any tab may be so that tabs of `natural` widths, `gap` apart, fit in `budget`: -/// narrow tabs keep their width and the rest share what is left equally (as browsers do). -/// `None` when every tab fits as it is; never below `min` (then the strip scrolls). -fn tab_cap(natural: &[f32], budget: f32, gap: f32, min: f32) -> Option { - let n = natural.len(); - if n == 0 { - return None; - } - let mut left = budget - gap * (n - 1) as f32; - if natural.iter().sum::() <= left { - return None; - } - let mut sorted = natural.to_vec(); - sorted.sort_by(f32::total_cmp); - for (k, w) in sorted.iter().enumerate() { - let share = left / (n - k) as f32; - if *w > share { - return Some(share.max(min)); - } - left -= w; - } - None -} - -/// Draw one tab with its icon, elided label, close button and unsaved dot; records a close request and -/// returns the tab response for drag handling. -struct TabSpec<'a> { - id: egui::Id, - theme: &'a Tokens, - icon: &'a str, - name: &'a str, - file: Option<&'a str>, - dirty: bool, - active: bool, - index: usize, - cap: Option, - height: f32, - draggable: bool, -} - -fn tab(ui: &mut egui::Ui, spec: TabSpec<'_>, close: &mut Option) -> egui::Response { - let TabSpec { id, theme: t, icon, name, file, dirty, active, index, cap, height, draggable } = spec; - let font = theme::regular(13.0); - let mut label = tab_name(name); - // A shrunk tab shows as much of its name as fits (the tooltip has all of it). - if let Some(cap) = cap { - let room = (cap - TAB_CHROME).max(0.0); - label = crate::panels::ellipsized_prefix(&label, |s| crate::bidi::layout_ltr(ui, s.to_owned(), font.clone(), t.text).size().x <= room); - } - // Logical text, laid out explicitly left to right: the fork shapes and reorders it once, - // and an Arabic file name keeps its extension at the visual end. AccessKit names stay logical. - let label_color = if active { t.text } else { t.text_muted }; - let label_galley = crate::bidi::layout_ltr(ui, label.clone(), font.clone(), label_color); - let text_w = label_galley.size().x; - let width = cap.map_or(text_w + TAB_CHROME, |cap| (text_w + TAB_CHROME).min(cap)); - // Full strip height so the active tab sits on the mode bar instead of floating in the title bar. - let height = ui.available_height().max(height); - let (rect, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover()); - let a11y = if dirty { format!("{name} (edited)") } else { name.to_string() }; - let sense = if draggable { Sense::click_and_drag() } else { Sense::click() }; - let resp = craft_ui::tabs::Tab::new(id, &a11y, active).sense(sense).focus_stroke(Stroke::new(1.0, t.accent)).show_at(ui, rect, |ui, resp| { - let press = theme::Press::track(ui, resp); - let bg = if active { - press.fill(t.chrome, t.chrome.lerp_to_gamma(t.hover, 0.65), t.hover) - } else { - press.fill(Color32::TRANSPARENT, t.hover, t.pressed) - }; - if bg.a() > 0 { - ui.painter().rect_filled(rect, CornerRadius { nw: 7, ne: 7, sw: 0, se: 0 }, bg); - } - icons::paint( - ui, - Rect::from_min_size(rect.min + vec2(6.0, (height - 16.0) / 2.0), vec2(16.0, 16.0)), - icon, - 15.0, - if active { t.accent } else { t.text_muted }, - ); - ui.painter().galley(rect.min + vec2(28.0, (rect.height() - label_galley.size().y) / 2.0), label_galley.clone(), label_color); - }); - let x_rect = Rect::from_center_size(rect.right_center() - vec2(16.0, 0.0), vec2(20.0, 20.0)); - let x = ui.interact(x_rect, id.with("close"), Sense::click()); - let x_press = theme::Press::track(ui, &x); - x_press.wash(ui, x_rect, 4, false); - // Unsaved changes: a dot where the close button sits, until the tab is hovered. - if dirty && !resp.hovered() && !x.hovered() { - ui.painter().circle_filled(x_rect.center(), 4.0, if active { t.text } else { t.text_muted }); - } else if active || resp.hovered() || x.hovered() { - icons::paint(ui, x_rect.translate(x_press.offset()), "x", 13.0, t.text_muted); - } - if theme::hand(x).clicked() { - *close = Some(index); - } - let shown = match file { - Some(file) => format!("{name}\n{file}"), - None => name.to_string(), - }; - theme::hand(resp).on_hover_text(if dirty { crate::i18n::fmt(tl!("{name} — unsaved changes"), &[("name", &shown)]) } else { shown }) -} - -/// Width the print, save and info buttons and their gaps take in the mode bar: three buttons, the -/// 4 pt `item_spacing` after each of them (three gaps, not two), and the 8 pt spacer. -const MODE_BAR_RIGHT: f32 = 3.0 * 32.0 + 3.0 * 4.0 + 8.0; -/// Narrowest search field the mode bar shows; below it the field becomes an icon button. -const MODE_BAR_SEARCH_MIN: f32 = 140.0; - -pub fn mode_bar(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - // The document in the active tab may hide the menu or the tools (`crate::viewer_prefs`). +/// Compose the window: title bar, mode bar, view rail and the dock, whose document panel holds the +/// pages. +/// +/// The shell carries out every screen-mode change; the mode it ends the pass with goes back to the +/// app, which does the presentation work in one place. +pub(crate) fn shell(app: &mut PdfCraftApp, ui: &mut egui::Ui) { let hidden = app.hidden_interface(); - egui::Panel::top("mode_bar") - .exact_size(48.0) - .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 0)).stroke(Stroke::new(1.0, t.divider))) - .show(ui, |ui| { - ui.horizontal_centered(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - // The menus, unless the native macOS menu bar has them or the document hides them. - if app.native_menu.is_none() && !hidden.menubar { - app.menu_bar_ui(ui); - ui.add_space(6.0); - ui.painter().vline(ui.cursor().left(), ui.max_rect().y_range().shrink(12.0), Stroke::new(1.0, t.divider)); - ui.add_space(10.0); - } - if hidden.toolbar { - return; - } - // Acrobat's mode bar has no Read tab: reading is what the viewer does with no tool - // in use. Read mode (the panes hidden) stays a View command and a default workspace. - let modes = [(Mode::AllTools, "All tools"), (Mode::Edit, "Edit"), (Mode::Convert, "Convert"), (Mode::Sign, "E-Sign")]; - // What the right side needs (three 32 px buttons, gaps) and the least search box worth showing. - let avail = ui.available_width(); - let tabs_w: f32 = modes.iter().map(|(_, l)| widgets::mode_tab_width(ui, tl!(*l))).sum::() + 2.0 * (modes.len() as f32 - 1.0); - let inline_tabs = avail >= tabs_w + MODE_BAR_RIGHT + MODE_BAR_SEARCH_MIN; - if inline_tabs { - for (mode, label) in modes { - if widgets::mode_tab(ui, tl!(label), app.mode == mode).clicked() { - app.switch_mode(mode, true); - } - } - } else { - // Narrow window: the modes fold into one menu named after the current one. - // Read is not one of the four choices but can be active (View command): name it too. - let current = if app.mode == Mode::Read { - tl!("Read") - } else { - tl!(modes.iter().find(|(m, _)| *m == app.mode).map_or("All tools", |(_, l)| *l)) - }; - let resp = widgets::ghost_button(ui, "chevron-down", current); - egui::Popup::menu(&resp).show(|ui| { - ui.set_min_width(160.0); - for (mode, label) in modes { - if ui.add(egui::Button::selectable(app.mode == mode, tl!(label))).clicked() { - app.switch_mode(mode, true); - } - } - }); - } - let left = ui.available_width(); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - let has_doc = app.active.is_some(); - ui.add_enabled_ui(has_doc, |ui| { - let tip = crate::commands::command_tip(ui.ctx(), tl!("Print ({key})"), "print.dialog"); - // A document that forbids printing says so here, before the dialog (#2669). - let may_print = !has_doc || pdfcraft_engine::commands::command("print.dialog").is_some_and(|c| app.command_enabled(c)); - let mut print = ui.add_enabled_ui(may_print, |ui| icons::button(ui, "printer", 32.0, false, &tip)).inner; - if !may_print { - print = print.on_disabled_hover_text(crate::print_refused()); - } - if print.clicked() { - app.run_command("print.dialog"); - } - let tip = crate::commands::command_tip(ui.ctx(), tl!("Save ({key})"), "file.save"); - if icons::button(ui, "save", 32.0, false, &tip).clicked() { - app.run_command("file.save"); - } - let tip = crate::commands::command_tip(ui.ctx(), tl!("Document properties ({key})"), "file.properties"); - if icons::button(ui, "info", 32.0, false, &tip).clicked() { - app.dialog = Some(Dialog::Properties(PropsTab::Description)); - } - }); - ui.add_space(8.0); - let search_w = (left - MODE_BAR_RIGHT).clamp(0.0, 260.0); - let opened = if search_w >= MODE_BAR_SEARCH_MIN { - widgets::search_box(ui, tl!("Find tools and commands"), search_w).clicked() - } else { - // Too narrow for the field: a button opens the same command search. - icons::button(ui, "search", 32.0, false, tl!("Find tools and commands")).clicked() - }; - if opened { - app.palette_open = true; - } - }); - }); - }); + let modes_visible = !hidden.mode_bar(app.native_menu.is_some()); + let window_ui = !hidden.window_ui; + let out = AppShell::new(WindowKey::main()) + .screen_mode(Bind::given(app.screen_mode)) + // A presentation shows the page and nothing else, so no reveal brings the bars back. + .allow_reveal(false) + .title_bar(|ui, _, app: &mut PdfCraftApp| title_bar(app, ui)) + .top(Slot::new("modes").visible(modes_visible), |ui, _, app: &mut PdfCraftApp| mode_bar::show(app, ui)) + .end(Slot::new("view-rail").visible(window_ui), |ui, _, app: &mut PdfCraftApp| view_rail::show(app, ui)) + .body(|ui, _, app: &mut PdfCraftApp| side_panels::dock(app, ui)) + .show(ui, app); + // PLAN: assumed `set_screen_mode(&mut self, ScreenMode)` (pdf-shell-w8) + app.set_screen_mode(out.screen_mode); } -/// The size of the rail's page and zoom fields: wide enough for "6400%", the largest zoom, in the -/// 12 pt font, and inside the 45 pt the rail leaves. -const RAIL_FIELD_SIZE: [f32; 2] = [42.0, 22.0]; -/// Padding inside the rail's page and zoom fields. -const RAIL_FIELD_MARGIN: egui::Vec2 = egui::vec2(1.0, 4.0); - -/// A field the rail can type in: boxed, and the same size whatever it holds, so the page and zoom -/// fields match and fit the rail's width. Sized outright: a text field is at least a control wide. -fn rail_field(ui: &mut egui::Ui, t: &Tokens, edit: egui::TextEdit<'_>) -> egui::Response { - egui::Frame::NONE - .fill(t.field) - .stroke(Stroke::new(1.0, t.border)) - .corner_radius(CornerRadius::same(5)) - .show(ui, |ui| { - ui.spacing_mut().interact_size.x = 0.0; - ui.add_sized(RAIL_FIELD_SIZE, edit) - }) - .inner -} - -/// Draw the right tool rail with page navigation, history, zoom, rotation and page-display controls for the -/// active view. -pub fn right_rail(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let Some((index, id)) = app.active_ids() else { return }; - let Some(doc) = app.session.get(id) else { return }; - let has_signatures = doc.is_signed(); - let has_check = app.a11y.report.as_ref().is_some_and(|(d, _)| *d == id); - let (has_comments, has_outline, has_fields, has_layers, has_files) = ( - !doc.info.annotations.is_empty(), - !doc.info.outline.is_empty(), - !doc.info.fields.is_empty(), - !doc.info.layers.is_empty(), - !doc.info.attachments.is_empty(), - ); - let page_count = doc.info.pages.len(); - let labels: Vec = doc.info.pages.iter().map(|p| p.label.clone()).collect(); - let item = |panel: RightPanel, icon: &str, label: &str, marker: Option<&str>| { - let item = RailItem::new(panel, icons::source(icon), tl!(label)).marker(marker.is_some()); - match marker { - Some(marker) => item.marker_label(tl!(marker)), - None => item, - } +/// The title bar: Home, the document tabs and Open, then the community, shortcuts, theme and +/// Preferences buttons. The window's caption buttons are the bar's own. +fn title_bar(app: &mut PdfCraftApp, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + let title = match app.active_ids().and_then(|(_, id)| app.session.get(id)) { + Some(doc) if doc.dirty => Title::unsaved(doc.name.clone()), + Some(doc) => Title::new(doc.name.clone()), + None => Title::new("PdfCraft"), }; - let has = |has: bool, label: &'static str| has.then_some(label); - let mut items = vec![ - item(RightPanel::Comments, "message-square-text", "Comments", has(has_comments, "Has comments")), - item(RightPanel::Bookmarks, "bookmark", "Bookmarks", has(has_outline, "Has bookmarks")), - item(RightPanel::Pages, "files", "Page thumbnails", None), - item(RightPanel::Fields, "text-cursor-input", "Form fields", has(has_fields, "Has form fields")), - item(RightPanel::Layers, "layers", "Layers", has(has_layers, "Has layers")), - item(RightPanel::Attachments, "paperclip", "Attachments", has(has_files, "Has attachments")), - item(RightPanel::Signatures, "signature", "Signatures", has(has_signatures, "Signed")), - ]; - if has_check { - items.push(item(RightPanel::Accessibility, "accessibility", "Accessibility Checker", None)); - } - items.push(item(RightPanel::Tags, "tag", "Tags", None)); - let view = &mut app.views[index]; - let mut page_display = None; - let rail = Rail::new(egui::Id::unique("rail")) - .edge(app.side_panels.rail_edge()) - .width(49.0) - .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(1, 8)).stroke(Stroke::new(1.0, t.divider))) - .show(ui, &items, app.right.as_ref(), |ui| { - // Page navigation cluster at the bottom, a panel of its own so that in a short - // window the buttons above scroll instead of running into it (#3282). - ui.with_layout(Layout::bottom_up(Align::Center), |ui| { - ui.spacing_mut().item_spacing.y = 2.0; - let right = app.side_panels.rail_on_right(); - let dock_tip = if right { tl!("Dock navigation rail on Left") } else { tl!("Dock navigation rail on Right") }; - if icons::button(ui, if right { "panel-left" } else { "panel-right" }, 32.0, false, dock_tip).clicked() { - app.side_panels.rail_side = if right { crate::side_panels::ToolsSide::Left } else { crate::side_panels::ToolsSide::Right }; - } - // Between rotate and zoom, as in Acrobat. Its command runs once `view` is free. - let tip = crate::i18n::fmt(tl!("Page display: {layout}"), &[("layout", tl!(view.layout.label()))]); - let resp = icons::button(ui, view.layout.icon(), 32.0, false, &tip); - page_display = egui::Popup::menu(&resp) - .show(|ui| { - ui.set_min_width(220.0); - rail_view_menu(ui, view) - }) - .and_then(|r| r.inner); - let tip = crate::commands::key_tip(ui.ctx(), tl!("Rotate view clockwise ({key})"), crate::commands::ROTATE_CW); - if icons::button(ui, "rotate-cw", 32.0, false, &tip).clicked() { - view.rotate_view(true); - } - // Not `columns-2` while fitting the page: that is the two-page view's icon. - let fit_icon = if view.fit == Fit::Width { "maximize" } else { "maximize-2" }; - if icons::button(ui, fit_icon, 32.0, false, tl!("Toggle fit page / fit width")).clicked() { - view.fit = if view.fit == Fit::Width { Fit::Page } else { Fit::Width }; - view.goto = Some((view.current, 0.0)); - } - // Out and in side by side right under the zoom field, so they are found with it. - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - // Two buttons across the rail, each leaving a pixel to the rail's edge. - let side = (ui.available_width() / 2.0).floor(); - let tip = crate::commands::key_tip(ui.ctx(), tl!("Zoom out ({key})"), crate::commands::ZOOM_OUT); - if icons::button(ui, "zoom-out", side, false, &tip).clicked() { - view.zoom_step(false); - } - let tip = crate::commands::key_tip(ui.ctx(), tl!("Zoom in ({key})"), crate::commands::ZOOM_IN); - if icons::button(ui, "zoom-in", side, false, &tip).clicked() { - view.zoom_step(true); - } - }); - let id = egui::Id::unique("zoom-input"); - let draft = id.with("draft"); - let mut typed = ui.data(|d| d.get_temp::(draft)).unwrap_or_else(|| format!("{:.0}%", view.zoom * 100.0)); - let edit = egui::TextEdit::singleline(&mut typed) - .id(id) - .align(egui::Align2::CENTER_CENTER) - .font(theme::medium(12.0)) - .text_color(t.text) - .frame(egui::Frame::NONE) - .margin(RAIL_FIELD_MARGIN); - let r = rail_field(ui, &t, edit).on_hover_text(tl!("Zoom — type a percentage and press Enter")); - ui.ctx().accesskit_node_builder(id, |node| node.set_label(tl!("Zoom"))); - if r.gained_focus() { - let mut state = egui::TextEdit::load_state(ui.ctx(), id).unwrap_or_default(); - let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(typed.chars().count())); - state.cursor.set_char_range(Some(all)); - state.store(ui.ctx(), id); - } - if r.has_focus() { - ui.data_mut(|d| d.insert_temp(draft, typed.clone())); - } else { - ui.data_mut(|d| d.remove::(draft)); - if r.lost_focus() - && ui.input(|i| i.key_pressed(egui::Key::Enter)) - && let Some(zoom) = DocView::parse_zoom_percent(&typed) - { - view.set_zoom(zoom); - } - } - ui.add_space(6.0); - if icons::button(ui, "chevron-down", 30.0, false, tl!("Next page")).clicked() { - view.step_page(true); - } - if icons::button(ui, "chevron-up", 30.0, false, tl!("Previous page")).clicked() { - view.step_page(false); - } - // History is distinct from stepping to the adjacent page, and belongs to this tab. - for (forward, icon, label, shortcut, enabled) in [ - (true, "chevron-right", tl!("Next view"), crate::commands::NEXT_VIEW, !view.forward.is_empty()), - (false, "chevron-left", tl!("Previous view"), crate::commands::PREV_VIEW, !view.back.is_empty()), - ] { - let tip = format!("{label} ({})", crate::commands::shortcut_label(ui.ctx(), shortcut)); - if ui.add_enabled_ui(enabled, |ui| icons::button(ui, icon, 30.0, false, &tip)).inner.clicked() { - view.view_history(forward); - } - } - let font = theme::regular(11.0); - let mut position = page_position(view.current, page_count, labels.get(view.current).map_or("", String::as_str)); - if widgets::text_width(ui, &position, &font) > ui.available_width() { - position = page_count.to_string(); - } - // Out of range (an empty document), like `page_position`: "Page 0 of 0", never past the end. - let shown = if view.current < page_count { view.current + 1 } else { page_count }; - let of = crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &shown.to_string()), ("n", &page_count.to_string())]); - ui.label(egui::RichText::new(position).font(font).color(t.text_muted)).on_hover_text(of); - let page_input_id = view.page_input_id(); - // Consume replacement selection once, including when the editor has lost focus. - let reselect = std::mem::take(&mut view.page_input_reselect); - // Navigation updates the idle display, never the text being edited. - if !ui.memory(|m| m.has_focus(page_input_id)) { - view.page_input = view.current_page_label(labels.get(view.current).map(String::as_str)); - } else if reselect { - // The replacement changed the label while egui retained this editor's cursor. - let mut state = egui::TextEdit::load_state(ui.ctx(), page_input_id).unwrap_or_default(); - let end = egui::text::CCursor::new(view.page_input.chars().count()); - state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), end))); - state.store(ui.ctx(), page_input_id); - } - let edit = egui::TextEdit::singleline(&mut view.page_input) - .id(page_input_id) - .align(egui::Align2::CENTER_CENTER) - .font(theme::medium(12.0)) - .frame(egui::Frame::NONE) - .margin(RAIL_FIELD_MARGIN); - let r = rail_field(ui, &t, edit) - .on_hover_text(tl!("Current page — type a page number or label (such as iv) and press Enter")) - .accessible_name(tl!("Current page")); - if r.lost_focus() { - if ui.input(|i| i.key_pressed(egui::Key::Enter)) { - // A page label first (logical page numbers, as Acrobat), then a number. - let typed = view.page_input.clone(); - view.go_to_typed(&typed, &labels); - } - view.page_input = view.current_page_label(labels.get(view.current).map(String::as_str)); - } + let theme_icon = match app.theme_preference { + ModeChoice::System => "monitor", + ModeChoice::Light => "sun", + ModeChoice::Dark => "moon", + }; + let out = TitleBar::new().show_titled( + ui, + title, + |ui, _| { + let home = app.active.is_none() && !app.combine_showing(); + if IconButton::new(IconId::new("house")).label(tl!("Home")).selected(home).show(ui).clicked() { + app.active = None; + app.combine_tab.focused = false; + } + doc_tabs::strip(app, ui, Place::Main); + Button::command("file.open").icon(IconId::new("plus")).show(ui); + }, + |ui, _| { + IconButton::command(IconId::new("messages-square"), "help.discord").show(ui); + IconButton::command(IconId::new("circle-help"), "help.shortcuts").show(ui); + let theme_button = IconButton::command(IconId::new(theme_icon), ThemeChoice::NextMode.command()).show(ui); + let opener = theme_button.response().clone(); + Menu::context(tl!("Appearance"), &opener).show(ui, |ui, _| { + let appearance = CommandRef::with_params("app.preferences", serde_json::json!({ "tab": "appearance" })); + MenuItem::command(appearance).label(tl!("Appearance settings…")).show(ui); }); - }); - match rail.request { - Some(RailRequest::Open(panel)) => app.choose_right_panel(Some(panel)), - Some(RailRequest::Close(_)) => app.choose_right_panel(None), - _ => {} - } - if let Some(id) = page_display { - app.execute(id); + IconButton::command(IconId::new("settings"), "app.preferences").show(ui); + }, + ); + if out.close_requested { + app.request_quit(&ctx); } } @@ -888,72 +87,6 @@ fn page_position(current: usize, count: usize, label: &str) -> String { if label.is_empty() || label == number || current >= count { count.to_string() } else { format!("{number}/{count}") } } -/// The rail's Page display menu: the layouts and the cover page (also View ▸ Page display). -/// Returns the command a click asks for, for the caller to run. -fn page_display_menu(ui: &mut egui::Ui, view: &DocView) -> Option<&'static str> { - let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(tl!("Page display")).color(t.text_faint).small()); - let mut picked = None; - for l in PageLayout::ORDER { - if ui.add(widgets::radio(view.layout == l, tl!(l.label()))).clicked() { - picked = Some(l.command()); - } - } - ui.separator(); - // Continuous scrolling is an independent checkbox over the base layout, as in Acrobat (#752). - let mut continuous = view.continuous(); - if ui.add(widgets::checkbox(&mut continuous, tl!("Continuous scrolling"))).changed() { - picked = Some("view.continuous"); - } - let mut gaps = view.show_page_gaps; - if ui.add(widgets::checkbox(&mut gaps, tl!("Show gaps between pages"))).changed() { - picked = Some("view.page_gaps"); - } - let mut cover = view.cover; - if ui.add_enabled(view.cover_applies(), widgets::checkbox(&mut cover, tl!("Show cover page in two-page view"))).changed() { - picked = Some("view.layout.cover"); - } - if picked.is_some() { - ui.close(); - } - picked -} - -/// The rail's Page display menu: Acrobat's view choices around the page display. Zoom changes -/// apply at once; the command a click asks for is returned for the caller to run. -fn rail_view_menu(ui: &mut egui::Ui, view: &mut DocView) -> Option<&'static str> { - let mut picked = None; - for (id, label) in [("view.fit_width_scrolling", "Fit to width scrolling"), ("view.fit_one_page", "Fit one full page")] { - if ui.button(tl!(label)).clicked() { - picked = Some(id); - } - } - ui.separator(); - if ui.button(tl!("Actual size")).clicked() { - view.set_zoom(1.0); - ui.close(); - } - if ui.button(tl!("Zoom to page level")).clicked() { - view.set_fit(Fit::Page); - ui.close(); - } - if ui.button(tl!("Fit visible")).clicked() { - picked = Some("view.fit_visible"); - } - ui.separator(); - picked = page_display_menu(ui, view).or(picked); - ui.separator(); - for (id, label) in [("view.read_mode", "Read mode"), ("view.full_screen", "Full screen mode")] { - if ui.button(tl!(label)).clicked() { - picked = Some(id); - } - } - if picked.is_some() { - ui.close(); - } - picked -} - #[cfg(test)] mod page_position_tests { use super::page_position; @@ -968,88 +101,3 @@ mod page_position_tests { assert_eq!(page_position(usize::MAX, 3, "x"), "3"); } } - -#[cfg(test)] -mod tab_widths { - use super::{MAC_CONTENT_LEFT, MAC_LIGHT, MAC_LIGHT_PITCH, MAC_LIGHTS_LEFT, MAC_TITLE_BAR, tab_cap}; - - /// Tabs that fit keep their own widths. - #[test] - fn tabs_that_fit_do_not_shrink() { - assert_eq!(tab_cap(&[200.0, 150.0], 400.0, 4.0, 110.0), None); - assert_eq!(tab_cap(&[], 0.0, 4.0, 110.0), None); - } - - /// Too wide: narrow tabs keep their width, the wide ones share the rest equally, and - /// together they fill the strip exactly. - #[test] - fn wide_tabs_share_what_narrow_ones_leave() { - let natural = [120.0, 300.0, 300.0]; - let cap = tab_cap(&natural, 500.0, 4.0, 110.0).expect("must shrink"); - let used: f32 = natural.iter().map(|w| w.min(cap)).sum::() + 2.0 * 4.0; - assert!((used - 500.0).abs() < 0.01, "{cap} uses {used}"); - assert!((cap - 186.0).abs() < 0.01, "{cap}"); - } - - /// Arrows appear only when the tabs can't fit even at their narrowest. - #[test] - fn arrows_only_when_the_narrowest_tabs_overflow() { - use super::tabs_overflow; - assert!(!tabs_overflow(&[250.0; 3], 600.0, 4.0, 180.0), "three shrunk tabs fit"); - assert!(tabs_overflow(&[250.0; 4], 600.0, 4.0, 180.0), "four don't, even at 180"); - assert!(!tabs_overflow(&[100.0; 5], 600.0, 4.0, 180.0), "narrow tabs fit as they are"); - assert!(!tabs_overflow(&[], 0.0, 4.0, 180.0)); - } - - /// Tabs never get narrower than the minimum: past it, the strip scrolls instead. - #[test] - fn tabs_stop_at_their_minimum() { - assert_eq!(tab_cap(&[250.0; 12], 600.0, 4.0, 110.0), Some(110.0)); - assert_eq!(tab_cap(&[250.0; 3], 0.0, 4.0, 110.0), Some(110.0)); - } - - /// Three 100-wide tabs, 4 apart, starting at x = 0. - fn three_slots() -> Vec<(usize, egui::Rect)> { - (0..3).map(|i| (i, egui::Rect::from_min_size(egui::pos2(i as f32 * 104.0, 0.0), egui::vec2(100.0, 30.0)))).collect() - } - - /// A dragged tab lands past every other tab whose centre the pointer has crossed. - #[test] - fn a_dragged_tab_drops_past_the_centres_it_crossed() { - use super::drop_index; - let slots = three_slots(); - // Centres at 50, 154 and 258. - assert_eq!(drop_index(&slots, 0, 10.0), 0, "still over itself"); - assert_eq!(drop_index(&slots, 0, 160.0), 1, "past the middle tab's centre"); - assert_eq!(drop_index(&slots, 0, 900.0), 2, "past the end"); - assert_eq!(drop_index(&slots, 2, -50.0), 0, "before the start"); - assert_eq!(drop_index(&slots, 2, 100.0), 1, "between the first and middle centres"); - assert_eq!(drop_index(&[], 0, 100.0), 0); - } - - /// The drop line sits in the gap the tab will land in, and not at all where it already is. - #[test] - fn the_drop_line_marks_the_gap_and_hides_when_nothing_moves() { - use super::drop_marker; - let slots = three_slots(); - assert_eq!(drop_marker(&slots, 0, 0, 4.0), None); - assert_eq!(drop_marker(&slots, 1, 1, 4.0), None); - // The first tab dropped at the end: after the last tab. - assert_eq!(drop_marker(&slots, 0, 2, 4.0), Some(310.0)); - // The first tab dropped between the middle and the last: in the gap between them. - assert_eq!(drop_marker(&slots, 0, 1, 4.0), Some(206.0)); - // The last tab dropped at the start: before the first tab. - assert_eq!(drop_marker(&slots, 2, 0, 4.0), Some(-2.0)); - assert_eq!(drop_marker(&[], 0, 1, 4.0), None); - } - - #[test] - fn the_mac_title_bar_centres_and_clears_the_traffic_lights() { - // The lights are centred in the bar, and content keeps the same gap after them (#789). - let margin = (MAC_TITLE_BAR - MAC_LIGHT) / 2.0; - let lights_end = MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT; - assert_eq!(MAC_CONTENT_LEFT - lights_end, margin); - // `egui::Margin` is in `i8`. - assert!(MAC_CONTENT_LEFT <= f32::from(i8::MAX)); - } -} diff --git a/crates/ui-egui/src/chrome/mode_bar.rs b/crates/ui-egui/src/chrome/mode_bar.rs new file mode 100644 index 0000000000..ba377c33e7 --- /dev/null +++ b/crates/ui-egui/src/chrome/mode_bar.rs @@ -0,0 +1,108 @@ +//! The top slot: the menus, the mode strip, the document buttons and the command search. + +use std::borrow::Cow; + +use craft::behavior::{DisplayOrder, IconId, ItemSource, SelectionChange}; +use craft::keymap::CommandRef; +use craft::menu::Target; +use craft::ui::bars::{Bar, BarKind}; +use craft::ui::buttons::{CommandSearch, IconButton}; +use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::layout_components::Row; +use craft::ui::menu::HelpEntry; +use craft::ui::patterns::panels::CommandPalette; +use craft::ui::tabs::{Tab, TabKind, TabStrip}; + +use pdfcraft_engine::catalog::{Availability, TOOL_GROUPS}; + +use crate::{Mode, PdfCraftApp}; + +/// The modes the strip offers. Read is a View command, not a tab. +const MODES: [(Mode, &str); 4] = [(Mode::AllTools, "All tools"), (Mode::Edit, "Edit"), (Mode::Convert, "Convert"), (Mode::Sign, "E-Sign")]; + +/// The mode labels, keyed by position. +struct ModeTabs; + +impl DisplayOrder for ModeTabs { + fn len(&self) -> usize { + MODES.len() + } + + fn key(&self, at: usize) -> usize { + at + } + + fn index_of(&self, key: &usize) -> Option { + (*key < MODES.len()).then_some(*key) + } + + fn text(&self, at: usize) -> Option> { + MODES.get(at).map(|(_, label)| Cow::Borrowed(tl!(*label))) + } +} + +impl ItemSource for ModeTabs {} + +/// Draw the menus, the mode strip and the buttons after it, then the command palette over them. +pub(super) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { + let hidden = app.hidden_interface(); + let menus = app.native_menu.is_none() && !hidden.menubar; + Row::new().show(ui, |ui, _| { + if menus { + app.menu_bar_ui(ui); + } + // The document may hide the tools (`crate::viewer_prefs`); the buttons stay. + let shown = MODES.iter().position(|(mode, _)| *mode == app.mode); + Bar::new(tl!("Modes"), BarKind::Tool) + .trailing(|ui, _| { + IconButton::command(IconId::new("printer"), "print.dialog").show(ui); + IconButton::command(IconId::new("save"), "file.save").show(ui); + IconButton::command(IconId::new("info"), "file.properties").show(ui); + CommandSearch::new("view.palette", tl!("Find tools and commands")).show(ui); + }) + .show(ui, |ui, _| { + if hidden.toolbar { + return; + } + let strip = TabStrip::new(tl!("Modes")).kind(TabKind::Text); + let strip = match shown { + Some(at) => strip.shown(at), + None => strip, + }; + let out = strip.show_items(ui, &ModeTabs, &mut |key, _| Tab::new(tl!(MODES[*key % MODES.len()].1))); + for event in out.response.events { + if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event + && let Some((mode, _)) = keys.last().and_then(|at| MODES.get(*at)) + { + app.switch_mode(*mode, true); + } + } + }); + }); + if app.palette_open { + let ctx = ui.ctx().clone(); + let entries = palette_entries(app, &ctx); + CommandPalette::new(tl!("Find tools and commands"), &entries, Bind::bound(&mut app.palette_open)).show(ui); + } +} + +/// What the palette searches: the menus' commands, each ready tool group, and the catalogue items +/// that are not commands of their own. +fn palette_entries(app: &PdfCraftApp, ctx: &egui::Context) -> Vec { + let mut entries = app.menu_bar(ctx).help_entries(Target::current(), &crate::menus::layout_options(), None); + for group in TOOL_GROUPS { + if group.availability == Availability::Ready { + // PLAN: assumed `tool.group` reads a `group` parameter (pdf-chrome-w9) + let select = CommandRef::with_params("tool.group", serde_json::json!({ "group": group.id })); + entries.push(HelpEntry::new(select, tl!(group.label)).with_path([tl!("Tool")])); + } + for section in group.sections { + for item in section.items { + if item.availability == Availability::Ready && pdfcraft_engine::commands::command(item.command).is_none() { + entries.push(HelpEntry::new(item.command, tl!(item.label)).with_path([tl!(group.label)])); + } + } + } + } + entries +} diff --git a/crates/ui-egui/src/platform/window_controls.rs b/crates/ui-egui/src/platform/window_controls.rs deleted file mode 100644 index 9965d46ec1..0000000000 --- a/crates/ui-egui/src/platform/window_controls.rs +++ /dev/null @@ -1,462 +0,0 @@ -//! Window buttons and resize edges for desktops that leave the window frame to the app. -//! -//! GNOME on Wayland has no server-side decorations (the compositor offers no -//! `zxdg_decoration_manager_v1`), so winit drew its own imitation frame. Instead the app turns the -//! frame off and the tab strip becomes the header bar, as in GNOME's own apps: it carries the -//! minimize, maximize and close buttons in the desktop's order (GNOME's `button-layout`), and -//! thin zones along the window's edges resize it. Desktops with server-side decorations (KDE, -//! Sway, Hyprland, X11) keep their own frame and never get here. - -use crate::theme::Tokens; -use egui::viewport::ResizeDirection; -use egui::{Align2, Color32, CursorIcon, Pos2, Rect, Sense, Stroke, Vec2}; - -/// A window button. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Button { - Minimize, - Maximize, - Close, -} - -/// Which buttons go on which end of the header bar, outermost last. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Layout { - pub left: Vec