diff --git a/.cargo/config.toml b/.cargo/config.toml index 2ccbcc61a3..7538a50cb0 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -6,10 +6,17 @@ xtask = "run -p xtask --" [target.wasm32-unknown-unknown] rustflags = ["-C", "target-feature=+simd128"] +[env] # aws-lc (digital signatures and TLS, through aws-lc-rs) detects the CPU when `main` asks it to # (`pdfcraft_sign::init_crypto`), not in a static initializer before `main`. On x86 it reads # `OPENSSL_ia32cap` then, and aborts when that asks for a feature the processor lacks; each # executable first runs itself again without the variable (#2916, `pdfcraft_platform::crypto_env`), # which it can only do once `main` runs. -[env] AWS_LC_SYS_CFLAGS = "-DBORINGSSL_NO_STATIC_INITIALIZER" + +# The optional craft-fonts build input (the Japanese face and the other UI faces; see +# crates/fonts/build.rs). A plain build embeds nothing and prints no warning, so a local build +# embeds a craft-fonts checkout next to this repository when there is one. A `CRAFT_FONTS_DIR` +# already in the environment wins (CI sets its own), and a missing checkout only gives the +# "building without craft-fonts" warning. +CRAFT_FONTS_DIR = { value = "../craft-fonts", relative = true } diff --git a/AGENTS.md b/AGENTS.md index 29e6fba85b..81ca8809a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,7 +81,7 @@ For the crates you changed: `cargo fmt --check`, `cargo clippy -p -- -D - The workspace sets `unsafe_code = "forbid"`; no module allows `unsafe`. `[lints] workspace = true` in every crate. - Hostile-input sweep: `crates/automation/tests/it/hostile_args.rs`. The last-resort `catch_unwind` guards are in `crates/engine/src/doc_state.rs` and `crates/ui-egui/src/frame_guard.rs`. - Attribution: `ATTRIBUTION.toml` is the source (one entry per asset, SHA-256 each); `ATTRIBUTION.md` is generated by `cargo xtask assets --write`. The ArtCraft logos in `docs/brand/` are trademark assets under `docs/brand/LICENSE-brand.txt`. -- Translations come from storytold/craft-i18n at the commit in `craft-i18n.rev`; PdfCraft keeps no catalogs. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (optional build input; code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty); the Latin UI fonts in `assets/fonts/` stay here. The system interface font is read at runtime through `OnDemandFonts` with `SystemCandidates` (never embedded or shipped). +- Translations come from storytold/craft-i18n at the commit in `craft-i18n.rev`; PdfCraft keeps no catalogs. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (optional build input; `.cargo/config.toml` points it at `../craft-fonts`, and a `CRAFT_FONTS_DIR` in the environment wins; code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty); the Latin UI fonts in `assets/fonts/` stay here. The system interface font is read at runtime through `OnDemandFonts` with `SystemCandidates` (never embedded or shipped). - Automation: every feature is a tool in `crates/automation` (`pdfcraft-cli run` and `pdfcraft-cli mcp` share the table; see `crates/automation/README.md`). MCP and the UI control channel are opt-in. The control channel runs only with `--control `, binds to loopback and authenticates with a token (`--control-token`, or an owner-only file named by `--control-token-file`, which `craft_platform::owner_only` sets and checks); never enable it by default or log the token. - Page modules register `PagePart`s (`canvas/page_parts.rs`) and act through the tool host (`canvas/page_tools.rs`). Keys and clipboard events are commands and tool claims, and the framework blocks both while a modal is open. - Large binary test oracles live in storytold/photocraft-corpus, not here; `cargo xtask corpus` fetches the pdf.js corpus pinned by commit and SHA-256. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 8af28a46c0..f173fb8a73 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -287,6 +287,10 @@ impl PdfCraftApp { status_captions_lang: None, views: Vec::new(), closed_tabs: Vec::new(), + tab_groups: Vec::new(), + next_group_id: 1, + editing_group: None, + group_title_draft: String::new(), rename_draft: None, rename_returned: rename_ui::Returned::default(), active: None, @@ -463,6 +467,7 @@ impl PdfCraftApp { last_copied_file: None, clipboard, page_props_draft: None, + delete_pages_draft: None, form_preview: false, #[cfg(not(target_arch = "wasm32"))] recovery: store, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index e9bc46e950..fffd09ff4f 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -167,6 +167,7 @@ impl PdfCraftApp { display_override: None, ready: None, reopen: false, + target_group: request.target_group, }); token } @@ -245,6 +246,9 @@ impl PdfCraftApp { } open_worker::ResultKind::Conversion(bytes) => match self.open_converted(&pending.name, &bytes) { Some(Ok(())) => { + if let Some(idx) = self.active { + self.attach_tab_to_target_group(idx, pending.target_group); + } if let Some(command) = pending.then { self.execute(ctx, command); } @@ -254,6 +258,9 @@ impl PdfCraftApp { }, open_worker::ResultKind::Converted(created) => match self.open_converted_pdf(&pending.name, created) { Ok(()) => { + if let Some(idx) = self.active { + self.attach_tab_to_target_group(idx, pending.target_group); + } if let Some(command) = pending.then { self.execute(ctx, command); } @@ -263,6 +270,9 @@ impl PdfCraftApp { open_worker::ResultKind::Prepared { bytes, result, named } => match *result { Ok(prepared) => match self.finish_open(ctx, &pending.name, pending.path.clone(), bytes.len(), prepared, pending.activate) { Ok(id) => { + if let Some(idx) = self.views.iter().position(|v| v.id == id) { + self.attach_tab_to_target_group(idx, pending.target_group); + } if let Some(path) = pending.path.as_deref() { self.watch.known_as(id, std::path::Path::new(path), pending.stamp); if pending.reopen { @@ -307,6 +317,7 @@ impl PdfCraftApp { then: pending.then, after_open: pending.after_open, display_override: pending.display_override, + target_group: pending.target_group, }); } Err(error) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error.to_string())]), @@ -347,6 +358,7 @@ impl PdfCraftApp { then: None, after_open: None, display_override: None, + target_group: None, }); return Ok(()); } @@ -464,7 +476,7 @@ impl PdfCraftApp { } if let Some(p) = path { #[cfg(target_os = "macos")] - macos_association::repair(std::path::Path::new(&p)); + crate::macos_association::repair(std::path::Path::new(&p)); self.recent.retain(|r| r.path != p); self.recent_check.opened(&p); self.recent.insert(0, RecentFile { name: name.to_string(), path: p, pages, size }); @@ -737,6 +749,7 @@ impl PdfCraftApp { recovered: p.recovered.clone(), then: p.then, priority: Priority::VISIBLE, + target_group: p.target_group, }); if let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == token) { pending.display_override = p.display_override; @@ -752,12 +765,17 @@ impl PdfCraftApp { #[cfg(target_arch = "wasm32")] fn retry_inline(&mut self, ctx: &egui::Context, mut p: PasswordPrompt, pw: zeroize::Zeroizing) { let after_open = p.after_open.clone(); + let before = self.views.len(); + let target_group = p.target_group; let opened = self.try_open(ctx, &p.name, p.path.take(), p.bytes.clone(), Some(&pw), p.activate); drop(pw); match opened { Err(e) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &p.name), ("e", &e.to_string())]), // A recovered encrypted document is open once its prompt is gone. Ok(()) if self.password_prompt.is_none() => { + if self.views.len() > before { + self.attach_tab_to_target_group(self.views.len() - 1, target_group); + } if let Some(destination) = after_open { self.apply_remote_destination(destination); } @@ -778,6 +796,7 @@ impl PdfCraftApp { prompt.then = p.then; prompt.after_open = after_open; prompt.display_override = p.display_override; + prompt.target_group = target_group; } } } @@ -832,7 +851,16 @@ impl PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] pub fn open_path(&mut self, path: &str) -> OpenOutcome { - self.open_path_request(path, None, None) + self.open_path_request(path, None, None, None) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn open_path_in_group( + &mut self, + path: &str, + group_target: Option<(crate::tab_group::TabGroupId, crate::panes::Place)>, + ) -> OpenOutcome { + self.open_path_request(path, None, None, group_target) } /// Keep a chosen tool with its file until preparation and any password entry finish. The @@ -840,7 +868,7 @@ impl PdfCraftApp { /// the file opened, focused its tab, was handed to the background worker, or failed. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn open_path_then(&mut self, ctx: &egui::Context, path: &str, then: Option<&'static str>) -> OpenOutcome { - let outcome = self.open_path_request(path, then, None); + let outcome = self.open_path_request(path, then, None, None); // A file that was open already is focused at once, and the tool it was opened for runs on it. if let (OpenOutcome::Focused, Some(command)) = (&outcome, then) { self.execute(ctx, command); @@ -849,12 +877,18 @@ impl PdfCraftApp { } #[cfg(not(target_arch = "wasm32"))] - fn open_path_request(&mut self, path: &str, then: Option<&'static str>, display_override: Option<(canvas::PageDisplay, bool)>) -> OpenOutcome { + fn open_path_request( + &mut self, + path: &str, + then: Option<&'static str>, + display_override: Option<(canvas::PageDisplay, bool)>, + target_group: Option<(crate::tab_group::TabGroupId, crate::panes::Place)>, + ) -> OpenOutcome { // `manual.pdf#nameddest=Intro`, as a help system starts a PDF reader (#3425): the file, // shown at that destination once open. A path that names a file is never split. match pdfcraft_engine::open_parameters::split(path, |p| std::path::Path::new(p).is_file()) { - Some((file, destination)) => self.open_file_request(&file, Some(destination), then, display_override), - None => self.open_file_request(path, None, then, display_override), + Some((file, destination)) => self.open_file_request(&file, Some(destination), then, display_override, target_group), + None => self.open_file_request(path, None, then, display_override, target_group), } } @@ -867,6 +901,7 @@ impl PdfCraftApp { after_open: Option, then: Option<&'static str>, display_override: Option<(canvas::PageDisplay, bool)>, + target_group: Option<(crate::tab_group::TabGroupId, crate::panes::Place)>, ) -> OpenOutcome { // One file, one tab (#2166): a file that is open already comes to the front instead, // and the tool it was opened for runs on it. One still being opened is left to that. @@ -882,6 +917,7 @@ impl PdfCraftApp { if let Some(destination) = after_open { self.apply_destination_at(i, destination); } + self.attach_tab_to_target_group(i, target_group); return OpenOutcome::Focused; } if let Some(pending) = self.pending_opens.iter_mut().find(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) { @@ -892,6 +928,9 @@ impl PdfCraftApp { if after_open.is_some() { pending.after_open = after_open; } + if target_group.is_some() { + pending.target_group = target_group; + } return OpenOutcome::Pending; } // The same file named again while its password is being asked for joins that prompt @@ -907,6 +946,9 @@ impl PdfCraftApp { if then.is_some() { prompt.then = then; } + if target_group.is_some() { + prompt.target_group = target_group; + } return OpenOutcome::Pending; } let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string()); @@ -924,6 +966,7 @@ impl PdfCraftApp { recovered: None, then, priority: Priority::NEAR, + target_group, }); if let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == token) { pending.display_override = display_override; @@ -934,7 +977,7 @@ impl PdfCraftApp { /// Reopen `path` from the last session: shown at `place` once open, and brought to the front only when `front`. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn reopen_path(&mut self, path: &str, place: pdfcraft_render::RemoteDestination, front: bool) { - if !matches!(self.open_file_request(path, Some(place), None, None), OpenOutcome::Pending) { + if !matches!(self.open_file_request(path, Some(place), None, None, None), OpenOutcome::Pending) { return; } if let Some(pending) = self.pending_opens.iter_mut().find(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) { @@ -974,7 +1017,22 @@ impl PdfCraftApp { /// Open one native file with a transient display override, including after a password prompt. #[cfg(not(target_arch = "wasm32"))] pub fn open_path_with_display(&mut self, path: &str, layout: canvas::PageDisplay, continuous: bool) { - self.open_path_request(path, None, Some((layout, continuous))); + self.open_path_request(path, None, Some((layout, continuous)), None); + } + + /// Attach newly opened tab `index` to `target_group` (setting its originating pane before grouping) if the group still exists. + pub(crate) fn attach_tab_to_target_group(&mut self, index: usize, target_group: Option<(crate::tab_group::TabGroupId, crate::panes::Place)>) { + if let Some((gid, target_place)) = target_group + && self.group(gid).is_some() + { + if let Some(view) = self.views.get_mut(index) + && !view.pane.placed + { + view.pane.place = if self.panes.split.is_some() { target_place } else { crate::panes::Place::Main }; + view.pane.placed = true; + } + self.add_tab_to_group(index, gid); + } } /// The File ▸ Open picker's file types, in order; the first, PDF, is the default. Images, text @@ -1000,19 +1058,32 @@ impl PdfCraftApp { } pub fn open_dialog(&mut self) { + self.open_dialog_in_group(None); + } + + /// Show the Open file picker and add opened tabs to `target_group` when given. + pub fn open_dialog_in_group(&mut self, target_group: Option<(crate::tab_group::TabGroupId, crate::panes::Place)>) { self.startup_superseded = true; // The web answers `Picked::Contents`, the desktop `Picked::Paths`. - self.pick_file(Self::open_request(), None, |app, ctx, picked| match picked { + self.pick_file(Self::open_request(), None, move |app, ctx, picked| match picked { #[cfg(not(target_arch = "wasm32"))] Picked::Paths(paths) => { for path in paths { - app.open_path(&path.to_string_lossy()); + app.open_path_in_group(&path.to_string_lossy(), target_group); } } Picked::Contents(files) => { for (name, bytes) in files { - if let Err(error) = app.open_bytes(ctx, &name, None, bytes) { - app.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]); + let before = app.views.len(); + match app.open_bytes(ctx, &name, None, bytes) { + Ok(()) => { + if app.views.len() > before { + app.attach_tab_to_target_group(app.views.len() - 1, target_group); + } else if let Some(prompt) = app.password_prompt.as_mut() { + prompt.target_group = target_group; + } + } + Err(error) => app.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]), } } } @@ -1051,7 +1122,10 @@ impl PdfCraftApp { } self.remember_view(index); let view = self.views.remove(index); - let (id, place) = (view.id, view.place()); + let (id, place, group) = (view.id, view.place(), view.group); + if let Some(gid) = group { + self.cleanup_empty_group(gid); + } // Another tab showing the same document (split view) keeps it open. if !self.views.iter().any(|v| v.id == id) { #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index dc7d2d429b..978d7a0e01 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -53,6 +53,7 @@ impl PdfCraftApp { recovered: None, then: None, priority: craft::host::queue::Priority::NEAR, + target_group: None, }); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index eff7d08b73..04b9383aab 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -155,6 +155,10 @@ pub struct DocView { /// Where the tab shows (split view's panes) and the key that tells two /// views of one document apart (`crate::panes`). pub(crate) pane: crate::panes::ViewPane, + /// Browser tab group this document belongs to, if any. + pub group: Option, + /// Whether this tab is pinned to the beginning of the tab strip. + pub pinned: bool, pub id: DocId, /// The document and attached file this tab was opened from, when a form or the Attachments /// panel opened it: asking for that attachment again comes back to this tab. @@ -416,6 +420,11 @@ pub struct PageSession { } impl PageSession { + /// Whether a page-box drag (Snapshot, Crop, Redact, or signature area) is currently active. + pub fn is_box_dragging(&self) -> bool { + self.box_drag.is_active() + } + /// The session of a newly opened document. fn new(info: &DocInfo, highlight_fields: bool) -> Self { Self { @@ -478,7 +487,7 @@ impl PageSession { } /// Organize-toolbar actions that need the app (file pickers, new tabs, dialogs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum ViewAction { InsertFromFile, /// Insert files at a gap of the page grid (0 = before the first page). @@ -515,6 +524,12 @@ pub enum ViewAction { }, /// Lock now, on the notice shown after a signature is placed (#2149). LockSignatures, + /// Ask before deleting the pages the panel picked, captured with the document's edit + /// generation when the ask was made. + ConfirmDeletePages { + pages: Vec, + generation: u64, + }, } impl DocView { @@ -581,6 +596,8 @@ impl DocView { pub fn new(id: DocId, info: &DocInfo, defaults: ViewDefaults, highlight_fields: bool) -> Self { Self { pane: Default::default(), + group: None, + pinned: false, id, from_attachment: None, view: PageViewState::from_defaults(&defaults), @@ -693,6 +710,8 @@ impl DocView { // The revision stamps carry on, so the pictures on screen stay until their replacements land. fresh.revisions = std::mem::take(&mut self.revisions); fresh.viewport = self.viewport; + fresh.group = self.group; + fresh.pinned = self.pinned; // Same view key (`pane`): the page view's remembered state and the grid's press id are still this view's. fresh.pane = self.pane.clone(); *self = fresh; @@ -716,6 +735,8 @@ impl DocView { let mut v = Self::new(self.id, info, ViewDefaults::default(), self.session.highlight_fields); v.view = self.view.clone(); v.view.go_to(self.view.current); + v.group = self.group; + v.pinned = self.pinned; v.page_input = self.page_input.clone(); v.notice_dismissed = self.notice_dismissed; v.scripts_off_noted = self.scripts_off_noted; @@ -2249,7 +2270,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize app.add_image_dialog(); } Some(PageMenuAction::DeletePage(page)) => { - app.views[index].session.pending_edit = Some(pdfcraft_engine::Edit::DeletePages { pages: vec![page] }); + app.request_delete_pages(index, vec![page]); } Some(PageMenuAction::ExportPdf) => { app.select_tool(ctx, "export"); diff --git a/crates/ui-egui/src/chrome/doc_tabs.rs b/crates/ui-egui/src/chrome/doc_tabs.rs index 51d2fcb9ca..e6d7426c73 100644 --- a/crates/ui-egui/src/chrome/doc_tabs.rs +++ b/crates/ui-egui/src/chrome/doc_tabs.rs @@ -1,77 +1,300 @@ //! The document tab strips: the main window's and split view's second pane's. A tab is a //! [`DocView`](crate::DocView) keyed by its view key, since split view can show one document in two -//! tabs; the Combine files tab sits last in the main strip and is never moved. +//! tabs; group pills sit directly before their group's tabs, and the Combine files tab sits last in +//! the main strip and is never moved. -use craft::behavior::IconId; +use std::borrow::Cow; +use std::collections::HashSet; + +use craft::behavior::{EditEvent, IconId, SelectionChange, keyed}; use craft::platform::open::CAN_REVEAL; use craft::ui::buttons::Button; -use craft::ui::contract::{Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::overlay::Dismiss; +use craft::ui::contract::{ + Bind, CollectionEvent, DropAt, DropKind, DropPlace, ListDrag, Props as _, ReorderRule, Show as _, ShowCollection as _, ShowContainer as _, Sizing, +}; +use craft::ui::layout_components::Row; use craft::ui::menu::{Menu, MenuItem}; -use craft::ui::tabs::{DocumentTab, DocumentTabs, DocumentTabsEvent}; +use craft::ui::popover::Popover; +use craft::ui::tabs::{Tab, TabStrip, TabStripOutput}; use crate::PdfCraftApp; use crate::panes::Place; use crate::tab_context::Action; +use crate::tab_group::TabGroupId; -/// What a strip tab stands for: a view of a document, or the Combine files tab. +/// What a strip item stands for: a group header pill, a view of a document, or the Combine files tab. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub(crate) enum StripTab { + /// A tab group's header pill, before its tabs. + Group(TabGroupId), /// A document view, by `DocView::view_key`. View(u64), /// The Combine files tab, always last. Combine, } -/// The strip of `place`: its tabs in pane order, then (main strip only) Combine files. +struct StripEntry { + key: StripTab, + label: String, + modified: bool, + closable: bool, + tooltip: Option, + icon: Option, +} + +/// The strip of `place`: its tabs (with group pills) in pane order, then (main strip only) Combine files. pub(crate) fn strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: Place) { - let mut tabs: Vec> = Vec::new(); - for index in app.tabs_in(place) { - let Some(view) = app.views.get(index) else { continue }; - let Some(doc) = app.session.get(view.id) else { continue }; - let name = crate::canvas::tab_label(app, index).unwrap_or_else(|| doc.name.clone()); - let mut tab = DocumentTab::new(StripTab::View(view.pane.key), name).modified(doc.dirty).closable(true); - if let Some(path) = &doc.path - && std::path::Path::new(path).file_name().is_some_and(|file| file.to_string_lossy() != doc.name.as_str()) - { - tab = tab.tooltip(path.clone()); - } - tabs.push(tab); - } - if place == Place::Main && app.combine_tab.open { - tabs.push(DocumentTab::new(StripTab::Combine, tl!("Combine files").to_string()).closable(true).movable(false)); - } + let (entries, seen_groups, has_combine) = build_strip_entries(app, ui, place); let selected = if place == Place::Main && app.combine_showing() { Some(StripTab::Combine) } else { app.pane_front(place).and_then(|i| app.views.get(i)).map(|v| StripTab::View(v.pane.key)) }; - let label = if place == Place::Main { tl!("Documents") } else { tl!("Split view documents") }; - let mut strip = DocumentTabs::new(label.to_string(), &tabs).reorderable(true); - if place == Place::Main { - strip = strip.trailing(|ui| { - Button::command("file.open").variant(craft::theme::Variant::GHOST).icon(IconId::new("plus")).show(ui); + let strip_label = if place == Place::Main { tl!("Documents") } else { tl!("Split view documents") }.to_string(); + let source = keyed(&entries, |entry: &StripEntry| entry.key.clone()).with_text(|entry: &StripEntry| Cow::Borrowed(entry.label.as_str())); + let item_count = entries.len(); + let entries_ref = &entries; + let make_strip = || { + let mut strip = TabStrip::new(strip_label.clone()) + .takes_drop(DropKind::new(DropPlace::Between, |_: &ListDrag, _| true)) + .can_close(move |key: &StripTab| entries_ref.iter().any(|entry| &entry.key == key && entry.closable)) + .reorder(ReorderRule::new()) + .drag_badge(false) + .can_drag(|key: &StripTab| matches!(key, StripTab::View(_))) + .accepts(move |drag: &ListDrag, _, insert| { + if has_combine && insert >= item_count { + return false; + } + drag.keys.iter().all(|k| matches!(k, StripTab::View(_))) + }); + if let Some(selected) = selected.clone() { + strip = strip.shown(selected); + } + strip + }; + let show_strip = |ui: &mut egui::Ui, strip: TabStrip<'_, StripTab>| { + strip.show_items(ui, &source, &mut |key, _| { + let Some(item) = entries_ref.iter().find(|entry| &entry.key == key) else { + return Tab::new("").closable(false); + }; + let mut tab = Tab::new(item.label.clone()).closable(item.closable); + if item.modified { + tab = tab.modified(); + } + if let Some(icon) = &item.icon { + tab = tab.icon(icon.clone()); + } + if let Some(tooltip) = &item.tooltip { + tab = tab.tooltip(tooltip.clone()); + } + tab + }) + }; + + let shown = show_strip_row(ui, place, entries.len(), make_strip, show_strip); + let Ok(output) = shown else { return }; + let group_rects = paint_group_overlays(app, ui, &output.tab_rects); + let response = output.response.response.clone(); + handle_strip_output(app, ui, place, &entries, output); + show_group_editor(app, ui, place, &seen_groups, &group_rects); + show_tab_context_menu(app, ui, place, &response); +} + +fn build_strip_entries(app: &mut PdfCraftApp, ui: &egui::Ui, place: Place) -> (Vec, HashSet, bool) { + let mut entries: Vec = Vec::new(); + let mut seen_groups: HashSet = HashSet::new(); + + for index in app.tabs_in(place) { + let Some(view) = app.views.get(index) else { continue }; + if let Some(gid) = view.group { + if seen_groups.insert(gid) + && let Some(g) = app.group(gid) + { + let title = g.title.trim(); + let group_label = if title.is_empty() { tl!("Tab group").to_string() } else { title.to_string() }; + let tip = if g.collapsed { + crate::i18n::fmt(tl!("{name}: Click to expand"), &[("name", &group_label)]) + } else { + crate::i18n::fmt(tl!("{name}: Click to collapse, right-click to edit"), &[("name", &group_label)]) + }; + entries.push(StripEntry { + key: StripTab::Group(gid), + label: group_label, + modified: false, + closable: false, + tooltip: Some(tip), + icon: Some(IconId::new(if g.collapsed { "chevron-right" } else { "chevron-down" })), + }); + } + if app.group(gid).is_some_and(|g| g.collapsed) { + continue; + } + } + let Some(doc) = app.session.get(view.id) else { continue }; + let base_name = crate::canvas::tab_label(app, index).unwrap_or_else(|| doc.name.clone()); + let name = if view.pinned { crate::i18n::fmt(tl!("{name} (pinned)"), &[("name", &base_name)]) } else { base_name }; + let tooltip = doc + .path + .as_ref() + .filter(|path| std::path::Path::new(path).file_name().is_some_and(|file| file.to_string_lossy() != doc.name.as_str())) + .cloned(); + entries.push(StripEntry { + key: StripTab::View(view.pane.key), + label: name, + modified: doc.dirty, + closable: !view.pinned, + tooltip, + icon: view.pinned.then(|| IconId::new("pin")), }); } - if let Some(selected) = selected { - strip = strip.selected(selected); - } - let output = strip.show(ui); - let (events, response) = (output.events, output.response); - for event in events { + // Advance group collapse/expand indicator animation for groups shown in this strip. + for &gid in &seen_groups { + if let Some(g) = app.group_mut(gid) { + g.open_progress = ui.ctx().animate_bool_with_time(ui.scope_id().with(("tab_group_open", g.id)), !g.collapsed, 0.15); + } + } + + let has_combine = place == Place::Main && app.combine_tab.open; + if has_combine { + entries.push(StripEntry { + key: StripTab::Combine, + label: tl!("Combine files").to_string(), + modified: false, + closable: true, + tooltip: None, + icon: None, + }); + } + + (entries, seen_groups, has_combine) +} + +fn show_strip_row<'a>( + ui: &mut egui::Ui, + place: Place, + item_count: usize, + mut make_strip: impl FnMut() -> TabStrip<'a, StripTab>, + mut show_strip: impl FnMut(&mut egui::Ui, TabStrip<'a, StripTab>) -> TabStripOutput, +) -> Result, egui::Response> { + if place != Place::Main { + return Ok(show_strip(ui, make_strip())); + } + let mut shown = None; + let row = Row::new().sizing(Sizing::FillWidth).show(ui, |ui, _| { + let strip = show_strip(ui, make_strip()); + let memory = ui.scope_id().with("document-tabs-trailing-width"); + let held = ui.ctx().data_mut(|d| d.get_temp::(memory).unwrap_or(0.0)); + let slot = ui.allocate_exact_size(egui::vec2(held, strip.response.response.rect.height()), egui::Sense::hover()).0; + let all_show = strip.tab_rects.len() == item_count; + let after = match strip.tab_rects.last() { + Some((_, rect)) if all_show => Some(rect.right() + ui.spacing().item_spacing.x), + None => Some(strip.response.response.rect.left()), + _ => None, + }; + let (room, layout) = match after { + Some(at) if !ui.layout().prefer_right_to_left() => { + let end = slot.right().min(ui.clip_rect().right().max(slot.left())); + let left = at.min(slot.left()).min(end - held).max(strip.response.response.rect.left()); + ( + egui::Rect::from_min_max(egui::pos2(left, slot.top()), egui::pos2(slot.right().max(left + 400.0), slot.bottom())), + egui::Layout::left_to_right(egui::Align::Center), + ) + } + _ => { + let end = slot.right().min(ui.clip_rect().right().max(slot.left())); + ( + egui::Rect::from_min_max(egui::pos2(end - slot.width(), slot.top()), egui::pos2(end, slot.bottom())), + egui::Layout::right_to_left(egui::Align::Center), + ) + } + }; + let builder = egui::UiBuilder::new().max_rect(room).layout(layout); + let drawn = ui + .scope_builder(builder, |ui| { + Button::command("file.open").variant(craft::theme::Variant::GHOST).icon(IconId::new("plus")).show(ui); + }) + .response + .rect + .width(); + if (drawn - held).abs() > 0.5 { + ui.ctx().data_mut(|d| d.insert_temp(memory, drawn)); + ui.ctx().request_repaint(); + } + shown = Some(strip); + }); + shown.ok_or(row.output) +} + +fn paint_group_overlays(app: &PdfCraftApp, ui: &egui::Ui, tab_rects: &[(StripTab, egui::Rect)]) -> Vec<(TabGroupId, egui::Rect)> { + let mut group_rects: Vec<(TabGroupId, egui::Rect)> = Vec::new(); + let mut prev: Option<(egui::Rect, Option)> = None; + for (item, rect) in tab_rects { + match item { + StripTab::Group(gid) => { + group_rects.push((*gid, *rect)); + if let Some(g) = app.group(*gid) { + let hovered = ui.rect_contains_pointer(*rect); + crate::tab_group::paint_group_pill(ui, g, *rect, hovered); + } + prev = Some((*rect, Some(*gid))); + } + StripTab::View(key) => { + let view_group = app.tab_with_key(*key).and_then(|i| app.views.get(i)).and_then(|v| v.group); + if let Some(gid) = view_group + && let Some(g) = app.group(gid) + { + let color = g.color.color32(); + let bar = egui::Rect::from_min_size(rect.min, egui::vec2(rect.width(), 2.5)); + ui.painter().rect_filled(bar, egui::CornerRadius::ZERO, color); + if let Some((prev_rect, Some(prev_gid))) = prev + && prev_gid == gid + { + let (gap_left, gap_right) = + if prev_rect.right() <= rect.left() { (prev_rect.right(), rect.left()) } else { (rect.right(), prev_rect.left()) }; + if gap_right > gap_left && gap_right - gap_left <= 16.0 { + let bridge = egui::Rect::from_min_max(egui::pos2(gap_left, rect.top()), egui::pos2(gap_right, rect.top() + 2.5)); + ui.painter().rect_filled(bridge, egui::CornerRadius::ZERO, color); + } + } + } + prev = Some((*rect, view_group)); + } + StripTab::Combine => { + prev = Some((*rect, None)); + } + } + } + group_rects +} + +fn select_strip_tab(app: &mut PdfCraftApp, tab: StripTab) { + match tab { + StripTab::Group(gid) => app.toggle_group_collapsed(gid), + StripTab::View(k) => { + if let Some(i) = app.tab_with_key(k) { + app.active = Some(i); + app.combine_tab.focused = false; + } + } + StripTab::Combine => { + app.active = None; + app.combine_tab.focused = true; + } + } +} + +fn handle_strip_output(app: &mut PdfCraftApp, ui: &egui::Ui, place: Place, entries: &[StripEntry], output: TabStripOutput) { + for event in output.response.events { match event { - DocumentTabsEvent::Selected(StripTab::View(key)) | DocumentTabsEvent::Picked(StripTab::View(key)) => { - if let Some(i) = app.tab_with_key(key) { - app.active = Some(i); - app.combine_tab.focused = false; + CollectionEvent::Selection(SelectionChange::Set(keys)) => { + for key in keys { + select_strip_tab(app, key); } } - DocumentTabsEvent::Selected(StripTab::Combine) | DocumentTabsEvent::Picked(StripTab::Combine) => { - app.active = None; - app.combine_tab.focused = true; - } // Double-clicking a saved document's tab renames its file, as in Finder and File Explorer. - DocumentTabsEvent::Activated(StripTab::View(key)) => { + CollectionEvent::Activate(StripTab::View(key)) => { let saved = app .tab_with_key(key) .and_then(|i| app.views.get(i)) @@ -83,63 +306,201 @@ pub(crate) fn strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: Place) { app.start_rename(ui.ctx(), id); } } - DocumentTabsEvent::CloseRequested(StripTab::View(key)) => app.tab_action(ui.ctx(), Action::Close(key)), - DocumentTabsEvent::CloseRequested(StripTab::Combine) => app.close_combine_tab(ui.ctx()), - DocumentTabsEvent::Reordered { documents, before, .. } => { - for document in documents { - let StripTab::View(key) = document else { continue }; - let Some(from) = app.tab_with_key(key) else { continue }; - let tabs = app.tabs_in(place); - let others: Vec = tabs.iter().copied().filter(|&i| i != from).collect(); - let to = match &before { - Some(StripTab::View(next)) => { - app.tab_with_key(*next).and_then(|n| others.iter().position(|&i| i == n)).unwrap_or(others.len()) - } - _ => others.len(), - }; - app.move_tab_in_strip(from, &tabs, to); - } - } - DocumentTabsEvent::DroppedInto { documents, .. } => { - for document in documents { - if let StripTab::View(key) = document - && let Some(i) = app.tab_with_key(key) - { - app.move_tab_to(i, place); + CollectionEvent::Reorder(edit) => { + if let (Some(moved), true) = (edit.value(), matches!(edit, EditEvent::Set { .. } | EditEvent::Commit { .. })) { + let remaining: Vec<&StripTab> = entries.iter().map(|e| &e.key).filter(|id| !moved.keys.contains(id)).collect(); + let before = remaining.get(moved.to).cloned().cloned(); + for document in &moved.keys { + let StripTab::View(key) = *document else { continue }; + let Some(from) = app.tab_with_key(key) else { continue }; + let tabs = app.tabs_in(place); + let others: Vec = tabs.iter().copied().filter(|&i| i != from).collect(); + let to = match &before { + Some(StripTab::View(next)) => { + app.tab_with_key(*next).and_then(|n| others.iter().position(|&i| i == n)).unwrap_or(others.len()) + } + Some(StripTab::Group(gid)) => { + others.iter().position(|&i| app.views.get(i).is_some_and(|v| v.group == Some(*gid))).unwrap_or(others.len()) + } + Some(StripTab::Combine) | None => others.len(), + }; + app.move_tab_in_strip(from, &tabs, to); } } } - DocumentTabsEvent::ContextMenu(request) => { - app.panes.tab_menu = match request.key { - StripTab::View(key) => Some((place, key)), - StripTab::Combine => None, - }; + CollectionEvent::Dropped { at: DropAt::Gap { key: Some(_), .. }, payload, .. } => { + if let Some(drag) = payload.get::>() { + for document in &drag.keys { + if let StripTab::View(key) = document + && let Some(i) = app.tab_with_key(*key) + { + app.move_tab_to(i, place); + } + } + } } _ => {} } } + if let Some(picked) = output.picked { + select_strip_tab(app, picked); + } + + for closed in output.closed { + match closed { + StripTab::View(key) => app.tab_action(ui.ctx(), Action::Close(key)), + StripTab::Combine => app.close_combine_tab(ui.ctx()), + StripTab::Group(_) => {} + } + } + + if let Some(request) = output.menu { + match request.key { + StripTab::View(key) => { + app.panes.tab_menu = Some((place, key)); + app.editing_group = None; + } + StripTab::Group(gid) => { + app.panes.tab_menu = None; + if let Some(g) = app.group(gid) { + app.group_title_draft = g.title.clone(); + app.editing_group = Some(gid); + } + } + StripTab::Combine => { + app.panes.tab_menu = None; + app.editing_group = None; + } + } + } +} + +fn show_group_editor( + app: &mut PdfCraftApp, + ui: &mut egui::Ui, + place: Place, + seen_groups: &HashSet, + group_rects: &[(TabGroupId, egui::Rect)], +) { + let Some(gid) = app.editing_group else { return }; + if app.group(gid).is_none() || !seen_groups.contains(&gid) { + return; + } + let mut open = true; + let mut close_popup = false; + let mut popover = + Popover::new(tl!("Tab group").to_string(), Bind::bound(&mut open)).dismiss(Dismiss::new().focus_left(false)).close_on_enter(true); + if let Some(pill_rect) = group_rects.iter().find(|(g, _)| *g == gid).map(|(_, r)| *r) { + popover = popover.at_point(pill_rect.left_bottom() + egui::vec2(0.0, 4.0)); + } else { + popover = popover.at_pointer(); + } + popover.show(ui, |ui, _| { + crate::tab_group::group_editor_popup(app, ui, place, gid, &mut close_popup); + }); + if !open || close_popup { + app.editing_group = None; + } +} + +fn show_tab_context_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: Place, response: &egui::Response) { // The menu acts on the tab it was asked for, not the active one. - let target: Option = app.panes.tab_menu.filter(|(menu_place, _)| *menu_place == place).map(|(_, key)| key); - let doc = target.and_then(|key| app.tab_with_key(key)).and_then(|i| app.views.get(i)).map(|v| v.id); + let Some(tab) = app.panes.tab_menu.filter(|(menu_place, _)| *menu_place == place).map(|(_, key)| key) else { + return; + }; + let view_idx = app.tab_with_key(tab); + let view = view_idx.and_then(|i| app.views.get(i)); + let doc = view.map(|v| v.id); let path = doc.and_then(|id| app.session.get(id)).and_then(|d| d.path.clone()); let can_reopen = !app.closed_tabs.is_empty(); + let is_pinned = view.is_some_and(|v| v.pinned); + let current_group = view.and_then(|v| v.group); + let tabs_in_place = app.tabs_in(place); + let has_other_closable = view_idx.is_some_and(|idx| tabs_in_place.iter().any(|&i| i != idx && app.views.get(i).is_some_and(|v| !v.pinned))); + let has_tabs_to_right = view_idx.is_some_and(|idx| { + tabs_in_place + .iter() + .position(|&i| i == idx) + .is_some_and(|pos| tabs_in_place[pos + 1..].iter().any(|&i| app.views.get(i).is_some_and(|v| !v.pinned))) + }); let reveal_label = if cfg!(target_os = "macos") { tl!("Reveal in Finder") } else { tl!("Reveal in File Explorer") }.to_string(); + let mut open = true; let mut chosen: Option = None; - let menu = Menu::context(tl!("Tab").to_string(), &response).show(ui, |ui, _| { - let Some(tab) = target else { return }; + let menu = Menu::context(tl!("Tab").to_string(), response).open(Bind::bound(&mut open)).show(ui, |ui, _| { + let group_label = |g: &crate::tab_group::TabGroup| { + let label = if g.title.is_empty() { tl!(g.color.name()) } else { g.title.as_str() }; + format!("● {label}") + }; + + // Grouping options (Edge standard) + if let Some(current_gid) = current_group { + if MenuItem::new(tl!("Remove from group").to_string()).show(ui).ran { + chosen = Some(Action::RemoveFromGroup(tab)); + } + if app.tab_groups.len() > 1 { + Menu::submenu_row_enabled(ui, tl!("Move to another group").to_string(), true, |ui, _| { + for g in &app.tab_groups { + if g.id != current_gid && MenuItem::new(group_label(g)).show(ui).ran { + chosen = Some(Action::AddToGroup { tab, group_id: g.id }); + } + } + }); + } + } else { + if MenuItem::new(tl!("Add tab to new group").to_string()).show(ui).ran { + chosen = Some(Action::AddToNewGroup(tab)); + } + if !app.tab_groups.is_empty() { + Menu::submenu_row_enabled(ui, tl!("Add tab to group").to_string(), true, |ui, _| { + if MenuItem::new(tl!("New group").to_string()).show(ui).ran { + chosen = Some(Action::AddToNewGroup(tab)); + } + ui.separator(); + for g in &app.tab_groups { + if MenuItem::new(group_label(g)).show(ui).ran { + chosen = Some(Action::AddToGroup { tab, group_id: g.id }); + } + } + }); + } + } + + ui.separator(); + + // Pinning (Edge standard) + let pin_label = if is_pinned { tl!("Unpin tab") } else { tl!("Pin tab") }.to_string(); + if MenuItem::new(pin_label).show(ui).ran { + chosen = Some(Action::TogglePin(tab)); + } + + // Duplicate tab (Edge standard) + if MenuItem::new(tl!("Duplicate tab").to_string()).show(ui).ran { + chosen = Some(Action::Duplicate(tab)); + } + + ui.separator(); + if MenuItem::new(tl!("Close Tab").to_string()).show(ui).ran { chosen = Some(Action::Close(tab)); } + if MenuItem::new(tl!("Close other tabs").to_string()).enabled(has_other_closable).show(ui).ran { + chosen = Some(Action::CloseOthers(tab)); + } + if MenuItem::new(tl!("Close tabs to the right").to_string()).enabled(has_tabs_to_right).show(ui).ran { + chosen = Some(Action::CloseToRight(tab)); + } if MenuItem::new(tl!("Reopen Closed Tab").to_string()).enabled(can_reopen).show(ui).ran { chosen = Some(Action::Reopen); } + ui.separator(); if MenuItem::new(tl!("Split right").to_string()).show(ui).ran { chosen = Some(Action::Split { tab, down: false }); } if MenuItem::new(tl!("Split down").to_string()).show(ui).ran { chosen = Some(Action::Split { tab, down: true }); } + ui.separator(); if MenuItem::new(reveal_label.clone()).enabled(CAN_REVEAL && path.is_some()).show(ui).ran && let Some(id) = doc { @@ -151,7 +512,7 @@ pub(crate) fn strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: Place) { chosen = Some(Action::Rename(id)); } }); - if menu.output.closed.is_some() && target.is_some() { + if !open || menu.output.closed.is_some() { app.panes.tab_menu = None; } if let Some(action) = chosen { diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index 6385cde024..6b7fb6b7e8 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -649,7 +649,9 @@ impl PdfCraftApp { self.apply_edit(ctx, Edit::RotatePages { pages: targets, degrees: -90 }); } "page.delete" => { - self.apply_edit(ctx, Edit::DeletePages { pages: targets }); + if let Some(i) = active { + self.request_delete_pages(i, targets); + } } "page.insert_blank" => { if let (Some(i), Some(&last)) = (active, targets.last()) diff --git a/crates/ui-egui/src/dialogs/prompts.rs b/crates/ui-egui/src/dialogs/prompts.rs index 4f5534880b..37be242288 100644 --- a/crates/ui-egui/src/dialogs/prompts.rs +++ b/crates/ui-egui/src/dialogs/prompts.rs @@ -23,6 +23,8 @@ pub(crate) struct OpenPrompts { pub(crate) sanitize: Option, /// The question about locking placed signatures into the page before a save (`pending_lock`). pub(crate) lock_signatures: Option, + /// The confirmation question before deleting pages. + pub(crate) delete_pages: Option, } /// `name` cut to at most `max` characters by replacing its middle with "…", keeping the start and @@ -130,6 +132,23 @@ impl PdfCraftApp { self.prompts.remote_link = Some(self.dialogs.open(prompt)); } + /// Ask before deleting pages. + pub(crate) fn ask_delete_pages(&mut self, pages: &[usize]) { + let n = pages.len(); + let message = if n == 1 { + tl!("Are you Sure you want to delete this page?").to_string() + } else { + crate::i18n::fmt(tl!("Are you Sure you want to delete these {n} pages?"), &[("n", &n.to_string())]) + }; + let prompt = StandardPrompt::custom(message) + .title(tl!("Delete page?")) + .button(PromptChoice::Proceed, tl!("Delete")) + .button(PromptChoice::Cancel, tl!("Cancel")) + .default_choice(PromptChoice::Proceed) + .instance("delete-pages"); + self.prompts.delete_pages = Some(self.dialogs.open(prompt)); + } + /// One pass over the document prompts: takes each open prompt's answer, cancels a prompt whose question is /// gone, then opens the prompts that are pending. An answer is taken once, so a second pass in a frame /// applies nothing twice. @@ -196,6 +215,20 @@ impl PdfCraftApp { _ => self.pending_lock = None, } } + if let Some(dialog) = self.prompts.delete_pages { + if let Some(go) = proceeded(self.dialogs.take_by_id::(dialog)) { + self.prompts.delete_pages = None; + if go { + self.confirm_delete_pages(ctx); + } else { + self.delete_pages_draft = None; + } + } else if self.delete_pages_draft.as_ref().is_none_or(|d| self.session.get(d.doc).is_none()) { + self.dialogs.cancel_by_id(ctx, dialog); + self.prompts.delete_pages = None; + self.delete_pages_draft = None; + } + } if self.pending_link.is_some() && self.prompts.link.is_none() { self.ask_link(); } diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 31d789ef80..663cf1dcca 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -65,7 +65,7 @@ fn select_after_edit( if let Some(&first) = pages.iter().min() { clear_shifted_page_comment_state(view, first); } - view.select_pages(&[]); + view.clear_page_selection(None); } // A stroke drawn with the pen stays unselected, so the selection box and // author popup don't sit over the next stroke (#429). @@ -559,6 +559,16 @@ impl PdfCraftApp { self.lock_signatures_now(ctx, id); } } + // The panel asked before deleting pages: open the confirmation dialog, which queues + // the edit when confirmed. + Some(crate::canvas::ViewAction::ConfirmDeletePages { pages, generation }) => { + // The panel captured the pages with the document's generation when it asked: an + // edit that ran since makes those indices stale, so the ask is dropped rather + // than shown, and never names the newer document. + if self.views.get(i).and_then(|v| self.session.get(v.id)).is_some_and(|d| d.edit_generation() == generation) { + self.request_delete_pages(i, pages); + } + } Some(crate::canvas::ViewAction::CameraNext(command)) => { self.leave_camera(i); self.execute(ctx, command); @@ -710,6 +720,54 @@ impl PdfCraftApp { } } + /// Ask before deleting `pages` (0-based) of the document in view `index` via a page's + /// right-click menu: the confirmation dialog queues the edit when confirmed. A deletion + /// that would leave the document without a page is refused silently. + pub fn request_delete_pages(&mut self, index: usize, pages: Vec) { + let Some(id) = self.views.get(index).map(|v| v.id) else { return }; + let Some(doc) = self.session.get(id) else { return }; + let mut pages = pages; + pages.sort_unstable(); + pages.dedup(); + if pages.is_empty() || pages.len() >= doc.info.pages.len() { + return; + } + self.delete_pages_draft = Some(crate::DeletePagesDraft { doc: id, generation: doc.edit_generation(), pages: pages.clone() }); + self.ask_delete_pages(&pages); + } + + /// The confirmation's Delete: queue the deletion the draft holds. A document changed since + /// the dialog opened (another edit ran behind it) deletes nothing, so the pages those + /// indices named are not the pages deleted. + pub fn confirm_delete_pages(&mut self, ctx: &egui::Context) { + if let Some(dialog) = self.prompts.delete_pages.take() { + self.dialogs.cancel_by_id(ctx, dialog); + } + let Some(d) = self.delete_pages_draft.take() else { return }; + let still_there = + self.active_ids().is_some_and(|(_, id)| id == d.doc) && self.session.get(d.doc).is_some_and(|doc| doc.edit_generation() == d.generation); + if !still_there { + self.notify_tr("The document changed while the dialog was open, so nothing was changed. Delete the pages again."); + return; + } + let Some((i, id)) = self.active_ids() else { return }; + let Some(doc) = self.session.get(id) else { return }; + let n = doc.info.pages.len(); + let current = self.views.get(i).map(|v| v.current()).unwrap_or(0); + let before = d.pages.iter().filter(|p| **p < current).count(); + let target_current = current.saturating_sub(before).min(n.saturating_sub(d.pages.len() + 1)); + + if self.apply_edit(ctx, Edit::DeletePages { pages: d.pages }) { + // The view keeps the page it showed, or the one after the deleted run, as the + // right-click delete did before it asked: pages deleted before it shift it up, and a page + // deleted itself is replaced by what followed the deleted run (or the last page). + if let Some(v) = self.views.get_mut(i) { + v.view.current = target_current; + v.clear_page_selection(None); + } + } + } + /// Organize ▸ Copy / Cut: remember the selected pages (the document as it is now); Cut also /// deletes them (one page always stays). pub fn copy_pages(&mut self, ctx: &egui::Context, cut: bool) { diff --git a/crates/ui-egui/src/editing/close.rs b/crates/ui-egui/src/editing/close.rs index f4c3046ee0..828a10d872 100644 --- a/crates/ui-egui/src/editing/close.rs +++ b/crates/ui-egui/src/editing/close.rs @@ -142,7 +142,7 @@ impl PdfCraftApp { /// Starts the unsaved-changes question for `docs` under `scope`. A newer operation replaces /// one still asking; a quit it replaces is called off. - fn begin_close(&mut self, ctx: &egui::Context, scope: CloseScope, docs: Vec) { + pub(crate) fn begin_close(&mut self, ctx: &egui::Context, scope: CloseScope, docs: Vec) { let Some(first) = docs.first().copied() else { return }; if self.close_guard.as_ref().is_some_and(|g| g.scope() == CloseScope::Quit) { self.session_keeper.quit_cancelled(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b4683f521a..3449fd4e5c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -57,11 +57,13 @@ mod home; mod hotbar; mod panels; pub mod panes; +pub mod tab_group; pub use print_ui::{ DefaultPaperSource, Handling as PrintHandling, OptionsSource, PrintDraft, PrinterPapersSource, PrinterSetup, PrinterSource, Spooler, TwoSidedSource, Which as PrintWhich, system_printers, system_two_sided, }; pub use redact_ui::{HiddenDraft, RedactPrefs, SearchDraft as RedactSearchDraft, SearchMode as RedactSearchMode}; +pub use tab_group::{TabGroup, TabGroupColor, TabGroupId}; pub mod i18n; pub mod viewer_prefs; // PLAN: the lead adds `mod notices; mod icons; mod brand; mod colour_picker; pub mod fonts;` here, and `pub mod settings;` in app.rs, at combine (L-212). @@ -140,8 +142,8 @@ pub use platform::ui_scale; #[cfg(not(target_arch = "wasm32"))] use state::OpenRequest; pub use state::{ - CommentClip, LeftPanel, LinkOrigin, Mode, OpenOutcome, PageClip, PagePropsDraft, PasswordPrompt, PendingLink, PendingRemoteLink, QuickTool, - RECENT_FILES_DEFAULT, RECENT_FILES_MAX, RecentFile, RightPanel, UnlockPrompt, + CommentClip, DeletePagesDraft, LeftPanel, LinkOrigin, Mode, OpenOutcome, PageClip, PagePropsDraft, PasswordPrompt, PendingLink, + PendingRemoteLink, QuickTool, RECENT_FILES_DEFAULT, RECENT_FILES_MAX, RecentFile, RightPanel, UnlockPrompt, }; pub use tools::bulk_fields; use tools::calc_order_ui; @@ -203,6 +205,8 @@ struct PendingOpen { ready: Option, /// Reopen Closed Tab asked for it: its closed-tab entry goes once it has opened, and stays when it fails. reopen: bool, + /// Optional tab group and originating pane to join once the opened tab is created ("New tab in group"). + target_group: Option<(tab_group::TabGroupId, panes::Place)>, } /// A named destination being looked up in a document. @@ -251,6 +255,11 @@ pub struct PdfCraftApp { pub(crate) status_captions_lang: Option, pub views: Vec, pub(crate) closed_tabs: Vec, + /// Browser-styled tab groups for document tabs. + pub tab_groups: Vec, + pub next_group_id: u64, + pub editing_group: Option, + pub group_title_draft: String, /// The Rename dialog's name being typed. pub(crate) rename_draft: Option, /// A name typed in Rename whose "Save and Rename" save did not go through; the dialog opens @@ -640,6 +649,8 @@ pub struct PdfCraftApp { pub(crate) clipboard: craft::platform::clipboard::Clipboard, /// Page Properties: which pages, and the tab order they have. pub page_props_draft: Option, + /// Delete pages: the document and pages the confirmation dialog would delete. + pub delete_pages_draft: Option, /// Prepare a form ▸ Preview: fill the form instead of editing its fields. pub form_preview: bool, /// Where autosaves go (`None`: autosave off, e.g. on the web and in tests). diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 5eadcde3c7..2ef9274894 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -547,6 +547,9 @@ pub(crate) fn frame(app: &mut PdfCraftApp, ctx: &egui::Context) { } let gate = Gate::default().modal(gated(app)).text_editing(text_editing(ctx)); let clicks = app.native_menu.as_mut().map(|native| { + // The menu events since the last frame, before the gate as craft-menu asks: clicks wait + // for `take_clicks`, key equivalents become the key presses they were. + native.poll(ctx); native.set_gate(gate); native.take_clicks(ctx) }); diff --git a/crates/ui-egui/src/menus/tab_context.rs b/crates/ui-egui/src/menus/tab_context.rs index e7f08868e6..486999b20e 100644 --- a/crates/ui-egui/src/menus/tab_context.rs +++ b/crates/ui-egui/src/menus/tab_context.rs @@ -9,6 +9,27 @@ pub(crate) enum Action { /// Close a tab, by its view key (`DocView::view_key`: split view can show one document in two /// tabs). Close(u64), + /// Close all tabs except this one. + CloseOthers(u64), + /// Close all tabs to the right of this one. + CloseToRight(u64), + /// Duplicate this tab as a second view of the document. + Duplicate(u64), + /// Toggle pinned state of this tab. + TogglePin(u64), + /// Create a new group and add this tab to it. + AddToNewGroup(u64), + /// Add this tab to an existing group. + AddToGroup { + tab: u64, + group_id: crate::tab_group::TabGroupId, + }, + /// Remove this tab from its current group. + RemoveFromGroup(u64), + /// Ungroup all tabs in a group. + Ungroup(crate::tab_group::TabGroupId), + /// Close all tabs in a group. + CloseGroup(crate::tab_group::TabGroupId), Reopen, Reveal(DocId), Rename(DocId), @@ -59,6 +80,51 @@ impl crate::PdfCraftApp { self.request_close_tab(ctx, i); } } + Action::CloseOthers(tab) => { + if let Some(i) = self.tab_with_key(tab) { + self.close_other_tabs(ctx, i); + } + } + Action::CloseToRight(tab) => { + if let Some(i) = self.tab_with_key(tab) { + self.close_tabs_to_right(ctx, i); + } + } + Action::Duplicate(tab) => { + if let Some(i) = self.tab_with_key(tab) { + self.duplicate_tab(i); + } + } + Action::TogglePin(tab) => { + if let Some(i) = self.tab_with_key(tab) { + let pinned = !self.views[i].pinned; + self.set_tab_pinned(i, pinned); + } + } + Action::AddToNewGroup(tab) => { + if let Some(i) = self.tab_with_key(tab) { + let gid = self.create_tab_group(String::new(), crate::tab_group::TabGroupColor::Blue); + self.add_tab_to_group(i, gid); + self.editing_group = Some(gid); + self.group_title_draft.clear(); + } + } + Action::AddToGroup { tab, group_id } => { + if let Some(i) = self.tab_with_key(tab) { + self.add_tab_to_group(i, group_id); + } + } + Action::RemoveFromGroup(tab) => { + if let Some(i) = self.tab_with_key(tab) { + self.remove_tab_from_group(i); + } + } + Action::Ungroup(group_id) => { + self.ungroup(group_id); + } + Action::CloseGroup(group_id) => { + self.close_tab_group(ctx, group_id); + } Action::Split { tab, down } => { if let Some(i) = self.tab_with_key(tab) { self.split_tab(ctx, i, down); diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index 9d6f0cf5c8..2d783611a4 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -85,7 +85,7 @@ pub(super) fn body(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult { ThumbnailEvent::Delete(_) => { // The menu bar owns keys while its menu is open, even over the thumbnails. if editable && !craft::ui::menu::bar::is_open(ui.ctx()) { - result.edit = delete_pages(view, count); + delete_pages(view, count, doc.edit_generation()); } } ThumbnailEvent::ContextMenu(request) => target = Some(request.key), @@ -123,7 +123,7 @@ pub(super) fn body(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult { // Never every page: a document keeps at least one. let some_left = view.target_pages().len() < count; if MenuItem::new(tl!("Delete pages")).enabled(editable && some_left).show(ui).ran { - result.edit = delete_pages(view, count); + delete_pages(view, count, doc.edit_generation()); } }); if menu.output.closed.is_some() { @@ -136,21 +136,16 @@ pub(super) fn body(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult { result } -/// Queue deleting the selection (or the current page) of a document of `n` pages, unless that -/// would leave no page. The selection goes; the current page stays on the page it showed, or on -/// the page that follows the deleted ones. The edit is returned for the caller to queue. -fn delete_pages(view: &mut crate::DocView, n: usize) -> Option { +/// Ask before deleting the selection (or the current page) of a document of `n` pages whose +/// edits are at `generation`, unless that would leave no page. The pages and the generation are +/// captured now; the current page and the selection change only when the confirmation deletes +/// them, and an edit that ran since drops the ask. +fn delete_pages(view: &mut crate::DocView, n: usize, generation: u64) { let mut pages = view.target_pages(); pages.sort_unstable(); pages.dedup(); if pages.is_empty() || pages.len() >= n { - return None; + return; } - // Deleted pages before it shift it up; if it was deleted itself, the page after the deleted - // run lands where it was (or the last page, when the deletion ran to the end). - let current = view.current(); - let before = pages.iter().filter(|p| **p < current).count(); - view.view.current = current.saturating_sub(before).min(n.saturating_sub(pages.len() + 1)); - view.clear_page_selection(None); - Some(pdfcraft_engine::Edit::DeletePages { pages }) + view.pending_action = Some(crate::canvas::ViewAction::ConfirmDeletePages { pages, generation }); } diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 17861c91ed..4a817f1d22 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -137,7 +137,7 @@ impl PdfCraftApp { self.views.iter().position(|v| v.pane.key == key) } - fn active_key(&self) -> Option { + pub(crate) fn active_key(&self) -> Option { self.active.and_then(|i| self.views.get(i)).map(|v| v.pane.key) } @@ -216,6 +216,9 @@ impl PdfCraftApp { /// tabs, so this goes by the tab it lands next to rather than by index in `views`. pub(crate) fn move_tab_in_strip(&mut self, from: usize, tabs: &[usize], to: usize) { let others: Vec = tabs.iter().copied().filter(|&i| i != from).collect(); + let is_pinned = self.views.get(from).is_some_and(|v| v.pinned); + let pinned_others = others.iter().filter(|&&idx| self.views.get(idx).is_some_and(|v| v.pinned)).count(); + let to = if is_pinned { to.min(pinned_others) } else { to.max(pinned_others) }; let (anchor, before) = match others.get(to) { Some(&a) => (a, true), None => match others.last() { @@ -228,6 +231,7 @@ impl PdfCraftApp { } let Some(anchor) = self.views.get(anchor).map(|v| v.pane.key) else { return }; let active = self.active_key(); + let old_group = self.views[from].group; let view = self.views.remove(from); let Some(a) = self.tab_with_key(anchor) else { self.views.insert(from.min(self.views.len()), view); @@ -236,6 +240,28 @@ impl PdfCraftApp { let at = if before { a } else { a.saturating_add(1) }; self.views.insert(at.min(self.views.len()), view); self.active = active.and_then(|k| self.tab_with_key(k)); + + let new_idx = at.min(self.views.len().saturating_sub(1)); + if self.views[new_idx].pinned { + self.views[new_idx].group = None; + } else { + let place = self.views[new_idx].pane.place; + let left_group = if new_idx > 0 { self.views.get(new_idx - 1).filter(|v| v.pane.place == place).and_then(|v| v.group) } else { None }; + let right_group = self.views.get(new_idx + 1).filter(|v| v.pane.place == place).and_then(|v| v.group); + + if left_group.is_some() && left_group == right_group { + self.views[new_idx].group = left_group; + } else if old_group.is_some() && (left_group == old_group || right_group == old_group) { + self.views[new_idx].group = old_group; + } else { + // Dropped outside its group, or at the edge of another one: not a member of either. + self.views[new_idx].group = None; + } + } + + if let Some(og) = old_group { + self.cleanup_empty_group(og); + } } /// Remove tab `index` but not its document, which another tab still shows. When it was the diff --git a/crates/ui-egui/src/persist/recovery.rs b/crates/ui-egui/src/persist/recovery.rs index bf5448f3aa..56b22171c3 100644 --- a/crates/ui-egui/src/persist/recovery.rs +++ b/crates/ui-egui/src/persist/recovery.rs @@ -231,6 +231,7 @@ impl PdfCraftApp { recovered: Some(entry.clone()), then: None, priority: craft::host::queue::Priority::VISIBLE, + target_group: None, }); } #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8341f1f9e6..9b15d3f61b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -97,6 +97,15 @@ pub enum QuickTool { ColumnSelect, } +/// Delete pages: the document and pages (0-based) the confirmation would delete, and the +/// document's edit generation when the dialog opened. +#[derive(Clone, Debug, PartialEq)] +pub struct DeletePagesDraft { + pub doc: DocId, + pub generation: u64, + pub pages: Vec, +} + /// Page Properties: the document and pages it applies to (0-based), the document's edit /// generation when the dialog opened, and the pages' tab order as they have it (`None` when they /// differ). The order chosen is the hosted dialog's value. @@ -238,6 +247,8 @@ pub struct PasswordPrompt { pub(crate) after_open: Option, /// A launch-time display override, applied only after this PDF is unlocked. pub(crate) display_override: Option<(craft::pages::PageDisplay, bool)>, + /// Optional tab group and originating pane to join once unlocked ("New tab in group"). + pub(crate) target_group: Option<(crate::tab_group::TabGroupId, crate::panes::Place)>, } #[cfg(not(target_arch = "wasm32"))] @@ -254,6 +265,8 @@ pub(crate) struct OpenRequest { /// Where the open waits in the worker's queue: a file the user named goes before files /// reopened from the last session. pub(crate) priority: craft::host::queue::Priority, + /// Optional tab group and originating pane to join once opened ("New tab in group"). + pub(crate) target_group: Option<(crate::tab_group::TabGroupId, crate::panes::Place)>, } /// Asks for the permissions password of an open document whose security restricts it, which diff --git a/crates/ui-egui/src/tab_group.rs b/crates/ui-egui/src/tab_group.rs new file mode 100644 index 0000000000..a09c983b9d --- /dev/null +++ b/crates/ui-egui/src/tab_group.rs @@ -0,0 +1,737 @@ +//! Microsoft Edge-styled tab grouping and management for document tabs. + +use craft::theme::Variant; +use craft::ui::buttons::Button; +use craft::ui::choice::{Swatch, SwatchShape}; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::Text; +use craft::ui::layout_components::Stack; +use craft::ui::text::TextField; +use egui::{Color32, CornerRadius, Rect, Stroke, pos2, vec2}; + +use crate::PdfCraftApp; + +/// Unique identifier for a tab group. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct TabGroupId(pub u64); + +/// Microsoft Edge standard curated group colors. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TabGroupColor { + Grey, + Blue, + Red, + Yellow, + Green, + Pink, + Purple, + Cyan, + Orange, +} + +impl TabGroupColor { + pub const ALL: [Self; 9] = [Self::Grey, Self::Blue, Self::Red, Self::Yellow, Self::Green, Self::Pink, Self::Purple, Self::Cyan, Self::Orange]; + + pub fn name(self) -> &'static str { + match self { + Self::Grey => "Grey", + Self::Blue => "Blue", + Self::Red => "Red", + Self::Yellow => "Yellow", + Self::Green => "Green", + Self::Pink => "Pink", + Self::Purple => "Purple", + Self::Cyan => "Cyan", + Self::Orange => "Orange", + } + } + + pub fn color32(self) -> Color32 { + match self { + Self::Grey => Color32::from_rgb(117, 117, 117), + Self::Blue => Color32::from_rgb(26, 115, 232), + Self::Red => Color32::from_rgb(217, 48, 37), + Self::Yellow => Color32::from_rgb(249, 171, 0), + Self::Green => Color32::from_rgb(24, 128, 56), + Self::Pink => Color32::from_rgb(208, 24, 130), + Self::Purple => Color32::from_rgb(147, 52, 230), + Self::Cyan => Color32::from_rgb(18, 181, 203), + Self::Orange => Color32::from_rgb(250, 123, 23), + } + } + + pub fn text_color(self) -> Color32 { + match self { + Self::Yellow | Self::Cyan | Self::Orange => Color32::from_rgb(32, 33, 36), + _ => Color32::WHITE, + } + } +} + +/// A tab group representing a set of grouped document tabs. +#[derive(Clone, Debug, PartialEq)] +pub struct TabGroup { + pub id: TabGroupId, + pub title: String, + pub color: TabGroupColor, + pub collapsed: bool, + /// Smooth expansion animation progress (0.0 = fully collapsed, 1.0 = fully open). + pub open_progress: f32, +} + +impl TabGroup { + pub fn new(id: TabGroupId, title: String, color: TabGroupColor) -> Self { + Self { id, title, color, collapsed: false, open_progress: 1.0 } + } +} + +impl PdfCraftApp { + /// Create a new tab group and return its identifier. + pub fn create_tab_group(&mut self, title: String, color: TabGroupColor) -> TabGroupId { + let id = TabGroupId(self.next_group_id); + self.next_group_id = self.next_group_id.saturating_add(1); + self.tab_groups.push(TabGroup::new(id, title, color)); + id + } + + /// Look up a tab group by its id. + pub fn group(&self, id: TabGroupId) -> Option<&TabGroup> { + self.tab_groups.iter().find(|g| g.id == id) + } + + /// Look up a mutable tab group by its id. + pub fn group_mut(&mut self, id: TabGroupId) -> Option<&mut TabGroup> { + self.tab_groups.iter_mut().find(|g| g.id == id) + } + + /// Look up the group for a tab at index `tab_index`. + pub fn group_for_tab(&self, tab_index: usize) -> Option<&TabGroup> { + let gid = self.views.get(tab_index)?.group?; + self.group(gid) + } + + /// Add tab at `tab_index` to group `group_id`. + /// Tabs in a group are contiguous within their pane: moves the tab adjacent to the group if needed. + pub fn add_tab_to_group(&mut self, tab_index: usize, group_id: TabGroupId) { + if tab_index >= self.views.len() { + return; + } + let active = self.active_key(); + let place = self.views[tab_index].pane.place; + let prev_group = self.views[tab_index].group; + let was_pinned = self.views[tab_index].pinned; + self.views[tab_index].group = Some(group_id); + self.views[tab_index].pinned = false; + + // Position this tab contiguous with other tabs of the group in the same pane. + let group_tab_indices: Vec = self + .views + .iter() + .enumerate() + .filter(|(i, v)| *i != tab_index && v.pane.place == place && v.group == Some(group_id)) + .map(|(i, _)| i) + .collect(); + + if let Some(&last_idx) = group_tab_indices.last() { + if tab_index > last_idx + 1 { + let view = self.views.remove(tab_index); + let target = last_idx + 1; + self.views.insert(target.min(self.views.len()), view); + } else if tab_index < group_tab_indices[0] { + let view = self.views.remove(tab_index); + let target = group_tab_indices[0]; + self.views.insert(target.min(self.views.len()), view); + } + } else if was_pinned { + // Destination group had no other members. Move the newly unpinned tab after all remaining pinned tabs in this pane. + let after_pinned = self + .views + .iter() + .enumerate() + .filter(|(i, v)| *i != tab_index && v.pane.place == place && v.pinned) + .map(|(i, _)| if i > tab_index { i } else { i + 1 }) + .max() + .unwrap_or(0); + if tab_index < after_pinned { + let view = self.views.remove(tab_index); + self.views.insert(after_pinned.min(self.views.len()), view); + } + } + + self.active = active.and_then(|k| self.tab_with_key(k)); + + if let Some(og) = prev_group + && og != group_id + { + self.cleanup_empty_group(og); + } + } + + /// Remove tab at `tab_index` from its current group. + pub fn remove_tab_from_group(&mut self, tab_index: usize) { + let Some(view) = self.views.get_mut(tab_index) else { return }; + let prev_group = view.group.take(); + if let Some(gid) = prev_group { + self.cleanup_empty_group(gid); + } + } + + /// Disband a group without closing its member tabs. + pub fn ungroup(&mut self, group_id: TabGroupId) { + for v in &mut self.views { + if v.group == Some(group_id) { + v.group = None; + } + } + self.tab_groups.retain(|g| g.id != group_id); + if self.editing_group == Some(group_id) { + self.editing_group = None; + } + } + + /// Close tabs identified by `keys`: clean tabs go through `request_close_tab`, and + /// dirty tabs are queued in strip order for `begin_close`. + fn close_tab_keys(&mut self, ctx: &egui::Context, keys: Vec) { + for &key in keys.iter().rev() { + let Some(i) = self.tab_with_key(key) else { continue }; + if !self.asks_before_closing(i) { + self.request_close_tab(ctx, i); + } + } + let mut dirty = Vec::new(); + for key in keys { + let Some(i) = self.tab_with_key(key) else { continue }; + if self.hold_close_for_ocr_review(i) { + continue; + } + if self.asks_before_closing(i) + && let Some(v) = self.views.get(i) + && !dirty.contains(&v.id) + { + dirty.push(v.id); + } + } + if !dirty.is_empty() { + self.begin_close(ctx, craft::quit::CloseScope::Close, dirty); + } + } + + /// Close all tabs in a group. + pub fn close_tab_group(&mut self, ctx: &egui::Context, group_id: TabGroupId) { + let keys: Vec = self.views.iter().filter(|v| v.group == Some(group_id)).map(|v| v.pane.key).collect(); + self.close_tab_keys(ctx, keys); + self.cleanup_empty_group(group_id); + } + + /// Toggle collapsed state of a group. + pub fn toggle_group_collapsed(&mut self, group_id: TabGroupId) { + if let Some(g) = self.group_mut(group_id) { + g.collapsed = !g.collapsed; + } + } + + /// Pin or unpin a tab. Pinned tabs sit at the start of their strip. + pub fn set_tab_pinned(&mut self, tab_index: usize, pinned: bool) { + if tab_index >= self.views.len() { + return; + } + let active = self.active_key(); + let place = self.views[tab_index].pane.place; + self.views[tab_index].pinned = pinned; + if pinned { + // Pinned tabs cannot be in a group + let prev_group = self.views[tab_index].group.take(); + if let Some(gid) = prev_group { + self.cleanup_empty_group(gid); + } + // Move to end of pinned tabs in this pane + let target = self + .views + .iter() + .enumerate() + .filter(|(i, v)| *i < tab_index && v.pane.place == place && v.pinned) + .map(|(i, _)| i + 1) + .max() + .or_else(|| self.tabs_in(place).first().copied()) + .unwrap_or(0); + if target < tab_index { + let view = self.views.remove(tab_index); + self.views.insert(target.min(self.views.len()), view); + } + } else { + // Move after all pinned tabs in this pane + let after_pinned = self + .views + .iter() + .enumerate() + .filter(|(i, v)| *i != tab_index && v.pane.place == place && v.pinned) + .map(|(i, _)| if i > tab_index { i } else { i + 1 }) + .max() + .unwrap_or(0); + if tab_index < after_pinned { + let view = self.views.remove(tab_index); + self.views.insert(after_pinned.min(self.views.len()), view); + } + } + self.active = active.and_then(|k| self.tab_with_key(k)); + } + + /// Duplicate a tab (creates a second twin view of the document in the same pane). + pub fn duplicate_tab(&mut self, tab_index: usize) { + let Some(view) = self.views.get(tab_index) else { return }; + let id = view.id; + let group = view.group; + let is_pinned = view.pinned; + let place = view.pane.place; + let Some(doc) = self.session.get(id) else { return }; + let mut twin = view.twin(&doc.info); + twin.pane.place = place; + twin.pane.placed = true; + twin.group = group; + twin.pinned = false; + let at = if is_pinned { + // Unpinned duplicate sits at the start of the unpinned section in this pane, preserving the pinned section + self.views.iter().enumerate().filter(|(_, v)| v.pane.place == place && v.pinned).map(|(i, _)| i + 1).max().unwrap_or(0) + } else { + (tab_index + 1).min(self.views.len()) + }; + self.views.insert(at, twin); + self.active = Some(at); + } + + /// Close all unpinned tabs in the same pane except `keep_index`. + pub fn close_other_tabs(&mut self, ctx: &egui::Context, keep_index: usize) { + let Some(view) = self.views.get(keep_index) else { return }; + let keep_key = view.pane.key; + let place = view.pane.place; + let keys: Vec = self + .tabs_in(place) + .into_iter() + .filter_map(|i| self.views.get(i)) + .filter(|v| v.pane.key != keep_key && !v.pinned) + .map(|v| v.pane.key) + .collect(); + self.close_tab_keys(ctx, keys); + } + + /// Close all unpinned tabs to the right of `from_index` in its pane's strip order. + pub fn close_tabs_to_right(&mut self, ctx: &egui::Context, from_index: usize) { + let Some(place) = self.views.get(from_index).map(|v| v.pane.place) else { return }; + let strip_tabs = self.tabs_in(place); + let Some(pos) = strip_tabs.iter().position(|&i| i == from_index) else { return }; + let keys: Vec = strip_tabs[pos + 1..].iter().filter_map(|&i| self.views.get(i)).filter(|v| !v.pinned).map(|v| v.pane.key).collect(); + self.close_tab_keys(ctx, keys); + } + + /// Remove a group if it has no member tabs remaining. + pub fn cleanup_empty_group(&mut self, group_id: TabGroupId) { + let has_tabs = self.views.iter().any(|v| v.group == Some(group_id)); + if !has_tabs { + self.tab_groups.retain(|g| g.id != group_id); + if self.editing_group == Some(group_id) { + self.editing_group = None; + } + } + } +} + +/// Paint an Edge-styled group header pill (dot, title, and collapse/expand chevron) over `rect`. +pub fn paint_group_pill(ui: &egui::Ui, group: &TabGroup, rect: Rect, hovered: bool) { + let font = egui::FontId::proportional(11.5); + let title = group.title.trim(); + let label = if title.is_empty() { tl!("Tab group") } else { title }; + let text_color = group.color.text_color(); + let bg_color = group.color.color32(); + let fill = if hovered { bg_color.lerp_to_gamma(Color32::WHITE, 0.15) } else { bg_color }; + + let pill_rect = rect.shrink2(vec2(2.0, 2.0)); + ui.painter().rect_filled(pill_rect, CornerRadius::same(5), fill); + + let dot_center = pos2(pill_rect.left() + 10.0, pill_rect.center().y); + ui.painter().circle_filled(dot_center, 3.0, text_color); + + let chevron_center = pos2(pill_rect.right() - 10.0, pill_rect.center().y); + let chevron_stroke = Stroke::new(1.5, text_color); + let open = group.open_progress.clamp(0.0, 1.0); + if group.collapsed && open < 0.5 { + // Right-pointing chevron (collapsed) + ui.painter().line_segment([chevron_center + vec2(-2.0, -3.5), chevron_center + vec2(2.0, 0.0)], chevron_stroke); + ui.painter().line_segment([chevron_center + vec2(2.0, 0.0), chevron_center + vec2(-2.0, 3.5)], chevron_stroke); + } else { + // Down-pointing chevron (expanded) + ui.painter().line_segment([chevron_center + vec2(-3.5, -1.5), chevron_center + vec2(0.0, 2.0)], chevron_stroke); + ui.painter().line_segment([chevron_center + vec2(0.0, 2.0), chevron_center + vec2(3.5, -1.5)], chevron_stroke); + } + + let text_left = pill_rect.left() + 18.0; + let text_right = (pill_rect.right() - 18.0).max(text_left); + let text_clip = Rect::from_min_max(pos2(text_left, pill_rect.top()), pos2(text_right, pill_rect.bottom())); + let galley = ui.painter().layout_no_wrap(label.to_string(), font, text_color); + let text_pos = pos2(text_left, pill_rect.center().y - galley.size().y * 0.5); + ui.painter().with_clip_rect(text_clip).galley(text_pos, galley, text_color); +} + +/// Render the Group Edit Popover (name input, color swatches, new tab in group, ungroup, close group). +pub fn group_editor_popup(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: crate::panes::Place, group_id: TabGroupId, close_popup: &mut bool) { + let Some(group) = app.group(group_id).cloned() else { + *close_popup = true; + return; + }; + + ui.set_min_width(220.0); + Stack::new().show(ui, |ui, _| { + Text::new(tl!("Group name")).show(ui); + let mut title_buf = app.group_title_draft.clone(); + let edit = TextField::new(tl!("Group name"), Bind::bound(&mut title_buf)).submits().show(ui); + if title_buf != app.group_title_draft { + app.group_title_draft = title_buf.clone(); + if let Some(g) = app.group_mut(group_id) { + g.title = title_buf; + } + } + if edit.submitted { + *close_popup = true; + } + + Text::new(tl!("Color")).show(ui); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 6.0); + for &color in &TabGroupColor::ALL { + let [r, g, b, _] = color.color32().to_srgba_unmultiplied(); + let srgba = craft::theme::Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0); + let selected = group.color == color; + if Swatch::new(tl!(color.name()), srgba).shape(SwatchShape::Round).cell().selected(selected).show(ui).clicked + && let Some(g) = app.group_mut(group_id) + { + g.color = color; + } + } + }); + + ui.separator(); + + if Button::new(tl!("New tab in group")).variant(Variant::GHOST).show(ui).clicked() { + app.open_dialog_in_group(Some((group_id, place))); + *close_popup = true; + } + + if Button::new(tl!("Ungroup")).variant(Variant::GHOST).show(ui).clicked() { + app.tab_action(ui.ctx(), crate::tab_context::Action::Ungroup(group_id)); + *close_popup = true; + } + + if Button::new(tl!("Close group")).variant(Variant::GHOST).show(ui).clicked() { + app.tab_action(ui.ctx(), crate::tab_context::Action::CloseGroup(group_id)); + *close_popup = true; + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + const FIXTURE: &[u8] = include_bytes!("../tests/data/form.pdf"); + + #[test] + fn create_and_manage_tab_groups() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "doc1.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc2.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc3.pdf", None, FIXTURE.to_vec()).unwrap(); + + assert_eq!(app.views.len(), 3); + assert_eq!(app.tab_groups.len(), 0); + + let gid = app.create_tab_group("Research".into(), TabGroupColor::Blue); + assert_eq!(app.tab_groups.len(), 1); + assert_eq!(app.tab_groups[0].title, "Research"); + assert_eq!(app.tab_groups[0].color, TabGroupColor::Blue); + assert!(!app.tab_groups[0].collapsed); + + app.add_tab_to_group(0, gid); + app.add_tab_to_group(1, gid); + + assert_eq!(app.views[0].group, Some(gid)); + assert_eq!(app.views[1].group, Some(gid)); + assert_eq!(app.views[2].group, None); + + app.toggle_group_collapsed(gid); + assert!(app.tab_groups[0].collapsed); + app.toggle_group_collapsed(gid); + assert!(!app.tab_groups[0].collapsed); + + app.remove_tab_from_group(0); + assert_eq!(app.views[0].group, None); + assert_eq!(app.views[1].group, Some(gid)); + + app.ungroup(gid); + assert_eq!(app.tab_groups.len(), 0); + assert_eq!(app.views[1].group, None); + } + + #[test] + fn pin_and_unpin_tabs() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "doc1.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc2.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc3.pdf", None, FIXTURE.to_vec()).unwrap(); + + app.set_tab_pinned(2, true); + assert!(app.views[0].pinned); + assert_eq!(app.session.get(app.views[0].id).unwrap().name, "doc3.pdf"); + + app.set_tab_pinned(0, false); + assert!(!app.views[0].pinned); + } + + #[test] + fn duplicate_and_close_tab_actions() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "doc1.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc2.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc3.pdf", None, FIXTURE.to_vec()).unwrap(); + + app.duplicate_tab(1); + assert_eq!(app.views.len(), 4); + assert_eq!(app.views[1].id, app.views[2].id); + + app.close_tabs_to_right(&ctx, 0); + assert_eq!(app.views.len(), 1); + assert_eq!(app.session.get(app.views[0].id).unwrap().name, "doc1.pdf"); + } + + #[test] + fn close_other_tabs_action() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "doc1.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc2.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc3.pdf", None, FIXTURE.to_vec()).unwrap(); + + app.close_other_tabs(&ctx, 1); + assert_eq!(app.views.len(), 1); + assert_eq!(app.session.get(app.views[0].id).unwrap().name, "doc2.pdf"); + } + + #[test] + fn close_tab_group_action() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "doc1.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc2.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc3.pdf", None, FIXTURE.to_vec()).unwrap(); + + let gid = app.create_tab_group("Work".into(), TabGroupColor::Green); + app.add_tab_to_group(0, gid); + app.add_tab_to_group(1, gid); + + app.close_tab_group(&ctx, gid); + assert_eq!(app.tab_groups.len(), 0); + assert_eq!(app.views.len(), 1); + assert_eq!(app.session.get(app.views[0].id).unwrap().name, "doc3.pdf"); + } + + #[test] + fn add_pinned_tab_to_empty_group_moves_past_pinned_tabs() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "doc1.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc2.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc3.pdf", None, FIXTURE.to_vec()).unwrap(); + + // Pin doc1 and doc2 + app.set_tab_pinned(0, true); + app.set_tab_pinned(1, true); + assert!(app.views[0].pinned); + assert!(app.views[1].pinned); + + // Add doc1 (index 0) to a new empty group + let gid = app.create_tab_group("Test".into(), TabGroupColor::Blue); + app.add_tab_to_group(0, gid); + + // doc1 is now unpinned and in the group, and must be after remaining pinned doc2 + assert!(!app.views[1].pinned); + assert_eq!(app.views[1].group, Some(gid)); + assert!(app.views[0].pinned); + assert_eq!(app.session.get(app.views[0].id).unwrap().name, "doc2.pdf"); + assert_eq!(app.session.get(app.views[1].id).unwrap().name, "doc1.pdf"); + } + + #[test] + fn dragging_a_member_to_the_edge_of_another_group_ungroups_it() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + for name in ["a1.pdf", "a2.pdf", "b1.pdf", "b2.pdf"] { + app.open_bytes(&ctx, name, None, FIXTURE.to_vec()).unwrap(); + } + let a = app.create_tab_group("A".into(), TabGroupColor::Blue); + let b = app.create_tab_group("B".into(), TabGroupColor::Green); + app.add_tab_to_group(0, a); + app.add_tab_to_group(1, a); + app.add_tab_to_group(2, b); + app.add_tab_to_group(3, b); + + // Drag a1.pdf behind b2.pdf: it sits after group B's last member, so it joins neither + // group, and group A keeps a2.pdf. + let tabs = app.tabs_in(crate::panes::Place::Main); + app.move_tab_in_strip(0, &tabs, 3); + + let names: Vec = app.views.iter().map(|v| app.session.get(v.id).unwrap().name.clone()).collect(); + assert_eq!(names, ["a2.pdf", "b1.pdf", "b2.pdf", "a1.pdf"]); + assert_eq!(app.views[3].group, None); + assert_eq!(app.views[0].group, Some(a)); + assert_eq!(app.views[2].group, Some(b)); + } + + #[test] + fn moving_last_member_to_another_group_cleans_up_previous_group() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "doc1.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc2.pdf", None, FIXTURE.to_vec()).unwrap(); + + let g1 = app.create_tab_group("G1".into(), TabGroupColor::Blue); + let g2 = app.create_tab_group("G2".into(), TabGroupColor::Green); + app.add_tab_to_group(0, g1); + app.add_tab_to_group(1, g2); + + assert_eq!(app.tab_groups.len(), 2); + // Move doc1 from g1 to g2 + app.add_tab_to_group(0, g2); + + // g1 is now empty and should be cleaned up + assert_eq!(app.tab_groups.len(), 1); + assert_eq!(app.tab_groups[0].id, g2); + } + + #[test] + fn multi_dirty_bulk_close_with_close_guard() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + let bytes = app.session.create_blank(200.0, 300.0, 1).unwrap(); + app.open_bytes(&ctx, "doc1.pdf", None, bytes.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc2.pdf", None, bytes.to_vec()).unwrap(); + app.open_bytes(&ctx, "doc3.pdf", None, bytes.to_vec()).unwrap(); + + // Mark doc2 and doc3 dirty by applying edits + app.active = Some(1); + assert!(app.apply_edit(&ctx, pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 })); + app.active = Some(2); + assert!(app.apply_edit(&ctx, pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 })); + app.active = Some(0); + + app.close_tabs_to_right(&ctx, 0); + + // Dirty tabs held by close_guard + assert!(app.close_guard.is_some()); + assert_eq!(app.views.len(), 3); + } + + #[test] + fn close_other_and_to_right_respect_pane_strip_order_and_keep_pinned() { + let mut app = PdfCraftApp::for_unit_tests(); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "pinned.pdf", Some("/tmp/pinned.pdf".into()), FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "main_a.pdf", Some("/tmp/main_a.pdf".into()), FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "main_b.pdf", Some("/tmp/main_b.pdf".into()), FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "second.pdf", Some("/tmp/second.pdf".into()), FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "main_c.pdf", Some("/tmp/main_c.pdf".into()), FIXTURE.to_vec()).unwrap(); + + app.set_tab_pinned(0, true); + // Move second.pdf (index 3) to the second pane, leaving Main tabs interleaved around it in `views`. + app.move_tab_to(3, crate::panes::Place::Second); + assert_eq!(app.views[3].place(), crate::panes::Place::Second); + assert_eq!(app.views[4].place(), crate::panes::Place::Main); + + // Close tabs to the right of main_a.pdf (index 1) in Place::Main. + app.close_tabs_to_right(&ctx, 1); + let remaining: Vec = app.views.iter().map(|v| app.session.get(v.id).unwrap().name.clone()).collect(); + assert_eq!(remaining, ["pinned.pdf", "main_a.pdf", "second.pdf"]); + + // Reopen another main tab and run close_other_tabs on it: pinned.pdf and second.pdf stay open. + app.open_bytes(&ctx, "main_d.pdf", None, FIXTURE.to_vec()).unwrap(); + let keep_idx = app.views.len() - 1; + app.close_other_tabs(&ctx, keep_idx); + let remaining: Vec = app.views.iter().map(|v| app.session.get(v.id).unwrap().name.clone()).collect(); + assert_eq!(remaining, ["pinned.pdf", "second.pdf", "main_d.pdf"]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn open_path_in_group_adds_opened_tab_to_group() { + use std::io::Write as _; + use std::sync::Arc; + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("pdfcraft-group-open-{}-{nonce}.pdf", std::process::id())); + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).unwrap(); + file.write_all(FIXTURE).unwrap(); + drop(file); + + let jobs = Arc::new(craft::host::ManualJobs::new()); + let host = craft::host::Host::builder(crate::APP_INFO).jobs(jobs.clone()).build(); + let mut app = PdfCraftApp::for_unit_tests_on(Arc::new(host)); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "first.pdf", None, FIXTURE.to_vec()).unwrap(); + let gid = app.create_tab_group("Bundle".into(), TabGroupColor::Purple); + app.add_tab_to_group(0, gid); + + app.open_path_in_group(path.to_str().unwrap(), Some((gid, crate::panes::Place::Main))); + jobs.run_all(); + app.poll_pending_opens(&ctx); + + assert_eq!(app.views.len(), 2); + assert_eq!(app.views[1].group, Some(gid)); + std::fs::remove_file(path).unwrap(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn open_path_in_group_in_second_pane_places_tab_next_to_group() { + use std::io::Write as _; + use std::sync::Arc; + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let filename = format!("pdfcraft-split-group-open-{}-{nonce}.pdf", std::process::id()); + let path = std::env::temp_dir().join(&filename); + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).unwrap(); + file.write_all(FIXTURE).unwrap(); + drop(file); + + let jobs = Arc::new(craft::host::ManualJobs::new()); + let host = craft::host::Host::builder(crate::APP_INFO).jobs(jobs.clone()).build(); + let mut app = PdfCraftApp::for_unit_tests_on(Arc::new(host)); + let ctx = egui::Context::default(); + app.open_bytes(&ctx, "main.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "grouped.pdf", None, FIXTURE.to_vec()).unwrap(); + app.open_bytes(&ctx, "unrelated.pdf", None, FIXTURE.to_vec()).unwrap(); + app.settle_panes(&ctx); + + // Put grouped.pdf and unrelated.pdf in the second (right) pane, with grouped.pdf before unrelated.pdf. + app.move_tab_to(1, crate::panes::Place::Second); + app.move_tab_to(2, crate::panes::Place::Second); + let gid = app.create_tab_group("RightBundle".into(), TabGroupColor::Blue); + app.add_tab_to_group(1, gid); + app.active = Some(1); + app.settle_panes(&ctx); + + app.open_path_in_group(path.to_str().unwrap(), Some((gid, crate::panes::Place::Second))); + jobs.run_all(); + app.poll_pending_opens(&ctx); + app.settle_panes(&ctx); + + let second_names: Vec = + app.tabs_in(crate::panes::Place::Second).into_iter().map(|i| app.session.get(app.views[i].id).unwrap().name.clone()).collect(); + let main_names: Vec = + app.tabs_in(crate::panes::Place::Main).into_iter().map(|i| app.session.get(app.views[i].id).unwrap().name.clone()).collect(); + assert_eq!(main_names, ["main.pdf"]); + assert_eq!(second_names, ["grouped.pdf", filename.as_str(), "unrelated.pdf"]); + let new_idx = app.tabs_in(crate::panes::Place::Second)[1]; + assert_eq!(app.views[new_idx].group, Some(gid)); + assert_eq!(app.views[new_idx].place(), crate::panes::Place::Second); + + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/ui-egui/tests/it/commands.rs b/crates/ui-egui/tests/it/commands.rs index 523f6b931c..fc71c7f4bc 100644 --- a/crates/ui-egui/tests/it/commands.rs +++ b/crates/ui-egui/tests/it/commands.rs @@ -451,7 +451,8 @@ fn escape_leaves_full_screen(h: &mut Harness<'static, PdfCraftApp>, _c: &Control assert!(!h.state().full_screen(), "Escape leaves full screen"); } -/// Check that choosing Edit ▸ Pages ▸ Delete pages in the menu bar reduces the page count once. +/// Check that choosing Edit ▸ Pages ▸ Delete pages in the menu bar asks, and the confirmation +/// deletes the page once. #[test] fn the_pages_menu_comes_from_the_registry() { let mut h = harness(); @@ -460,6 +461,9 @@ fn the_pages_menu_comes_from_the_registry() { h.run_steps(3); support::menu_row(&h, "Delete pages").click(); h.run_steps(3); + // The menu's ask opens the dialog; Delete confirms the deletion. + h.get_by_label("Delete").click(); + h.run_steps(3); let app = h.state(); assert_eq!(app.session.get(app.views[0].id).unwrap().info.pages.len(), 2); } diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs index 8f75098cbc..0a763f9763 100644 --- a/crates/ui-egui/tests/it/editing.rs +++ b/crates/ui-egui/tests/it/editing.rs @@ -6274,6 +6274,9 @@ fn pages_panel_escape_clears_and_deleted_pages_leave_the_selection() { h.state_mut().views[0].select_pages(&[3, 4]); assert!(h.execute("page.delete")); h.run_steps(3); + // The command's ask opens the dialog; Delete confirms the deletion. + h.get_by_label("Delete").click(); + h.run_steps(3); assert_eq!(page_texts(h.state()).len(), 3); assert!(picked(&h).iter().all(|p| *p < 3), "{:?}", picked(&h)); } @@ -6396,6 +6399,9 @@ fn deleting_pages_from_the_pages_panel_menu() { let at = panel_thumb(&h, "Page 2"); right_click_at(&mut h, at); h.get_by_label("Delete pages").click(); + h.run_steps(3); + // The ask opens the dialog; Delete confirms the deletion. + h.get_by_label("Delete").click(); h.run_steps(4); assert_eq!(page_texts(h.state()), ["Page 1", "Page 3", "Page 4"]); assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Delete page")); @@ -6431,6 +6437,9 @@ fn the_delete_key_deletes_pages_picked_in_the_pages_panel_but_never_every_page() h.run_steps(1); h.key_press(Key::Delete); h.run_steps(4); + // The ask opens the dialog; Delete confirms the deletion of pages 2 and 3. + h.get_by_label("Delete").click(); + h.run_steps(3); assert_eq!(page_texts(h.state()), ["Page 1"]); assert_eq!(h.state().views[0].current(), 0); } @@ -8220,9 +8229,153 @@ fn delete_with_the_pointer_on_the_pages_panel_deletes_a_page() { h.run_steps(2); h.key_press(egui::Key::Delete); h.run_steps(4); + // The ask opens the dialog; Delete confirms the page goes. + h.get_by_label("Delete").click(); + h.run_steps(4); assert_eq!(h.state().session.get(id).unwrap().info.pages.len(), pages - 1, "a page goes"); } +/// An edit that runs between the Pages panel capturing the pages and the ask being processed +/// makes those indices stale: the ask is dropped, so it never names the newer document. +#[test] +fn an_edit_before_the_pages_delete_ask_is_processed_drops_the_ask() { + let mut h = pages_panel(5); + let id = h.state().views[0].id; + let generation = h.state().session.get(id).unwrap().edit_generation(); + // A queued move runs before the ask is processed, and the move succeeds: the captured pages + // no longer name the moved-to document. + h.state_mut().views[0].session.pending_edit = Some(pdfcraft_engine::Edit::MovePages { pages: vec![0], to: 5 }); + h.state_mut().views[0].pending_action = Some(pdfcraft_ui_egui::canvas::ViewAction::ConfirmDeletePages { pages: vec![0], generation }); + h.run_steps(4); + assert_eq!(page_texts(h.state()), ["Page 2", "Page 3", "Page 4", "Page 5", "Page 1"], "the move ran"); + assert!(!crate::support::dialog_open(&h), "the stale ask is dropped"); + assert_eq!(h.state().session.get(id).unwrap().info.pages.len(), 5); +} + +/// Cancel in the pages delete ask deletes nothing: the ask closes, the pages stay, and the ask +/// carries nothing after it — confirming again queues no deletion either. +#[test] +fn cancel_in_the_pages_delete_ask_deletes_nothing() { + let mut h = pages_panel(5); + let ctx = h.ctx.clone(); + h.state_mut().views[0].select_pages(&[0]); + h.run_steps(2); + assert!(h.execute("page.delete")); + h.run_steps(3); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert!(!crate::support::dialog_open(&h), "the ask is closed"); + assert_eq!(page_texts(h.state()).len(), 5, "cancel deletes nothing"); + // The draft went with it: a confirm after the cancel queues nothing. + h.state_mut().confirm_delete_pages(&ctx); + h.run_steps(2); + assert_eq!(page_texts(h.state()).len(), 5); +} + +/// Dismissing the pages delete ask (Escape) deletes nothing and drops the ask with it. +#[test] +fn dismissing_the_pages_delete_ask_deletes_nothing() { + let mut h = pages_panel(5); + let ctx = h.ctx.clone(); + h.state_mut().views[0].select_pages(&[0]); + h.run_steps(2); + assert!(h.execute("page.delete")); + h.run_steps(3); + h.key_press(Key::Escape); + h.run_steps(3); + assert!(!crate::support::dialog_open(&h), "the ask is dismissed"); + assert_eq!(page_texts(h.state()).len(), 5, "dismissing deletes nothing"); + h.state_mut().confirm_delete_pages(&ctx); + h.run_steps(2); + assert_eq!(page_texts(h.state()).len(), 5); +} + +/// A document that changed while the pages delete ask was open deletes nothing: those indices +/// would name the newer document's pages. +#[test] +fn a_document_changed_behind_the_open_pages_delete_ask_deletes_nothing() { + let mut h = pages_panel(5); + let ctx = h.ctx.clone(); + h.state_mut().views[0].select_pages(&[0]); + h.run_steps(2); + assert!(h.execute("page.delete")); + h.run_steps(3); + // An edit runs behind the open ask: confirming must not apply the captured pages to it. + h.state_mut().apply_edit(&ctx, pdfcraft_engine::Edit::RotatePages { pages: vec![1], degrees: 90 }); + h.run_steps(2); + h.get_by_label("Delete").click(); + h.run_steps(3); + assert_eq!(page_texts(h.state()).len(), 5, "the changed document deletes nothing"); + // The draft went with it: a second confirm queues nothing either. + h.state_mut().confirm_delete_pages(&ctx); + h.run_steps(2); + assert_eq!(page_texts(h.state()).len(), 5); +} + +/// After deleting pages through the confirmation, the selection and Shift-click anchor are +/// cleared, so a subsequent Shift-click ranges from the new current page. +#[test] +fn shift_click_anchor_resets_after_page_deletion() { + let mut h = harness(6, |_| {}); + let ctx = h.ctx.clone(); + + // Click Page 2 (idx 1). + h.state_mut().views[0].view.current = 1; + h.state_mut().views[0].clear_page_selection(Some(1)); + // Select Page 2 and Page 3. + h.state_mut().views[0].selected = craft::behavior::Selection::new(vec![1, 2], Some(2), Some(1)); + assert_eq!(h.state().views[0].selected.items, vec![1, 2]); + + // Request deletion of pages 1 and 2, then confirm. + h.state_mut().request_delete_pages(0, vec![1, 2]); + h.state_mut().confirm_delete_pages(&ctx); + h.run_steps(3); + + assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().info.pages.len(), 4); + assert_eq!(h.state().views[0].current(), 1); + assert!(h.state().views[0].selected.items.is_empty(), "selection is cleared"); + + // Shift-click original Page 6 (now index 3 in the 4-page doc): + // In craft framework Selection, extend_to extends from anchor (which clear_page_selection(None) reset) + // or falls back to current. + let anchor = h.state().views[0].selected.anchor.unwrap_or(h.state().views[0].current()); + let low = anchor.min(3); + let high = anchor.max(3); + h.state_mut().views[0].selected = craft::behavior::Selection::new((low..=high).collect(), Some(3), Some(anchor)); + // Range must be from current (1) to 3: [1, 2, 3] (original Pages 4, 5, 6), not [2, 3]. + assert_eq!(h.state().views[0].selected.items, vec![1, 2, 3]); +} + +/// When page deletion fails (e.g. disallowed by permissions or signed rewrite guard), the +/// current page is preserved instead of remapping as if pages were removed. +#[test] +fn preserve_current_page_when_deletion_fails() { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|cc| { + crate::support::install_runtime(&cc.egui_ctx); + { + let mut app = scripted_app(); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app.open_bytes(&egui::Context::default(), "doc.pdf", None, protected("", "owner", 0b0100)).expect("fixture opens"); + app + } + }); + h.run_steps(4); + let ctx = h.ctx.clone(); + assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().info.pages.len(), 2); + + // Navigate to Page 2 (idx 1). + h.state_mut().views[0].view.current = 1; + + // Request deleting Page 2 and confirm. + h.state_mut().request_delete_pages(0, vec![1]); + h.state_mut().confirm_delete_pages(&ctx); + h.run_steps(3); + + // Deletion was rejected: both pages remain, and view stays on Page 2. + assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().info.pages.len(), 2); + assert_eq!(h.state().views[0].current(), 1); +} + /// In crop mode, a right-click on another picture selects it for its menu, as without crop mode. It /// went to crop mode's whole-page hit, which unselected every picture. #[test] diff --git a/crates/ui-egui/tests/it/ui.rs b/crates/ui-egui/tests/it/ui.rs index c478217298..d2f2fd88d6 100644 --- a/crates/ui-egui/tests/it/ui.rs +++ b/crates/ui-egui/tests/it/ui.rs @@ -1776,6 +1776,121 @@ fn the_combine_tab_does_not_move_and_documents_stay_in_order() { assert_eq!(h.state().views.iter().map(|view| view.id).collect::>(), ids); } +#[test] +fn tab_group_collapsing_and_expanding_harness() { + use egui::accesskit::Role; + let mut h = three_tab_harness(); + let gid = h.state_mut().create_tab_group("Project".into(), pdfcraft_ui_egui::TabGroupColor::Cyan); + h.state_mut().add_tab_to_group(0, gid); + h.state_mut().add_tab_to_group(1, gid); + h.run_steps(3); + + // Both grouped tabs and last tab are visible + assert!(h.query_by_role_and_label(Role::Tab, "first.pdf").is_some()); + assert!(h.query_by_role_and_label(Role::Tab, "middle.pdf").is_some()); + assert!(h.query_by_role_and_label(Role::Tab, "last.pdf").is_some()); + + // Collapse the group + h.state_mut().toggle_group_collapsed(gid); + h.run_steps(3); + + // Grouped tabs are collapsed into the pill + assert!(h.query_by_role_and_label(Role::Tab, "first.pdf").is_none()); + assert!(h.query_by_role_and_label(Role::Tab, "middle.pdf").is_none()); + assert!(h.query_by_role_and_label(Role::Tab, "last.pdf").is_some()); + + // Expand the group again + h.state_mut().toggle_group_collapsed(gid); + h.run_steps(3); + + assert!(h.query_by_role_and_label(Role::Tab, "first.pdf").is_some()); + assert!(h.query_by_role_and_label(Role::Tab, "middle.pdf").is_some()); + assert!(h.query_by_role_and_label(Role::Tab, "last.pdf").is_some()); + + // Clicking the group pill collapses and expands the group + h.get_by_role_and_label(Role::Tab, "Project").click(); + h.run_steps(3); + assert!(h.query_by_role_and_label(Role::Tab, "first.pdf").is_none()); + assert!(h.query_by_role_and_label(Role::Tab, "middle.pdf").is_none()); + + h.get_by_role_and_label(Role::Tab, "Project").click(); + h.run_steps(3); + assert!(h.query_by_role_and_label(Role::Tab, "first.pdf").is_some()); + assert!(h.query_by_role_and_label(Role::Tab, "middle.pdf").is_some()); + + // Secondary-clicking the group pill opens the group editor popover + h.get_by_role_and_label(Role::Tab, "Project").click_secondary(); + h.run_steps(3); + assert!(h.query_by_role_and_label(Role::TextInput, "Group name").is_some()); + assert!(h.query_by_label("New tab in group").is_some()); + assert!(h.query_by_label("Ungroup").is_some()); + assert!(h.query_by_label("Close group").is_some()); + + // Clicking Ungroup disbands the group and closes the editor popover + h.get_by_role_and_label(Role::Button, "Ungroup").click(); + h.run_steps(3); + assert!(h.state().tab_groups.is_empty()); + assert_eq!(h.state().views[0].group, None); + assert_eq!(h.state().views[1].group, None); + assert!(h.query_by_role_and_label(Role::TextInput, "Group name").is_none()); +} + +#[test] +fn tab_dragging_between_grouped_tabs_adopts_group() { + let mut h = three_tab_harness(); + let gid = h.state_mut().create_tab_group("Work".into(), pdfcraft_ui_egui::TabGroupColor::Green); + h.state_mut().add_tab_to_group(0, gid); + h.state_mut().add_tab_to_group(1, gid); + h.run_steps(3); + + // doc 0 and 1 are in group, doc 2 is ungrouped + assert_eq!(h.state().views[0].group, Some(gid)); + assert_eq!(h.state().views[1].group, Some(gid)); + assert_eq!(h.state().views[2].group, None); + + // Drag last.pdf between doc 0 and doc 1 + let last_key = h.state().views[2].view_key(); + let tab = |h: &Harness<'static, PdfCraftApp>, name: &str| h.get_by_role_and_label(egui::accesskit::Role::Tab, name).rect(); + let to = tab(&h, "first.pdf").right_center() + egui::vec2(2.0, 0.0); + drag_named_tab(&mut h, "last.pdf", to, true); + + // last.pdf was dropped between two members of the group, so it adopted the group! + assert_eq!(h.state().views[1].view_key(), last_key); + assert_eq!(h.state().views[1].group, Some(gid)); +} + +#[test] +fn pinned_tabs_cannot_be_closed_with_middle_click() { + let mut h = three_tab_harness(); + h.state_mut().set_tab_pinned(0, true); + h.run_steps(3); + + assert!(h.state().views[0].pinned); + let initial_count = h.state().views.len(); + + // Middle click on pinned tab + let pinned_rect = h.get_by_role_and_label(egui::accesskit::Role::Tab, "first.pdf (pinned)").rect(); + h.event(egui::Event::PointerMoved(pinned_rect.center())); + h.event(egui::Event::PointerButton { + pos: pinned_rect.center(), + button: egui::PointerButton::Middle, + pressed: true, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + h.event(egui::Event::PointerButton { + pos: pinned_rect.center(), + button: egui::PointerButton::Middle, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(3); + + // Tab was NOT closed because pinned tabs stay protected + assert_eq!(h.state().views.len(), initial_count); + assert!(h.state().views[0].pinned); +} + /// The Edit tab turns on Edit text & images at once, as Acrobat does, so every paragraph and image /// is boxed and editable with one click; another tab puts the tool down again. #[test] diff --git a/crates/ui-egui/tests/it/view.rs b/crates/ui-egui/tests/it/view.rs index 963ba2d5a2..be656eb3dd 100644 --- a/crates/ui-egui/tests/it/view.rs +++ b/crates/ui-egui/tests/it/view.rs @@ -2237,6 +2237,9 @@ fn the_pages_panel_tools_act_on_the_selected_pages() { h.state_mut().views[0].select_pages(&[0]); h.run_steps(2); tool(&mut h, "page.delete"); + // The panel's ask opens the dialog; Delete confirms the deletion. + h.get_by_label("Delete").click(); + h.run_steps(3); assert_eq!(h.state().session.get(id).unwrap().info.pages.len(), 2, "page 1 deleted"); tool(&mut h, "page.insert_blank"); assert_eq!(h.state().session.get(id).unwrap().info.pages.len(), 3); diff --git a/docs/development.md b/docs/development.md index 80fc909f48..1ff21e816e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -154,6 +154,7 @@ copies retain their current preferences locations. | `PDFCRAFT_TITLEBAR` | Linux: `app` draws PdfCraft's own title bar (window buttons in the tab strip, in the order of GNOME's `button-layout`, and resize edges); `system` keeps the frame winit or the desktop draws; unset, PdfCraft draws its own when the Wayland compositor draws no frames (GNOME), and leaves it to the desktop otherwise (KDE, Sway, Hyprland, X11). Where PdfCraft draws it, Preferences ▸ Use system title bar switches back to winit's frame without a restart; `system` also hides that option | | `PDFCRAFT_BUILD_LABEL` | Build time: a label for a local or patched build (letters, digits, inner dots), shown after the version in `--version`, About and the log (`0.7.1 (titlebar)`). `packaging/linux/package.sh` also puts it in the file names and the .rpm/.deb release (`1.titlebar`), which upgrades over the release of the same version | | `CRAFT_FONTS_DIR` | Build time: a [craft-fonts](https://github.com/storytold/craft-fonts) checkout to embed (Japanese fonts) | +| `CRAFT_I18N_DIR` | Build time: a [craft-i18n](https://github.com/storytold/craft-i18n) checkout, at the commit in `craft-i18n.rev`, whose catalogs the build embeds. Unset, the build is English only; `CRAFT_I18N_REQUIRED=1` makes that an error (see [localization](localization.md)) | | `PDFCRAFT_SYSTEM_FONTS` | `0` disables installed-font fallback for both interface text and non-embedded CJK page text in the desktop viewer, Combine thumbnails and accessibility figure previews (`cargo xtask screenshots` sets it). Document fallback is display-only: exports, printing, OCR and automation retain the bundled-font path. | | `FONTCONFIG_FILE` | On Linux/Unix, the Fontconfig configuration file used to discover installed UI fallback fonts (default: `/etc/fonts/fonts.conf`); relative filenames are resolved under `FONTCONFIG_PATH` | | `FONTCONFIG_PATH` | Directory for a relative `FONTCONFIG_FILE` (default: `/etc/fonts`; the first entry of a search path is used) |