feat(shell): document tabs above the stage, each with its own session, view and autosave; New and Open bring a tab, closing asks about unsaved changes, quitting asks once for all (M8)

This commit is contained in:
Tanish Manku committed 2026-11-18 01:24:58 -07:00
1 parent 2ccb66a96f
commit 0f90ef98bc
20 files changed
+1588 -108

No files matched your search

+7
View File
@@ -687,6 +687,13 @@ impl Session {
self.history.budget_bytes = budget;
}
/// Drops what the session keeps only to draw faster (its display list and the picture of an
/// open symbol in place): a document put aside while another is shown keeps none (ADR 0112).
pub fn drop_caches(&self) {
self.dl_cache.replace(None);
self.picture_cache.replace(None);
}
/// Takes over from `from` what belongs to the editor rather than to one document (ADR
/// 0112): the clipboards, the tool style, the plug-ins, recent files, brushes and filter
/// presets, and how the rulers, grid and guides show. An editor with several documents open
+12
View File
@@ -372,6 +372,12 @@ impl FrameCache {
self.bytes = self.bytes.saturating_sub(cpu);
self.native_bytes = self.native_bytes.saturating_sub(gpu);
}
/// Forgets every picture (the document they show is no longer on screen, ADR 0112).
pub fn clear(&mut self) {
self.map.clear();
self.bytes = 0;
self.native_bytes = 0;
}
pub fn len(&self) -> usize {
self.map.len()
}
@@ -575,6 +581,12 @@ impl RenderService {
!q.busy.is_empty() || !q.urgent.is_empty() || !q.prefetch.is_empty()
}
/// Forgets every finished picture, in memory and on the GPU: an editor showing another
/// document calls it, so the one put aside keeps no pictures (ADR 0112).
pub fn forget_pictures(&self) {
self.cache().clear();
}
/// `(images, bytes, hits, misses)`.
pub fn cache_stats(&self) -> (usize, usize, u64, u64) {
let c = self.cache();
+4
View File
@@ -98,6 +98,10 @@ This page is generated from the editor's shortcut map, so it always matches the
| Find Next | F3 | F3 |
| Find Previous | Shift+F3 | ⇧F3 |
| Movie Explorer | Alt+F3 | ⌥F3 |
| Close Document | Ctrl+W | ⌘W |
| Close All Documents | Ctrl+Alt+W | ⌥⌘W |
| Next Document | Ctrl+PageDown | ⌘PageDown |
| Previous Document | Ctrl+PageUp | ⌘PageUp |
| Brush Size Down | \[ | \[ |
| Brush Size Up | \] | \] |
| Zoom in / out | Ctrl+=, Ctrl+- | ⌘=, ⌘- |
+65 -34
View File
@@ -565,11 +565,11 @@ pub struct App {
/// The Custom Ease window (ADR 0081), when open.
pub ease: Option<crate::ease_editor::EaseEditor>,
pub show_shortcuts: bool,
/// The window close was intercepted because of unsaved changes.
pub close_dialog: bool,
/// The open documents (ADR 0112): the one being edited is `s`, the others wait in their
/// tabs. Closing one, or the window, with unsaved changes asks first (`tabs::CloseFlow`).
pub tabs: crate::tabs::Tabs,
/// The window may close: every document's unsaved changes were saved or given up.
pub allow_close: bool,
/// Close the window once the pending Save As succeeds.
pub close_after_save: bool,
pub prefs: prefs::Prefs,
pub show_prefs: bool,
/// This copy as an AppImage, and its applications menu entry (ADR 0094); `None` elsewhere.
@@ -589,7 +589,7 @@ pub struct App {
system_clipboard: bool,
swallowed_paste: platform::SwallowedPaste,
/// Document revision at the end of the last frame (edits schedule a repaint).
last_revision: u64,
pub(crate) last_revision: u64,
title: String,
/// Keyboard shortcuts in effect (defaults plus the user's changes) and their lookup table.
pub keymap: keymap::Keymap,
@@ -603,7 +603,7 @@ pub struct App {
/// Playback follows the sound's clock (the movie has sounds and the device plays them).
audio_clock: bool,
/// The scene and frame last heard, so a moved playhead plays a snippet (scrubbing).
heard: Option<(usize, u32)>,
pub(crate) heard: Option<(usize, u32)>,
/// The panel Ctrl+F6 last moved focus to (where the next press continues from).
pub last_panel: Option<crate::a11y::Region>,
/// The stage's elements as keyboard stops and screen-reader nodes (ADR 0064).
@@ -663,6 +663,12 @@ pub const VIEW_SHORTCUTS: &[(&str, &str)] = &[
("F3", "view.find_next"),
("Shift+F3", "view.find_prev"),
("Alt+F3", "view.movie_explorer"),
// The open documents (ADR 0112): Close and Close All as in Animate, and the tab keys of
// browsers (Ctrl+Tab and Ctrl+Shift+Tab work too).
("Ctrl+W", "view.close_document"),
("Ctrl+Alt+W", "view.close_all_documents"),
("Ctrl+PageDown", "view.next_document"),
("Ctrl+PageUp", "view.prev_document"),
// Brush size, as in paint programs.
("[", "view.brush_smaller"),
("]", "view.brush_larger"),
@@ -710,6 +716,8 @@ impl App {
let _ = anicraft_engine::text::Fonts::get();
});
let mut session = session;
// The sample or a blank page gives way to the first document opened (ADR 0112).
let placeholder = session.path.is_none() && !session.is_dirty();
// Open Recent is the session's list, kept in the preferences (ADR 0059).
session.recent = prefs.recent.clone();
session.brushes = prefs.brushes.clone();
@@ -837,9 +845,8 @@ impl App {
envelope: None,
ease: None,
show_shortcuts: false,
close_dialog: false,
tabs: crate::tabs::Tabs::new(placeholder),
allow_close: false,
close_after_save: false,
prefs,
show_prefs: false,
desktop: None,
@@ -1302,6 +1309,7 @@ impl App {
#[cfg(not(target_arch = "wasm32"))]
Some("updates") => self.updates.request(),
Some("files") => self.show_files = true,
Some("tabs") => crate::tabs::sample(self),
Some("start") => {
// The start screen with sample recent files (one pinned, one missing).
crate::start::open(self);
@@ -2988,7 +2996,7 @@ impl App {
/// Any modal (prompt, confirmation, close guard) is open: global shortcuts pause.
pub fn modal_open(&self) -> bool {
self.prompt.is_some() || self.convert.is_some() || self.shape_dialog.is_some() || self.confirm.is_some() || self.close_dialog || self.plugin_dialog.is_some() || self.templates.save.is_some()
self.prompt.is_some() || self.convert.is_some() || self.shape_dialog.is_some() || self.confirm.is_some() || self.tabs.asking() || self.plugin_dialog.is_some() || self.templates.save.is_some()
}
/// The single entry point for user-initiated commands: asks first when the engine says the
@@ -3001,6 +3009,12 @@ impl App {
{
o.insert("folder".into(), json!(f.display().to_string()));
}
// New and Open bring their document in a tab of its own (ADR 0112): the one being
// edited stays open, so there is nothing to ask about.
if crate::tabs::opens_document(id) {
self.perform(id, params);
return;
}
if let Some(c) = self.s.confirmation(id, &params)
&& (c.irreversible || !self.skip_confirm.contains(id))
{
@@ -3011,8 +3025,17 @@ impl App {
self.perform(id, params);
}
/// Runs a command and reports the outcome; routine destructive edits say how to undo.
/// Runs a command and reports the outcome; routine destructive edits say how to undo. A
/// command that brings a document (New, Open, a restored copy) runs in a new tab (ADR 0112).
pub fn perform(&mut self, id: &str, params: Value) -> Option<Value> {
if crate::tabs::opens_document(id) {
return crate::tabs::open(self, id, params);
}
self.perform_here(id, params)
}
/// [`App::perform`] on the document being edited, whatever the command.
pub(crate) fn perform_here(&mut self, id: &str, params: Value) -> Option<Value> {
if id == "file.publish" {
// File › Publish runs in the background, with its own progress view (ADR 0060).
crate::publish_panel::start(self, &params);
@@ -3085,9 +3108,6 @@ impl App {
// In a browser the file goes to the downloads (ADR 0036).
let path = v["saved"].as_str().unwrap_or("");
self.status_ok(if platform::WEB { tr!("Saved {path} to your downloads", path = path) } else { tr!("Saved {path}", path = path) });
if self.close_after_save {
self.allow_close = true;
}
}
"file.import" | "file.import_to_library" if v.get("sound").is_some() => {
let id = anicraft_engine::doc::SoundId(v["sound"].as_u64().unwrap_or(0));
@@ -3241,7 +3261,7 @@ impl App {
return;
}
if id == "file.recovery_list" {
if !self.recovery.rescan() {
if !self.recovery.rescan(&crate::tabs::recovery_sessions(self)) {
return; // a browser answers on a later frame (autosave::tick)
}
self.recovery.show = !self.recovery.found.is_empty();
@@ -3417,9 +3437,8 @@ impl App {
// The platform's own dialog (it blocks, as native dialogs do). Cancel = no-op.
self.playing = false;
#[cfg(not(target_arch = "wasm32"))]
match platform::file_dialog(id, crate::i18n::t(title), &text) {
Some(path) => self.request(id, json!({ key: path.display().to_string() })),
None => self.close_after_save = false,
if let Some(path) = platform::file_dialog(id, crate::i18n::t(title), &text) {
self.request(id, json!({ key: path.display().to_string() }));
}
return;
}
@@ -3683,6 +3702,12 @@ impl App {
if sheet {
self.show_shortcuts = !self.show_shortcuts;
}
// The next and the previous document (ADR 0112): Ctrl+Tab and Ctrl+Shift+Tab, with the
// Control key on every system (⌘+Tab is the Mac's own), from anywhere.
let doc_step = ctx.input_mut(|i| if i.consume_key(Modifiers::CTRL | Modifiers::SHIFT, Key::Tab) { Some(false) } else if i.consume_key(Modifiers::CTRL, Key::Tab) { Some(true) } else { None });
if let Some(forward) = doc_step {
crate::tabs::step(self, forward);
}
// Moving between panels (Ctrl+F6) works from anywhere, a text field included.
let panel_step = ctx.input_mut(|i| {
self.shortcuts.iter().filter(|(_, _, id)| matches!(*id, "view.next_panel" | "view.prev_panel")).find_map(|(m, k, id)| i.consume_key(*m, *k).then_some(*id == "view.next_panel"))
@@ -3701,8 +3726,11 @@ impl App {
// The Test Movie window's movie has the keyboard (ADR 0052): its keys are the
// movie's; only shortcuts with Ctrl (⌘) or Alt reach the app (Restart is Ctrl+Enter).
if self.test_movie.is_some() && crate::test_movie::has_keys(ctx) {
let fire: Vec<&'static str> = ctx.input_mut(|i| self.shortcuts.iter().filter(|(m, _, _)| m.command || m.ctrl || m.alt).filter_map(|(m, k, id)| i.consume_key(*m, *k).then_some(*id)).collect());
for id in fire.into_iter().filter(|id| !id.starts_with("view.") && !id.starts_with("tool.")) {
// (The view's own keys stay with the window: Ctrl+W there closes the movie, not the
// document.)
let fire: Vec<&'static str> =
ctx.input_mut(|i| self.shortcuts.iter().filter(|(m, _, id)| (m.command || m.ctrl || m.alt) && !id.starts_with("view.") && !id.starts_with("tool.")).filter_map(|(m, k, id)| i.consume_key(*m, *k).then_some(*id)).collect());
for id in fire {
self.invoke(id);
}
return;
@@ -3788,6 +3816,10 @@ impl App {
"view.find_next" => crate::find_panel::step(self, true),
"view.find_prev" => crate::find_panel::step(self, false),
"view.movie_explorer" => crate::movie_explorer::open(self),
"view.close_document" => crate::tabs::close_active(self),
"view.close_all_documents" => crate::tabs::close_all(self),
"view.next_document" => crate::tabs::step(self, true),
"view.prev_document" => crate::tabs::step(self, false),
"view.brush_smaller" => crate::brushtool::resize(self, false),
"view.brush_larger" => crate::brushtool::resize(self, true),
id if id.starts_with("tool.") => tool = keymap::tool_for(id).or(tool),
@@ -3867,7 +3899,7 @@ impl App {
}
fn update_title(&mut self, ctx: &egui::Context) {
let name = self.s.path.as_ref().and_then(|p| p.file_name()).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned());
let name = crate::tabs::active_name(self);
let title = format!("AniCraft — {name}{}", if self.s.is_dirty() { " •" } else { "" }); // i18n-exempt: the product name and the file's
if title != self.title {
ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));
@@ -3912,7 +3944,6 @@ impl App {
}
} else if cancel {
self.prompt = None;
self.close_after_save = false;
}
}
@@ -4122,8 +4153,10 @@ impl eframe::App for App {
crate::test_movie::remember_place(self);
// And the floating panels' windows (ADR 0075).
crate::dock_ui::remember(self);
let clean = !self.s.is_dirty() || self.allow_close || self.shot.is_some();
self.recovery.finish(&self.s, clean);
// Every open document (ADR 0112): unsaved work nobody decided about is kept for the
// next start.
let clean = self.allow_close || self.shot.is_some();
crate::tabs::finish_all(self, clean);
#[cfg(not(target_arch = "wasm32"))]
self.updates.finish();
#[cfg(not(target_arch = "wasm32"))]
@@ -4219,6 +4252,8 @@ impl App {
/// and the stage.
fn workspace(&mut self, ui: &mut egui::Ui) {
let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2));
// The open documents' tabs, above the edit bar of the one shown (ADR 0112).
egui::Panel::top("document_tabs").exact_size(crate::tabs::BAR_HEIGHT).frame(egui::Frame::NONE.fill(T.chrome)).show(ui, |ui| crate::tabs::bar(self, ui));
egui::Panel::top("edit_bar").exact_size(theme::TARGET + 8.0).frame(bar(T.panel)).show(ui, |ui| panels::edit_bar(self, ui));
egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui));
crate::dock_ui::workspace(self, ui);
@@ -4250,18 +4285,14 @@ impl App {
crate::envelope::show(self, &ctx);
crate::ease_editor::show(self, &ctx);
// Never lose work on close: intercept it while there are unsaved changes.
if self.allow_close {
if self.close_after_save || self.close_dialog {
self.close_after_save = false;
self.close_dialog = false;
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
} else if ctx.input(|i| i.viewport().close_requested()) && self.shot.is_none() && self.s.is_dirty() {
// Never lose work on close: intercept it while any open document has unsaved changes,
// and ask once for all of them (ADR 0004, ADR 0112).
if !self.allow_close && ctx.input(|i| i.viewport().close_requested()) && self.shot.is_none() && crate::tabs::any_dirty(self) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
self.playing = false;
self.close_dialog = true;
crate::tabs::quit(self);
}
// Closing tabs, or the window: the next step once a question is answered or a save done.
crate::tabs::tick(self, &ctx);
self.files_window(&ctx);
// Close a coalesced edit (property drags) once nothing is being dragged or typed.
@@ -4285,7 +4316,7 @@ impl App {
let pointer_down = ctx.input(|i| i.pointer.any_down());
crate::brushtool::sync(self, pointer_down);
// A browser asks before leaving a page with unsaved work (its close guard).
platform::set_unsaved(self.s.is_dirty());
platform::set_unsaved(crate::tabs::any_dirty(self));
// Copied artwork or frames: the system clipboard says so, as any copy replaces what it
// held, and so the next Ctrl/⌘+V comes through (issue #197). A browser sends that key
// press whatever its clipboard holds.
+71 -26
View File
@@ -23,11 +23,12 @@ use anicraft_engine::StateId;
use serde_json::json;
use std::path::PathBuf;
/// Autosave state of the running app.
/// One open document's autosave (ADR 0112): each document is its own recovery session, with
/// its own copy in the recovery folder, so a crash leaves one copy per document with unsaved
/// changes. It goes with its document when another tab is shown.
#[derive(Default)]
pub struct Recovery {
pub struct DocSaver {
saver: Option<Autosaver>,
pub dir: Option<PathBuf>,
/// Document state the newest copy holds (handed to the writer, or restored from disk).
written: Option<StateId>,
/// This session has a copy on disk (or one on its way).
@@ -41,6 +42,17 @@ pub struct Recovery {
/// A restored copy of another session, removed once this session holds the work.
adopt: Option<String>,
failed: bool,
}
/// Autosave state of the running app.
#[derive(Default)]
pub struct Recovery {
/// The document being edited's autosave; the other open documents' are with them
/// (`tabs::Parked`).
pub doc: DocSaver,
pub dir: Option<PathBuf>,
/// Autosave runs (a recovery folder, and not a screenshot run): new documents get a saver.
on: bool,
/// Copies left by sessions that didn't close cleanly, and whether the window shows them.
pub found: Vec<Entry>,
pub show: bool,
@@ -68,7 +80,8 @@ impl Recovery {
let _ = shot_mode;
match Autosaver::start() {
Ok(s) => {
r.saver = Some(s);
r.doc.saver = Some(s);
r.on = true;
r.scanning = Some(false);
(r, None)
}
@@ -86,7 +99,8 @@ impl Recovery {
r.show = !r.found.is_empty();
let err = match SessionLock::acquire(&dir).and_then(Autosaver::start) {
Ok(s) => {
r.saver = Some(s);
r.doc.saver = Some(s);
r.on = true;
None
}
Err(e) => Some(tr!("Autosave is off: {error}", error = e)),
@@ -97,14 +111,36 @@ impl Recovery {
}
pub fn active(&self) -> bool {
self.saver.is_some()
self.doc.saver.is_some()
}
/// The autosave of a document being opened in a new tab (ADR 0112): its own recovery
/// session. Without one (autosave is off here, or the folder can't be written) the document
/// opens all the same.
pub fn for_new_document(&self) -> DocSaver {
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
let mut d = DocSaver::default();
if !self.on {
return d;
}
#[cfg(target_arch = "wasm32")]
{
d.saver = Autosaver::start().ok();
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(dir) = &self.dir {
d.saver = SessionLock::acquire(dir).and_then(Autosaver::start).ok();
}
d
}
/// Rescans for left-behind copies (File › Recover Autosaved Documents…). `false` when the
/// list comes later (a browser asks which tabs are open), and [`tick`] shows it then.
pub fn rescan(&mut self) -> bool {
/// `own`: the recovery sessions of the documents open here, which are not left behind.
pub fn rescan(&mut self, own: &[String]) -> bool {
#[cfg(target_arch = "wasm32")]
{
let _ = own;
crate::web::refresh_live();
self.scanning = Some(true);
false
@@ -112,8 +148,8 @@ impl Recovery {
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(dir) = &self.dir {
let own = self.saver.as_ref().map(|s| s.id().to_string());
self.found = recovery::scan(dir, own.as_deref());
self.found = recovery::scan(dir, own.first().map(String::as_str));
self.found.retain(|e| !own.contains(&e.session));
}
true
}
@@ -124,9 +160,9 @@ impl Recovery {
pub fn restored(&mut self, session: &str) {
self.found.retain(|e| e.session != session);
self.show = self.show && !self.found.is_empty();
self.adopt = Some(session.to_string());
self.written = None;
self.dirty_since = Some(f64::NEG_INFINITY);
self.doc.adopt = Some(session.to_string());
self.doc.written = None;
self.doc.dirty_since = Some(f64::NEG_INFINITY);
}
pub fn discarded(&mut self, session: &str) {
@@ -134,6 +170,13 @@ impl Recovery {
self.confirm_discard = None;
self.show = self.show && !self.found.is_empty();
}
}
impl DocSaver {
/// This document's recovery session, while it has one.
pub fn id(&self) -> Option<String> {
self.saver.as_ref().map(|s| s.id().to_string())
}
/// Writes a copy of unsaved work now, without waiting for the interval (the graphics driver
/// reported trouble, ADR 0092: the next thing may be the window going). Whether one was
@@ -151,8 +194,9 @@ impl Recovery {
true
}
/// Ends the session: a clean exit removes this session's copy; anything else (unsaved work
/// the user didn't decide about) is written one last time for the next start.
/// Ends the document's session: a clean end (saved, closed, or the user chose Don't Save)
/// removes its copy; anything else (unsaved work the user didn't decide about) is written
/// one last time for the next start.
pub fn finish(&mut self, s: &anicraft_engine::Session, clean: bool) {
if let Some(saver) = self.saver.take() {
let keep = !clean && s.is_dirty();
@@ -179,8 +223,9 @@ fn drop_adopted(app: &mut App, old: &str) {
#[cfg(target_arch = "wasm32")]
fn poll_scan(app: &mut App) {
let Some(asked) = app.recovery.scanning else { return };
let own = app.recovery.saver.as_ref().map(|s| s.id().to_string());
let Some(found) = crate::web::scan(own.as_deref()) else { return };
let own = crate::tabs::recovery_sessions(app);
let Some(mut found) = crate::web::scan(own.first().map(String::as_str)) else { return };
found.retain(|e| !own.contains(&e.session));
let r = &mut app.recovery;
r.scanning = None;
r.found = found;
@@ -248,28 +293,28 @@ pub fn tick(app: &mut App, ctx: &egui::Context) {
#[cfg(target_arch = "wasm32")]
poll_scan(app);
let now = ctx.input(|i| i.time);
let outcomes = app.recovery.saver.as_ref().map(Autosaver::poll).unwrap_or_default();
let outcomes = app.recovery.doc.saver.as_ref().map(Autosaver::poll).unwrap_or_default();
for o in outcomes {
match o {
Outcome::Written { .. } => {
app.recovery.last_copy_at = Some(now);
app.recovery.failed = false;
if let Some(old) = app.recovery.adopt.take() {
app.recovery.doc.last_copy_at = Some(now);
app.recovery.doc.failed = false;
if let Some(old) = app.recovery.doc.adopt.take() {
drop_adopted(app, &old);
}
}
Outcome::Failed { error, .. } => {
if !app.recovery.failed {
if !app.recovery.doc.failed {
app.status_err(tr!("Autosave failed: {error}. Save your work to be safe; AniCraft will keep trying.", error = error));
}
app.recovery.failed = true;
app.recovery.written = None;
app.recovery.dirty_since = Some(now);
app.recovery.doc.failed = true;
app.recovery.doc.written = None;
app.recovery.doc.dirty_since = Some(now);
}
Outcome::Cleared { .. } => {}
}
}
let r = &mut app.recovery;
let r = &mut app.recovery.doc;
let Some(saver) = &mut r.saver else { return };
if !app.prefs.autosave || !app.s.is_dirty() {
// Nothing to protect (saved, back at the saved state, a new document) or autosave off.
@@ -320,7 +365,7 @@ pub fn status(app: &App, now: f64) -> Option<String> {
if !app.s.is_dirty() || !app.prefs.autosave {
return None;
}
let at = app.recovery.last_copy_at?;
let at = app.recovery.doc.last_copy_at?;
Some(tr!("autosaved {when}", when = ago((now - at).max(0.0) as u64)))
}
+3 -2
View File
@@ -344,7 +344,7 @@ pub fn subject(app: &App, ctx: &egui::Context, pointer: bool) -> Subject {
if app.templates.save.is_some() {
return Subject::Dialog(Dialog::SaveTemplate);
}
if app.close_dialog {
if app.tabs.asking() {
return Subject::Dialog(Dialog::CloseUnsaved);
}
if let Some(p) = &app.palette {
@@ -506,7 +506,8 @@ mod tests {
app.show_prefs = false;
settle(&ctx, &mut app);
// A dialog that asks first: help for the command it asks about.
app.close_dialog = true;
app.run("layer.new", serde_json::json!({}));
crate::tabs::quit(&mut app);
assert_eq!(subject(&app, &ctx, true), Subject::Dialog(Dialog::CloseUnsaved));
frame(&ctx, &mut app, f1());
assert_eq!(app.help_opened.as_deref(), Some("getting-started.md#save-your-work"), "F1 works while a dialog holds the editor");
+25 -28
View File
@@ -93,7 +93,6 @@ fn confirm_modal(app: &mut App, ctx: &egui::Context) {
}
Some(false) => {
app.confirm = None;
app.close_after_save = false;
app.status_ok(tr!("Cancelled"));
}
None => {}
@@ -101,20 +100,31 @@ fn confirm_modal(app: &mut App, ctx: &egui::Context) {
}
fn close_modal(app: &mut App, ctx: &egui::Context) {
if !app.close_dialog || app.prompt.is_some() || app.confirm.is_some() {
if !app.tabs.asking() || app.prompt.is_some() || app.confirm.is_some() {
return;
}
#[derive(PartialEq)]
enum Choice {
Save,
Discard,
Cancel,
}
use crate::tabs::Answer as Choice;
// The document a closing tab asks about, or every unsaved one when the window closes: one
// question for all of them (ADR 0112).
let names = crate::tabs::asked_about(app);
let Some(name) = names.first().cloned() else { return };
let several = names.len() > 1;
let mut choice = None;
let name = app.s.path.as_ref().and_then(|p| p.file_name()).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned());
egui::Modal::new(egui::Id::new("close_guard")).show(ctx, |ui| {
ui.set_width(440.0);
ui.label(text(Type::Title, tr!("Save changes to “{name}” before closing?", name = name)));
if several {
ui.label(text(Type::Title, trn!("Save changes to {n} document before closing?", "Save changes to {n} documents before closing?", names.len())));
ui.add_space(6.0);
// Their own names, as on their tabs (the first few of a long list).
for n in names.iter().take(8) {
ui.label(text(Type::Body, format!("• {n}")));
}
if names.len() > 8 {
ui.label(text(Type::Body, trn!("and {n} more", "and {n} more", names.len() - 8)).color(T.text_dim));
}
} else {
ui.label(text(Type::Title, tr!("Save changes to “{name}” before closing?", name = name)));
}
ui.add_space(6.0);
ui.label(text(Type::Body, tr!("If you don't save, your changes since the last save will be lost.")).color(T.text_dim));
ui.add_space(12.0);
@@ -123,7 +133,7 @@ fn close_modal(app: &mut App, ctx: &egui::Context) {
choice = Some(Choice::Discard);
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(text(Type::Body, tr!("Save")).strong().color(T.on_fill)).fill(T.accent).min_size(egui::vec2(96.0, crate::theme::TARGET + 4.0))).clicked() {
if ui.add(egui::Button::new(text(Type::Body, if several { tr!("Save All") } else { tr!("Save") }).strong().color(T.on_fill)).fill(T.accent).min_size(egui::vec2(96.0, crate::theme::TARGET + 4.0))).clicked() {
choice = Some(Choice::Save);
}
if ui.add(egui::Button::new(tr!("Cancel")).min_size(egui::vec2(96.0, crate::theme::TARGET + 4.0))).clicked() {
@@ -139,23 +149,10 @@ fn close_modal(app: &mut App, ctx: &egui::Context) {
} else if enter {
choice = Some(Choice::Save);
}
match choice {
Some(Choice::Save) => {
app.close_dialog = false;
app.close_after_save = true;
if app.s.path.is_some() {
app.perform("file.save", json!({}));
} else {
app.invoke("file.save_as");
}
}
Some(Choice::Discard) => {
app.allow_close = true;
}
Some(Choice::Cancel) => {
app.close_dialog = false;
}
None => {}
// Save saves each (a document without a file asks for a name); Don't Save gives the changes
// up; Cancel leaves everything open (`tabs::tick` does the rest).
if let Some(choice) = choice {
crate::tabs::answer(app, choice);
}
}
+9 -6
View File
@@ -652,9 +652,10 @@ mod tests {
run(&mut app, &[dir.join("notes.txt")], Spot::Stage(0.0, 0.0));
assert!(app.s.doc == before);
assert!(app.status.as_ref().is_some_and(|s| s.error && s.text.contains("notes.txt")));
// A document over unsaved work asks first.
// A document over unsaved work opens in a tab of its own (ADR 0112): nothing to ask.
run(&mut app, &[dir.join("other.anicraft")], Spot::Stage(0.0, 0.0));
assert!(app.confirm.is_some());
assert!(app.confirm.is_none());
assert!(crate::tabs::infos(&app).iter().any(|t| t.dirty), "the unsaved work is still open");
}
/// Documents the system hands the running app (macOS Finder, the Dock; ADR 0062) arrive as
@@ -684,20 +685,22 @@ mod tests {
assert_eq!(app.s.path.as_deref(), Some(walk.as_path()));
assert!(app.start.is_none(), "the start screen gave way");
assert!(app.status.as_ref().is_some_and(|s| s.text.contains("photo.png")), "{:?}", app.status.as_ref().map(|s| &s.text));
// While running, over unsaved work: it asks first, and nothing changes until it's answered.
// While running, over unsaved work: it opens in a tab of its own, and the work stays
// open in its tab (ADR 0112).
app.run("layer.new", json!({}));
assert!(app.s.is_dirty());
push_request(SystemRequest::Open(vec![other.clone()]));
frame(&mut app);
assert!(app.confirm.as_ref().is_some_and(|c| c.id == "file.open"), "the unsaved-changes guard asks");
assert_eq!(app.s.path.as_deref(), Some(walk.as_path()));
app.confirm = None;
assert!(app.confirm.is_none());
assert_eq!(app.s.path.as_deref(), Some(other.as_path()));
assert_eq!(crate::tabs::infos(&app).iter().map(|t| (t.path.clone(), t.dirty)).collect::<Vec<_>>(), [(Some(walk.clone()), true), (Some(other.clone()), false)]);
// Only files AniCraft can't open: one clear message, nothing else.
push_request(SystemRequest::Open(vec![dir.join("notes.txt")]));
frame(&mut app);
assert!(app.status.as_ref().is_some_and(|s| s.error && s.text.contains("notes.txt")));
assert!(app.confirm.is_none());
// The Dock's Quit closes the editor's window, which the close guard intercepts.
app.allow_close = true;
push_request(SystemRequest::Quit);
let out = frame(&mut app);
let closes = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.commands.contains(&egui::ViewportCommand::Close));
+2 -2
View File
@@ -225,7 +225,7 @@ fn notice_due(at: f64) -> bool {
pub fn tick(app: &mut crate::app::App, ctx: &egui::Context) {
let news = take_news();
if news.error.is_some() || news.failing {
app.recovery.write_now(&app.s);
app.recovery.doc.write_now(&app.s);
}
if news.failing {
ctx.request_repaint_after(Duration::from_millis(500));
@@ -236,7 +236,7 @@ pub fn tick(app: &mut crate::app::App, ctx: &egui::Context) {
let Some(why) = news.gone else { return };
crate::startup::line(&format!("closing the window to open it again another way ({why})"));
// The work goes to the recovery folder for the next window (the lock goes, so it finds it).
app.recovery.finish(&app.s, false);
crate::tabs::finish_all(app, false);
crate::startup::lost_mid_session();
// A saved document opens again as it was; unsaved work is offered back.
let file = app.s.path.clone().filter(|_| !app.s.is_dirty());
+1 -1
View File
@@ -858,7 +858,7 @@ fn screen_reader_names_are_translated_too() {
}
found.extend(untranslated_names("close guard", |a, _| {
a.run("layer.new", serde_json::json!({}));
a.close_dialog = true;
crate::tabs::quit(a);
}));
found.extend(untranslated_names("library item", |a, _| {
a.library_sel = a.s.doc.library.first().map(|s| crate::app::LibraryItem::Symbol(s.id));
+4
View File
@@ -89,6 +89,10 @@ fn view_label(id: &str) -> &'static str {
"view.find_next" => tr_noop!("Find Next"),
"view.find_prev" => tr_noop!("Find Previous"),
"view.movie_explorer" => tr_noop!("Movie Explorer"),
"view.close_document" => tr_noop!("Close Document"),
"view.close_all_documents" => tr_noop!("Close All Documents"),
"view.next_document" => tr_noop!("Next Document"),
"view.prev_document" => tr_noop!("Previous Document"),
"view.brush_smaller" => tr_noop!("Brush Size Down"),
"view.brush_larger" => tr_noop!("Brush Size Up"),
_ => tr_noop!("View action"),
+5
View File
@@ -90,6 +90,7 @@ mod shape_hints;
mod stage;
mod stage_a11y;
mod swatches_panel;
mod tabs;
mod start;
mod startup;
mod templates;
@@ -179,6 +180,10 @@ fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option<PathBuf>, op
startup::log_adapter(cc.wgpu_render_state.as_ref());
let starting_fresh = file_given.is_none() && shot.is_none();
let mut a = app::App::new(cc, session, shot);
// A file named on the command line keeps its tab, even an imported one (ADR 0112).
if file_given.is_some() {
a.tabs.keep_first();
}
if let Some(s) = a.shot.as_mut() {
s.width = look.shot_width;
}
+21
View File
@@ -553,6 +553,13 @@ fn registry_items(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSp
if ui_item(ui, tr!("Start Screen"), "", None) {
crate::start::open(app);
}
// The open documents (ADR 0112): close the one shown, or all of them.
if ui_item(ui, tr!("Close"), app.keymap.primary("view.close_document").unwrap_or(""), None) {
crate::tabs::close_active(app);
}
if ui_item(ui, tr!("Close All"), app.keymap.primary("view.close_all_documents").unwrap_or(""), None) {
crate::tabs::close_all(app);
}
}
}
let mut subs: Vec<&str> = Vec::new();
@@ -736,6 +743,20 @@ pub(crate) fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &
crate::onion::toggle_ghosts(app);
}
ui.label(text(Type::Caption, tr!("Drag a panel's tab to dock it on any side, stack it with others or float it")));
// The open documents, as in Animate's Window menu: the shown one is ticked.
ui.separator();
if ui_item(ui, tr!("Next Document"), "Ctrl+Tab", None) {
crate::tabs::step(app, true);
}
if ui_item(ui, tr!("Previous Document"), "Ctrl+Shift+Tab", None) {
crate::tabs::step(app, false);
}
for t in crate::tabs::infos(app) {
// A document's own name: not translated.
if ui_item(ui, &t.name, "", Some(t.active)) {
crate::tabs::activate_id(app, t.id);
}
}
}
"Help" => {
if ui_item(ui, tr!("User Guide"), "", None) {
+57
View File
@@ -406,6 +406,10 @@ pub fn places() -> Vec<(&'static str, Option<PathBuf>)> {
/// Where crash-recovery copies live (ADR 0015): `Recovery` in the settings folder.
/// `ANICRAFT_RECOVERY_DIR` points it elsewhere (tests, portable installs).
pub fn recovery_dir() -> Option<PathBuf> {
#[cfg(test)]
if let Some(d) = TEST_RECOVERY_DIR.with(|d| d.borrow().clone()) {
return Some(d);
}
match std::env::var_os("ANICRAFT_RECOVERY_DIR").filter(|v| !v.is_empty()) {
Some(d) => Some(PathBuf::from(d)),
None => config_dir().map(|d| d.join("Recovery")), // i18n-exempt: a folder name
@@ -440,11 +444,64 @@ pub fn write_private_file(path: &std::path::Path, contents: &[u8]) -> std::io::R
f.sync_all()
}
/// What showing a file where it is kept is called on this system (a document tab's menu, ADR
/// 0112).
pub fn reveal_label() -> &'static str {
match OS {
Os::Mac => tr!("Reveal in Finder"),
Os::Windows => tr!("Show in File Explorer"),
_ => tr!("Show in Folder"),
}
}
/// Opens the system's file manager on `path`'s folder, with the file picked where the system
/// can do that (Explorer and the Finder; elsewhere the folder opens).
pub fn reveal_in_folder(path: &Path) -> Result<(), String> {
// Tests click every control: they never start another program. A browser has no folders.
if cfg!(test) || WEB {
return Ok(());
}
let mut cmd = match OS {
Os::Windows => {
let mut c = std::process::Command::new("explorer");
c.arg(format!("/select,{}", path.display()));
c
}
Os::Mac => {
let mut c = std::process::Command::new("open");
c.arg("-R").arg(path);
c
}
_ => {
let mut c = std::process::Command::new("xdg-open");
c.arg(path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")));
c
}
};
cmd.spawn().map(|_| ()).map_err(|e| tr!("could not show {path}: {e}", path = path.display(), e = e))
}
/// Whether the recovery folder was chosen explicitly (screenshot runs only touch it then).
pub fn recovery_dir_overridden() -> bool {
#[cfg(test)]
if TEST_RECOVERY_DIR.with(|d| d.borrow().is_some()) {
return true;
}
std::env::var_os("ANICRAFT_RECOVERY_DIR").is_some_and(|v| !v.is_empty())
}
#[cfg(test)]
thread_local! {
/// A test's own recovery folder (each test runs on its own thread, so no other sees it).
static TEST_RECOVERY_DIR: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
}
/// Points this test's apps at a recovery folder of its own (`None`: back to none).
#[cfg(test)]
pub fn set_recovery_dir_for_tests(dir: Option<PathBuf>) {
TEST_RECOVERY_DIR.with(|d| *d.borrow_mut() = dir);
}
/// Where Help › User Guide writes the bundled book (ADR 0069): the system's cache folder
/// (%LOCALAPPDATA%, ~/Library/Caches, $XDG_CACHE_HOME or ~/.cache), else the temporary folder;
/// `Cache` in the data folder of a portable copy.
+3 -2
View File
@@ -109,10 +109,11 @@ fn drawing_and_free_transform_snap_to_guides() {
let screen_of = |x: f32, y: f32| pos2(g.origin.x + x * g.zoom, g.origin.y + y * g.zoom);
// Grabbed near the middle, so the box's centre is what snaps; let go 3 screen pixels short.
// (Not on the very centre: the transformation point is there, and a drag on it moves the
// point, not the box; ADR 0111.)
// point, not the box; ADR 0111. Nor far from it: the box is under 40 screen pixels tall
// with the document tabs above the stage, and its lower edge's handle is 20 below.)
let sel = app.s.selection_bounds();
let cx = (sel.min.x + sel.max.x) * 0.5;
let inside = screen_of(cx, (sel.min.y + sel.max.y) * 0.5) + vec2(0.0, 12.0);
let inside = screen_of(cx, (sel.min.y + sel.max.y) * 0.5) + vec2(0.0, 9.0);
let dx = (500.0 - cx) * g.zoom - 3.0;
drag(&ctx, &mut app, inside, inside + vec2(dx, 0.0));
let after = app.s.selection_bounds();
+18
View File
@@ -89,6 +89,24 @@ impl Cache {
})
}
/// Another document is shown from now on (ADR 0112): the tiles of the one put aside go, and
/// the render service's pictures with them, so only the document on screen holds graphics
/// memory.
pub fn forget_document(&mut self) {
self.tiles.clear();
self.shown_state = None;
self.ready = (0, 0);
if let Some(s) = &self.service {
s.forget_pictures();
}
}
/// How many tile textures are held (tests).
#[cfg(test)]
pub fn tile_count(&self) -> usize {
self.tiles.len()
}
fn has(&mut self, key: u64) -> bool {
self.tick += 1;
let tick = self.tick;
+6 -4
View File
@@ -307,14 +307,16 @@ mod tests {
}
#[test]
fn over_unsaved_work_new_asks_first_and_esc_goes_back() {
fn over_unsaved_work_new_opens_a_tab_and_esc_goes_back() {
let (mut app, ctx) = app();
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
crate::start::open(&mut app);
app.request("file.new", new_params(1920, 1080, 24.0));
assert!(app.confirm.is_some(), "unsaved work asks first");
assert!(app.start.is_some(), "and the start screen waits for the answer");
app.confirm = None;
assert!(app.confirm.is_none(), "nothing to ask: the work stays open in its tab (ADR 0112)");
assert_eq!(app.tabs.len(), 2);
assert!(app.start.is_none());
assert!(crate::tabs::activate(&mut app, 0));
crate::start::open(&mut app);
// Esc returns to the work, untouched.
let input = egui::RawInput { events: vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], ..Default::default() };
let mut out = ctx.run_ui(input, |ui| app.frame(ui));
+856
View File
@@ -0,0 +1,856 @@
//! Several documents open at once, each in a tab above the stage (ADR 0112).
//!
//! The document being edited is where it always was: its [`Session`] is `App::s` and its view
//! state is in `App`'s own fields, so every panel and tool keeps reading the same places. The
//! other open documents are *parked*: each tab that isn't shown holds its whole session (the
//! document, its undo history, selection and playhead), its view state ([`DocView`]: zoom and
//! pan, timeline scroll, Library and Motion Editor state, …) and its autosave. Showing another
//! tab exchanges the two, and hands the editor's share (the clipboards, the tool style, plug-ins,
//! recent files) from one session to the other, so a copy made in one document pastes into the
//! next (`Session::take_shared`).
//!
//! Which documents are open is the window's state, like zoom and the tool in hand: it isn't in
//! any document and isn't a command. The CLI and MCP stay one document per session.
use crate::a11y;
use crate::app::{App, Drag, LibraryItem, StageView};
use crate::autosave::DocSaver;
use crate::platform;
use crate::theme::{self, T, Type, font};
use anicraft_engine::Session;
use anicraft_engine::doc::{Document, ElementId, LayerId};
use egui::{Id, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
use serde_json::{Value, json};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
/// The most documents open at once: each keeps its undo history in memory and its own autosave
/// writer.
pub const MAX_TABS: usize = 32;
/// The bar's height (points).
pub const BAR_HEIGHT: f32 = theme::TARGET + 2.0;
/// A tab is never narrower or wider than this, whatever its name.
const TAB_MIN: f32 = 96.0;
const TAB_MAX: f32 = 240.0;
/// Space the close button takes at a tab's right end, and the unsaved dot at its left.
const CLOSE_W: f32 = 22.0;
const DOT_W: f32 = 12.0;
const PAD: f32 = 10.0;
/// Declares [`DocView`]: the fields of [`App`] that belong to the document being edited rather
/// than to the window. Each is named as in `App`, with the value a newly opened document gets.
macro_rules! doc_view {
($app:ident; $($field:ident: $ty:ty = $fresh:expr),* $(,)?) => {
/// One document's view state while another is shown (see the module docs).
pub struct DocView { $($field: $ty),* }
impl DocView {
/// The view of a document that has just been opened.
fn fresh($app: &App) -> DocView {
DocView { $($field: $fresh),* }
}
/// Exchanges this view with the one in `app`.
fn swap(&mut self, app: &mut App) {
$(std::mem::swap(&mut self.$field, &mut app.$field);)*
}
}
};
}
doc_view! { app;
view: StageView = StageView { zoom: 1.0, pan: egui::Vec2::ZERO, fit: true, fitted: None, clip_to_stage: app.view.clip_to_stage },
camera_preview: bool = false,
tl_scroll: f32 = 0.0,
tl_cell_w: f32 = crate::timeline::CELL_DEFAULT,
tl_button_zoom: Option<(f32, f32)> = None,
tl_vscroll: f32 = 0.0,
tl_last_layer: Option<LayerId> = None,
tl_collapsed: HashSet<LayerId> = HashSet::new(),
timeline_focus: bool = false,
frame_sel: Option<crate::timeline::FrameSel> = None,
library_sel: Option<LibraryItem> = None,
library: crate::library::LibraryView = Default::default(),
explorer: crate::movie_explorer::ExplorerView = Default::default(),
actions: crate::actions_panel::State = Default::default(),
points: Vec<crate::pathtools::PointRef> = Vec::new(),
raw_anchors: Vec<anicraft_engine::geom::Vec2> = Vec::new(),
raw_ends: Vec<anicraft_engine::geom::Vec2> = Vec::new(),
width_sel: Option<(ElementId, usize)> = None,
bone_sel: Option<anicraft_engine::doc::BoneId> = None,
warp_pin: Option<(ElementId, anicraft_engine::doc::warp::PinId)> = None,
motion_anchors: Vec<usize> = Vec::new(),
xf: crate::xform::State = Default::default(),
envelope_open: bool = false,
me_prop: anicraft_engine::doc::Property = anicraft_engine::doc::Property::X,
me_key: Option<u32> = None,
me_sel: Vec<(anicraft_engine::doc::Property, u32)> = Vec::new(),
me_sel_at: (u64, u32) = (0, 0),
me_vscroll: f32 = 0.0,
me_styles: Vec<anicraft_engine::doc::ColorStyle> = Vec::new(),
me_open: Vec<(u8, anicraft_engine::doc::FilterColor)> = Vec::new(),
}
/// An open document that isn't the one being edited.
pub struct Parked {
pub s: Session,
view: DocView,
saver: DocSaver,
}
/// One tab.
struct Slot {
/// The tab's identity while it is open (never reused in a run).
id: u64,
/// Which untitled document it is (1: "Untitled", 2: "Untitled 2", …), for its name until it
/// is saved.
untitled: u32,
/// The document the app started with, untouched: opening a file takes its place instead of
/// a new tab, as a word processor's blank page does.
placeholder: bool,
/// `None` for the document being edited (it is in `App`).
parked: Option<Box<Parked>>,
}
/// What a tab shows.
#[derive(Clone, Debug, PartialEq)]
pub struct TabInfo {
pub id: u64,
pub name: String,
pub dirty: bool,
pub path: Option<PathBuf>,
pub active: bool,
}
/// Closing documents, or the window: which tabs are still to go, and what is being waited for.
#[derive(Clone, Debug, PartialEq)]
pub struct CloseFlow {
/// Tabs to close, in order (for a quit: the ones with unsaved changes).
pub ids: Vec<u64>,
/// The window is closing: one question for every document (ADR 0004).
pub quit: bool,
/// The answer was Save: documents are being saved, one after another when quitting.
saving: bool,
/// The tab whose save was started (its Save As may still be asking for a name).
asked: Option<u64>,
}
/// What the close question was answered with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Answer {
Save,
Discard,
Cancel,
}
/// The open documents.
pub struct Tabs {
slots: Vec<Slot>,
active: usize,
next_id: u64,
/// The tab being dragged along the bar.
drag: Option<u64>,
pub closing: Option<CloseFlow>,
/// How far the tabs are scrolled when they don't fit (points), and whether the shown one
/// should be brought into view.
scroll: f32,
reveal: bool,
/// Where each tab was drawn last frame (tests and screenshots).
pub rects: Vec<(u64, Rect)>,
}
impl Tabs {
/// One tab: the document the app starts with. `placeholder`: it is the sample or a blank
/// page rather than a file the user opened.
pub fn new(placeholder: bool) -> Tabs {
Tabs { slots: vec![Slot { id: 1, untitled: 1, placeholder, parked: None }], active: 0, next_id: 2, drag: None, closing: None, scroll: 0.0, reveal: false, rects: Vec::new() }
}
pub fn len(&self) -> usize {
self.slots.len()
}
/// The shown tab's place in the bar.
#[cfg(test)]
pub fn active(&self) -> usize {
self.active
}
fn index_of(&self, id: u64) -> Option<usize> {
self.slots.iter().position(|s| s.id == id)
}
/// The document the app started with was opened by the user after all (a file named on the
/// command line): it keeps its tab.
pub fn keep_first(&mut self) {
for s in &mut self.slots {
s.placeholder = false;
}
}
/// The close question is showing (a modal: shortcuts pause).
pub fn asking(&self) -> bool {
self.closing.as_ref().is_some_and(|f| !f.saving)
}
}
/// A document's name on its tab: the file's, or "Untitled" (numbered from the second on).
fn name_of(untitled: u32, path: Option<&Path>) -> String {
match path.and_then(Path::file_name) {
Some(n) => n.to_string_lossy().into_owned(),
None if untitled <= 1 => tr!("Untitled").to_string(),
None => tr!("Untitled {n}", n = untitled),
}
}
/// The session of tab `i`: the app's for the shown one.
fn session(app: &App, i: usize) -> Option<&Session> {
let slot = app.tabs.slots.get(i)?;
Some(slot.parked.as_ref().map_or(&app.s, |p| &p.s))
}
/// What tab `i` shows.
pub fn info(app: &App, i: usize) -> Option<TabInfo> {
let slot = app.tabs.slots.get(i)?;
let s = session(app, i)?;
Some(TabInfo { id: slot.id, name: name_of(slot.untitled, s.path.as_deref()), dirty: s.is_dirty(), path: s.path.clone(), active: i == app.tabs.active })
}
/// Every tab, in the bar's order.
pub fn infos(app: &App) -> Vec<TabInfo> {
(0..app.tabs.len()).filter_map(|i| info(app, i)).collect()
}
/// The shown document's name, as its tab has it (the window title and the close question).
pub fn active_name(app: &App) -> String {
info(app, app.tabs.active).map_or_else(|| tr!("Untitled").to_string(), |t| t.name)
}
/// Whether any open document has unsaved changes.
pub fn any_dirty(app: &App) -> bool {
(0..app.tabs.len()).any(|i| session(app, i).is_some_and(Session::is_dirty))
}
/// The tabs with unsaved changes, in the bar's order.
fn dirty_ids(app: &App) -> Vec<u64> {
infos(app).into_iter().filter(|t| t.dirty).map(|t| t.id).collect()
}
/// The recovery sessions of the open documents (they are not "left behind").
pub fn recovery_sessions(app: &App) -> Vec<String> {
let parked = app.tabs.slots.iter().filter_map(|s| s.parked.as_ref()).filter_map(|p| p.saver.id());
app.recovery.doc.id().into_iter().chain(parked).collect()
}
/// Ends every document's autosave (the window is closing): a clean end removes the copies,
/// otherwise each document with unsaved changes is written once more for the next start.
pub fn finish_all(app: &mut App, clean: bool) {
app.recovery.doc.finish(&app.s, clean);
for p in app.tabs.slots.iter_mut().filter_map(|s| s.parked.as_mut()) {
p.saver.finish(&p.s, clean);
}
}
/// Why another document can't be shown right now, if it can't: something is open that belongs
/// to this one and has to be finished first.
fn busy(app: &App) -> Option<&'static str> {
if app.modal_open() && !app.tabs.asking() {
Some(tr!("Finish with the open dialog first."))
} else if app.publish.running() || app.plugin_export.is_some() {
Some(tr!("Wait for the export to finish first."))
} else {
None
}
}
/// Finishes what is in progress on the shown document, before it is put aside or closed: text
/// being typed and a pen path are kept, playback stops, an open drag ends its undo step.
fn settle(app: &mut App) {
if app.playing {
app.toggle_play();
}
if app.text_edit.is_some() {
crate::stage::commit_text(app);
}
if app.pen.is_some() {
crate::pathtools::commit_pen(app, false);
}
if app.s.in_gesture() {
app.s.end_gesture();
}
app.drag = Drag::None;
app.tl_drag = crate::timeline::TlDrag::None;
app.tl_layer_drag = None;
app.me_drag = None;
app.motion_drag = None;
app.new_guide = None;
app.snap_ring = None;
app.hint_menu = None;
app.path_pick = None;
app.zoom_text = None;
app.cursor_stage = None;
app.pencil.clear();
app.brush_samples.clear();
app.raw_points = Value::Null;
app.raw_touched.clear();
app.raw_with.clear();
// Windows that edit one keyframe or layer of this document.
app.envelope = None;
app.ease = None;
app.layer_props = None;
app.aids_dialogs = Default::default();
}
/// The document in `app` is another one from here on: nothing drawn for the last one is kept
/// (ADR 0112: a document that isn't shown holds no render caches).
fn arrived(app: &mut App) {
app.stage_cache.forget_document();
app.last_revision = 0;
app.heard = None;
app.tl_heard = None;
app.stage_nav = Default::default();
app.tabs.reveal = true;
app.decode_sounds();
}
/// Shows tab `to`. `false` when it can't be (a dialog of the shown document is open).
pub fn activate(app: &mut App, to: usize) -> bool {
let from = app.tabs.active;
if to == from {
return true;
}
if to >= app.tabs.len() {
return false;
}
if let Some(why) = busy(app) {
app.status_err(why);
return false;
}
settle(app);
let Some(mut p) = app.tabs.slots.get_mut(to).and_then(|s| s.parked.take()) else { return false };
// Unsaved work is copied before it is put aside: nothing looks after it while it waits.
if app.prefs.autosave {
app.recovery.doc.write_now(&app.s);
}
p.view.swap(app);
std::mem::swap(&mut app.s, &mut p.s);
std::mem::swap(&mut app.recovery.doc, &mut p.saver);
app.s.take_shared(&mut p.s);
p.s.drop_caches();
if let Some(slot) = app.tabs.slots.get_mut(from) {
slot.parked = Some(p);
}
app.tabs.active = to;
arrived(app);
true
}
/// Shows the tab with this id.
pub fn activate_id(app: &mut App, id: u64) -> bool {
app.tabs.index_of(id).is_some_and(|i| activate(app, i))
}
/// The next tab (or the one before), round the ends (Ctrl+Tab, Ctrl+PageDown).
pub fn step(app: &mut App, forward: bool) {
let n = app.tabs.len();
if n < 2 {
return;
}
let to = if forward { (app.tabs.active + 1) % n } else { (app.tabs.active + n - 1) % n };
if activate(app, to) {
app.status_ok(tr!("{name} ({number} of {count})", name = active_name(app), number = to + 1, count = n));
}
}
/// Commands that bring a document: each opens in a tab of its own.
pub fn opens_document(id: &str) -> bool {
matches!(id, "file.new" | "file.new_sample" | "file.new_from_template" | "file.open" | "file.open_recent" | "file.recover")
}
/// Whether two paths name the same file (as far as the file system can tell).
fn same_file(a: &Path, b: &Path) -> bool {
if a == b {
return true;
}
if platform::WEB {
return false;
}
matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(x), Ok(y)) if x == y)
}
/// The tab that already has the file `id` would open.
fn already_open(app: &App, id: &str, params: &Value) -> Option<usize> {
// A restored copy is new work, whatever file it came from.
if params.get("unsaved") == Some(&json!(true)) {
return None;
}
let path = match id {
"file.open" => PathBuf::from(params.get("path")?.as_str()?),
"file.open_recent" => match (params.get("index").and_then(Value::as_u64), params.get("path").and_then(Value::as_str)) {
(Some(i), _) => app.s.recent.entries().get(usize::try_from(i).ok()?)?.path.clone(),
(None, Some(p)) => PathBuf::from(p),
_ => return None,
},
_ => return None,
};
(0..app.tabs.len()).find(|i| session(app, *i).and_then(|s| s.path.as_deref()).is_some_and(|p| same_file(p, &path)))
}
/// The shown document is the one the app started with, untouched: what is opened takes its
/// place.
fn gives_way(app: &App) -> bool {
app.tabs.slots.get(app.tabs.active).is_some_and(|s| s.placeholder) && app.s.path.is_none() && !app.s.is_dirty() && app.s.history_len() == 0
}
/// Runs a command that brings a document (New, Open, a recent file, a template, a restored
/// copy) so that it arrives in a tab of its own; a file that is already open is shown instead.
/// When the command fails, the tab made for it goes again and the document that was shown is
/// back.
pub fn open(app: &mut App, id: &str, params: Value) -> Option<Value> {
if let Some(i) = already_open(app, id, &params) {
if activate(app, i) {
app.start = None;
app.status_ok(tr!("“{name}” is already open.", name = active_name(app)));
}
return None;
}
if gives_way(app) {
let v = app.perform_here(id, params)?;
if let Some(slot) = app.tabs.slots.get_mut(app.tabs.active) {
slot.placeholder = false;
}
arrived(app);
return Some(v);
}
if app.tabs.len() >= MAX_TABS {
app.status_err(trn!("{n} document is open, the most at once. Close one to open another.", "{n} documents are open, the most at once. Close one to open another.", MAX_TABS));
return None;
}
if let Some(why) = busy(app) {
app.status_err(why);
return None;
}
let from = app.tabs.slots.get(app.tabs.active).map(|s| s.id);
let id_new = app.tabs.next_id;
app.tabs.next_id += 1;
// The lowest number no open document without a file has.
let taken: Vec<u32> = (0..app.tabs.len()).filter(|i| session(app, *i).is_some_and(|s| s.path.is_none())).filter_map(|i| app.tabs.slots.get(i).map(|s| s.untitled)).collect();
let untitled = (1..=MAX_TABS as u32 + 1).find(|n| !taken.contains(n)).unwrap_or(1);
let parked = Parked { s: Session::new(Document::default()), view: DocView::fresh(app), saver: app.recovery.for_new_document() };
app.tabs.slots.push(Slot { id: id_new, untitled, placeholder: false, parked: Some(Box::new(parked)) });
if !activate(app, app.tabs.len() - 1) {
app.tabs.slots.pop();
return None;
}
match app.perform_here(id, params) {
Some(v) => Some(v),
None => {
// What went wrong stays in the status bar; the tab made for it goes.
let status = app.status.take();
if let Some(from) = from {
activate_id(app, from);
}
remove_parked(app, id_new);
app.status = status;
None
}
}
}
/// Drops a tab that isn't shown, ending its autosave cleanly (its copy goes).
fn remove_parked(app: &mut App, id: u64) {
let Some(i) = app.tabs.index_of(id) else { return };
if i == app.tabs.active || app.tabs.len() < 2 {
return;
}
let slot = app.tabs.slots.remove(i);
if let Some(mut p) = slot.parked {
p.saver.finish(&p.s, true);
}
if i < app.tabs.active {
app.tabs.active -= 1;
}
}
/// Closes tab `id` without asking (its changes were saved, or the answer was Don't Save). The
/// tab next to it shows; when it was the last one, an empty document takes its place and the
/// start screen comes up, as when the app starts. `false` when it can't be closed right now.
fn close_now(app: &mut App, id: u64) -> bool {
let Some(i) = app.tabs.index_of(id) else { return true };
if i != app.tabs.active {
remove_parked(app, id);
return true;
}
if app.tabs.len() > 1 {
let to = if i + 1 < app.tabs.len() { i + 1 } else { i - 1 };
if !activate(app, to) {
return false;
}
remove_parked(app, id);
return true;
}
if let Some(why) = busy(app) {
app.status_err(why);
return false;
}
settle(app);
// The last document: the window always has one.
app.recovery.doc.finish(&app.s, true);
app.recovery.doc = app.recovery.for_new_document();
app.s.replace_document(Document::default(), None);
let mut fresh = DocView::fresh(app);
fresh.swap(app);
if let Some(slot) = app.tabs.slots.get_mut(i) {
slot.untitled = 1;
slot.placeholder = true;
}
arrived(app);
if app.prefs.start_screen && app.shot.is_none() {
crate::start::open(app);
}
true
}
/// File › Close, a tab's × or middle click: closes these tabs, asking about each one that has
/// unsaved changes (ADR 0004).
pub fn close(app: &mut App, ids: Vec<u64>) {
if app.tabs.closing.is_some() || ids.is_empty() {
return;
}
app.playing = false;
app.tabs.closing = Some(CloseFlow { ids, quit: false, saving: false, asked: None });
}
/// The shown tab, the others, or all of them.
pub fn close_active(app: &mut App) {
let ids = info(app, app.tabs.active).map(|t| t.id).into_iter().collect();
close(app, ids);
}
pub fn close_others(app: &mut App, keep: u64) {
let ids = infos(app).into_iter().map(|t| t.id).filter(|id| *id != keep).collect();
close(app, ids);
}
pub fn close_all(app: &mut App) {
let ids = infos(app).into_iter().map(|t| t.id).collect();
close(app, ids);
}
/// The window is closing with unsaved changes somewhere: one question for all of them.
pub fn quit(app: &mut App) {
if app.tabs.closing.as_ref().is_some_and(|f| f.quit) {
return;
}
app.playing = false;
app.tabs.closing = Some(CloseFlow { ids: dirty_ids(app), quit: true, saving: false, asked: None });
}
/// The names of the documents the close question is about.
pub fn asked_about(app: &App) -> Vec<String> {
let Some(flow) = &app.tabs.closing else { return Vec::new() };
let all = infos(app);
let named = |id: &u64| all.iter().find(|t| t.id == *id && t.dirty).map(|t| t.name.clone());
if flow.quit { flow.ids.iter().filter_map(named).collect() } else { flow.ids.first().and_then(named).into_iter().collect() }
}
/// The close question's answer.
pub fn answer(app: &mut App, a: Answer) {
let Some(mut flow) = app.tabs.closing.take() else { return };
match a {
Answer::Cancel => {}
Answer::Save => {
flow.saving = true;
app.tabs.closing = Some(flow);
}
Answer::Discard if flow.quit => {
// Nothing is saved: the window goes (see `tick`).
flow.ids.clear();
app.tabs.closing = Some(flow);
}
Answer::Discard => {
if let Some(id) = flow.ids.first().copied()
&& close_now(app, id)
{
flow.ids.remove(0);
app.tabs.closing = Some(flow);
}
}
}
}
/// Starts saving the shown document: at once when it has a file, else Save As asks for one.
fn save_shown(app: &mut App) {
if app.s.path.is_some() {
app.perform("file.save", json!({}));
} else {
app.invoke("file.save_as");
}
}
/// Per frame: moves a close on. Tabs without unsaved changes close at once; one with changes
/// is shown and asked about; after Save, the flow waits for the save (and its Save As) and
/// goes on, or stops when the save was cancelled or failed. When every document of a quit is
/// dealt with, the window closes.
pub fn tick(app: &mut App, ctx: &egui::Context) {
let Some(mut flow) = app.tabs.closing.take() else { return };
loop {
let Some(&id) = flow.ids.first() else {
if flow.quit {
app.allow_close = true;
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close);
}
return;
};
let Some(i) = app.tabs.index_of(id) else {
flow.ids.remove(0);
continue;
};
if !session(app, i).is_some_and(Session::is_dirty) {
// Saved, or never changed. A quit leaves the tab: the window is about to go.
if !flow.quit && !close_now(app, id) {
return;
}
flow.ids.remove(0);
flow.asked = None;
// A tab's question was for that tab: the next one with changes asks again.
flow.saving = flow.saving && flow.quit;
continue;
}
if i != app.tabs.active && !activate(app, i) {
return;
}
if !flow.saving {
// The question shows (`dialogs::close_modal`).
break;
}
if flow.asked != Some(id) {
flow.asked = Some(id);
save_shown(app);
continue;
}
if app.prompt.is_some() || app.confirm.is_some() {
// Save As is asking for a name, or whether to replace a file.
break;
}
// The save was cancelled or failed: the document stays open, and so does the window.
return;
}
app.tabs.closing = Some(flow);
}
/// Moves the tab at `from` to `to` in the bar; the shown document stays shown.
fn move_tab(app: &mut App, from: usize, to: usize) {
let n = app.tabs.len();
if from == to || from >= n || to >= n {
return;
}
let shown = app.tabs.slots.get(app.tabs.active).map(|s| s.id);
let slot = app.tabs.slots.remove(from);
app.tabs.slots.insert(to, slot);
if let Some(i) = shown.and_then(|id| app.tabs.index_of(id)) {
app.tabs.active = i;
}
}
/// What the bar asks for this frame.
enum Act {
Show(u64),
Close(u64),
CloseOthers(u64),
CloseAll,
Reveal(PathBuf),
Move(usize, usize),
}
/// `name` in one line no wider than `width`, cut with an ellipsis.
fn elided(p: &egui::Painter, name: &str, width: f32) -> std::sync::Arc<egui::Galley> {
let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font(Type::Body), T.text);
job.wrap = egui::text::TextWrapping { max_width: width.max(1.0), max_rows: 1, break_anywhere: true, overflow_character: Some('…') };
p.layout_job(job)
}
/// What a screen reader says for a tab.
fn spoken(t: &TabInfo) -> String {
if t.dirty { tr!("{name}, unsaved changes", name = t.name) } else { t.name.clone() }
}
/// The document tabs, above the edit bar: one per open document, with a dot while it has
/// unsaved changes and a button to close it. Click shows a document, middle click closes it,
/// a drag moves the tab, right-click has Close, Close Others, Close All and where the file is.
pub fn bar(app: &mut App, ui: &mut egui::Ui) {
let tabs = infos(app);
let full = ui.max_rect();
let mut acts: Vec<Act> = Vec::new();
// How wide each tab is: its name, within limits; all a little narrower when they don't fit.
let natural: Vec<f32> = tabs.iter().map(|t| (elided(ui.painter(), &t.name, TAB_MAX).rect.width() + 2.0 * PAD + CLOSE_W + DOT_W).clamp(TAB_MIN, TAB_MAX)).collect();
let wanted: f32 = natural.iter().sum();
let shrink = if wanted > full.width() && wanted > 0.0 { (full.width() / wanted).max(TAB_MIN / TAB_MAX) } else { 1.0 };
let widths: Vec<f32> = natural.iter().map(|w| (w * shrink).max(TAB_MIN.min(*w))).collect();
let total: f32 = widths.iter().sum();
let max_scroll = (total - full.width()).max(0.0);
// The wheel moves along the tabs when they still don't fit.
if max_scroll > 0.0 && ui.rect_contains_pointer(full) {
let d = ui.input(|i| i.smooth_scroll_delta);
app.tabs.scroll -= if d.x.abs() > d.y.abs() { d.x } else { d.y };
}
if std::mem::take(&mut app.tabs.reveal) {
let before: f32 = widths.iter().take(app.tabs.active).sum();
let w = widths.get(app.tabs.active).copied().unwrap_or(0.0);
app.tabs.scroll = app.tabs.scroll.min(before).max(before + w - full.width());
}
app.tabs.scroll = app.tabs.scroll.clamp(0.0, max_scroll);
let pointer = ui.input(|i| i.pointer.interact_pos());
let mut rects = Vec::with_capacity(tabs.len());
ui.scope_builder(egui::UiBuilder::new().id_salt("document_tabs").max_rect(full), |ui| {
// A tab list, for screen readers: its tabs are the open documents.
ui.ctx().accesskit_node_builder(ui.unique_id(), |node| {
node.set_role(egui::accesskit::Role::TabList);
node.set_label(tr!("Open documents"));
});
ui.set_clip_rect(full.intersect(ui.clip_rect()));
let mut x = full.left() - app.tabs.scroll;
for (i, t) in tabs.iter().enumerate() {
let w = widths.get(i).copied().unwrap_or(TAB_MIN);
let r = Rect::from_min_size(pos2(x, full.top()), vec2(w, full.height()));
x += w;
rects.push((t.id, r));
let shown = r.intersect(full);
if shown.width() <= 0.0 {
continue;
}
let resp = ui.interact(shown, Id::new(("document_tab", t.id)), Sense::click_and_drag());
let said = spoken(t);
resp.widget_info(|| egui::WidgetInfo::selected(WidgetType::SelectableLabel, true, t.active, &said));
ui.ctx().accesskit_node_builder(resp.id, |node| {
node.set_role(egui::accesskit::Role::Tab);
node.set_selected(t.active);
});
let close_r = Rect::from_center_size(pos2(r.right() - PAD * 0.5 - CLOSE_W * 0.5, r.center().y), vec2(CLOSE_W - 4.0, CLOSE_W - 4.0));
let close = ui.interact(close_r.intersect(full), Id::new(("document_tab_close", t.id)), Sense::click());
a11y::control(ui, &close, WidgetType::Button, &tr!("Close {name}", name = t.name), None);
// The tab: the shown one joins the edit bar below it.
let p = ui.painter();
if t.active {
p.rect_filled(r, theme::SQUARE, T.panel);
p.rect_filled(Rect::from_min_max(r.left_top(), pos2(r.right(), r.top() + 2.0)), theme::SQUARE, T.accent);
} else if resp.hovered() || close.hovered() {
p.rect_filled(r, theme::SQUARE, T.hover);
}
p.vline(r.right(), r.top() + 6.0..=r.bottom() - 6.0, Stroke::new(1.0, T.border));
let mut left = r.left() + PAD;
if t.dirty {
// Unsaved changes: a dot before the name.
p.circle_filled(pos2(left + 3.5, r.center().y), 3.5, if t.active { T.accent } else { T.text_dim });
left += DOT_W;
}
let galley = elided(p, &t.name, close_r.left() - 4.0 - left);
let cut = galley.elided;
p.galley_with_override_text_color(pos2(left, r.center().y - galley.rect.height() * 0.5), galley, if t.active { T.text } else { T.text_dim });
// The close button: an ×, brighter under the pointer.
if close.hovered() {
p.rect_filled(close_r, T.rc(), T.hover);
}
let (c, d) = (close_r.center(), 4.0);
let ink = Stroke::new(1.5, if close.hovered() || close.has_focus() { T.icon_hot } else { T.icon });
p.line_segment([c + vec2(-d, -d), c + vec2(d, d)], ink);
p.line_segment([c + vec2(-d, d), c + vec2(d, -d)], ink);
if resp.has_focus() {
p.rect_stroke(r, T.rc(), Stroke::new(2.0, T.accent), StrokeKind::Inside);
}
// What it does.
if close.clicked() || resp.clicked_by(egui::PointerButton::Middle) {
acts.push(Act::Close(t.id));
} else if resp.clicked() {
acts.push(Act::Show(t.id));
}
if resp.drag_started_by(egui::PointerButton::Primary) {
app.tabs.drag = Some(t.id);
acts.push(Act::Show(t.id));
}
let place = match &t.path {
Some(path) => path.display().to_string(),
None => tr!("Not saved yet").to_string(),
};
let tip = if cut { format!("{}\n{place}", t.name) } else { place };
close.on_hover_text(tr!("Close"));
let resp = resp.on_hover_text(tip);
resp.context_menu(|ui| {
let item = |ui: &mut egui::Ui, on: bool, label: &str| {
let hit = ui.add_enabled(on, egui::Button::new(label)).clicked();
if hit {
ui.close();
}
hit
};
if item(ui, true, tr!("Close")) {
acts.push(Act::Close(t.id));
}
if item(ui, tabs.len() > 1, tr!("Close Others")) {
acts.push(Act::CloseOthers(t.id));
}
if item(ui, true, tr!("Close All")) {
acts.push(Act::CloseAll);
}
ui.separator();
// Only a file that is somewhere can be shown there.
if item(ui, t.path.is_some() && !platform::WEB, platform::reveal_label())
&& let Some(path) = &t.path
{
acts.push(Act::Reveal(path.clone()));
}
});
}
// A dragged tab changes places with a neighbour once the pointer is past its middle.
if let Some(id) = app.tabs.drag {
if !ui.input(|i| i.pointer.primary_down()) {
app.tabs.drag = None;
} else if let (Some(at), Some(from)) = (pointer, tabs.iter().position(|t| t.id == id)) {
let mid = |i: usize| rects.get(i).map(|(_, r): &(u64, Rect)| r.center().x);
if from > 0 && mid(from - 1).is_some_and(|m| at.x < m) {
acts.push(Act::Move(from, from - 1));
} else if mid(from + 1).is_some_and(|m| at.x > m) {
acts.push(Act::Move(from, from + 1));
}
}
}
});
app.tabs.rects = rects;
for act in acts {
match act {
Act::Show(id) => {
activate_id(app, id);
}
Act::Close(id) => close(app, vec![id]),
Act::CloseOthers(id) => close_others(app, id),
Act::CloseAll => close_all(app),
Act::Move(from, to) => move_tab(app, from, to),
Act::Reveal(path) => match platform::reveal_in_folder(&path) {
Ok(()) => app.status_ok(tr!("Shown in your system's file viewer")),
Err(e) => app.status_err(e),
},
}
}
}
/// `--open tabs` (screenshots and the guide): three documents open, the shown one with unsaved
/// changes.
pub fn sample(app: &mut App) {
let name = |app: &mut App, file: &str| {
app.s.path = Some(PathBuf::from(file));
app.s.mark_saved();
};
app.tabs.keep_first();
name(app, "walk-cycle.anicraft");
app.perform("file.new", crate::start::new_params(1280, 720, 24.0));
name(app, "title-card.anicraft");
app.perform("file.new_sample", json!({}));
app.run("draw.rect", json!({"x": 420, "y": 250, "w": 160, "h": 100, "fill": "#f2b134", "stroke": null}));
let _ = app.s.execute("edit.deselect", &json!({}));
app.status_ok(tr!("Three documents are open: click a tab to show it, or press {key}.", key = platform::shortcut_label("Ctrl+Tab")));
}
#[cfg(test)]
#[path = "tabs_tests.rs"]
mod tests;
+416
View File
@@ -0,0 +1,416 @@
//! Document tabs (ADR 0112): each open document keeps its own undo history, selection,
//! playhead and view; artwork pastes across them with its symbols; closing with unsaved changes
//! asks; autosave covers every open document.
use super::*;
use egui::{Event, Key, Modifiers, RawInput};
fn app() -> (egui::Context, App) {
let ctx = egui::Context::default();
let session = Session::new(anicraft_engine::doc::sample::demo());
let app = App::with_context(&ctx, session, Some(PathBuf::from("unused.png")));
(ctx, app)
}
fn input(modifiers: Modifiers, events: Vec<Event>) -> RawInput {
let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect();
RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1600.0, 940.0))), events, ..Default::default() }
}
fn frame(ctx: &egui::Context, app: &mut App, input: RawInput) -> egui::FullOutput {
let mut out = ctx.run_ui(input, |ui| app.frame(ui));
out.textures_delta.clear();
out
}
fn settle(ctx: &egui::Context, app: &mut App) {
for _ in 0..3 {
frame(ctx, app, input(Modifiers::NONE, vec![]));
}
}
fn key(k: Key, m: Modifiers) -> RawInput {
input(m, vec![Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m }])
}
/// Ctrl as egui-winit reports it on Windows and Linux (Ctrl is the command key there).
fn ctrl() -> Modifiers {
Modifiers { ctrl: true, command: true, ..Modifiers::NONE }
}
fn names(app: &App) -> Vec<String> {
infos(app).into_iter().map(|t| t.name).collect()
}
/// The sample plus two new documents; the third is shown.
fn three(app: &mut App) {
app.tabs.keep_first();
app.perform("file.new", json!({"width": 640, "height": 480}));
app.perform("file.new", json!({"width": 800, "height": 600}));
assert_eq!(app.tabs.len(), 3);
}
fn click(ctx: &egui::Context, app: &mut App, at: egui::Pos2, button: egui::PointerButton) {
frame(ctx, app, input(Modifiers::NONE, vec![Event::PointerMoved(at)]));
for pressed in [true, false] {
frame(ctx, app, input(Modifiers::NONE, vec![Event::PointerButton { pos: at, button, pressed, modifiers: Modifiers::NONE }]));
}
}
fn tab_rect(app: &App, i: usize) -> Rect {
app.tabs.rects[i].1
}
#[test]
fn the_first_document_opened_takes_the_samples_place_and_the_next_gets_a_tab() {
let (_, mut app) = app();
assert_eq!(app.tabs.len(), 1);
app.request("file.new", json!({"width": 640, "height": 480}));
assert_eq!(app.tabs.len(), 1, "the untouched sample gives way");
assert_eq!(app.s.doc.stage.width, 640);
app.request("file.new", json!({"width": 800, "height": 600}));
assert_eq!((app.tabs.len(), app.tabs.active()), (2, 1), "a document of the user's stays; the new one is shown");
assert_eq!(names(&app), ["Untitled", "Untitled 2"]);
// Over unsaved work nothing is asked: the work stays open in its tab.
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
app.request("file.new", json!({}));
assert!(app.confirm.is_none());
assert_eq!(app.tabs.len(), 3);
assert!(infos(&app)[1].dirty);
// A changed sample is the user's work too.
let (_, mut app) = self::app();
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
app.request("file.new", json!({}));
assert_eq!(app.tabs.len(), 2);
}
#[test]
fn switching_keeps_each_documents_undo_selection_playhead_and_view() {
let (ctx, mut app) = app();
three(&mut app);
// The third document: a rectangle, selected; frame 0; zoomed in.
app.run("draw.rect", json!({"x": 10, "y": 10, "w": 50, "h": 50}));
settle(&ctx, &mut app);
app.view.fit = false;
app.view.zoom = 3.0;
app.view.pan = vec2(40.0, -20.0);
app.me_vscroll = 12.0;
app.run("edit.select_all", json!({}));
let (third_state, third_steps, third_sel) = (app.s.state, app.s.history_len(), app.s.selection.len());
assert!(third_steps == 1 && third_sel > 0);
// The first (the sample): playhead moved, another zoom.
assert!(activate(&mut app, 0));
assert_eq!(app.s.doc.library.len(), 2, "the sample's Library shows");
assert_eq!((app.s.history_len(), app.s.selection.len()), (0, 0), "its own history and selection");
app.run("timeline.goto", json!({"frame": 7}));
app.run("edit.select_all", json!({}));
app.run("element.translate", json!({"dx": 5, "dy": 0}));
app.view.fit = false;
app.view.zoom = 0.5;
let first_sel = app.s.selection.len();
// Back: everything as it was left, and undo acts on that document only.
assert!(activate(&mut app, 2));
assert_eq!((app.s.state, app.s.history_len(), app.s.selection.len(), app.s.frame), (third_state, third_steps, third_sel, 0));
assert_eq!((app.view.zoom, app.view.pan, app.me_vscroll), (3.0, vec2(40.0, -20.0), 12.0));
app.invoke("edit.undo");
assert_eq!(app.s.elements_on(app.s.layer).len(), 0);
assert!(activate(&mut app, 0));
assert_eq!((app.s.frame, app.s.selection.len(), app.s.history_len(), app.view.zoom), (7, first_sel, 1, 0.5));
// The untouched second.
assert!(activate(&mut app, 1));
assert_eq!((app.s.doc.stage.width, app.s.history_len(), app.view.fit), (640, 0, true));
}
#[test]
fn a_copy_in_one_document_pastes_into_another_with_its_symbols() {
let (_, mut app) = app();
app.tabs.keep_first();
// The sample's ball (a symbol instance) is copied…
app.run("layer.select", json!({"index": 0}));
app.run("edit.select_all", json!({}));
app.invoke("edit.copy");
let copied = app.s.selection.len();
assert!(copied > 0);
// …and pasted into a new document, which has a symbol of its own under that name.
app.perform("file.new", json!({}));
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
app.run("modify.convert_to_symbol", json!({"name": "Ball"}));
app.invoke("edit.paste");
let lib: Vec<&str> = app.s.doc.library.iter().map(|s| s.name.as_str()).collect();
assert_eq!(lib.first(), Some(&"Ball"), "{lib:?}");
assert!(lib.contains(&"Ball 2"), "the copied symbol came along, renamed: {lib:?}");
let uses = app.s.doc.library_uses();
let came = app.s.doc.library.iter().find(|s| s.name == "Ball 2").unwrap().id;
assert!(uses.get(&LibraryItem::Symbol(came)).is_some_and(|n| *n >= 1), "and the pasted instance places it");
// The sample is as it was.
assert!(activate(&mut app, 0));
assert_eq!(app.s.doc.library.len(), 2);
assert!(!app.s.is_dirty());
}
#[test]
fn closing_a_tab_with_unsaved_changes_asks_and_a_saved_one_just_closes() {
let (ctx, mut app) = app();
three(&mut app);
// The second is untouched: it closes at once.
let second = infos(&app)[1].id;
close(&mut app, vec![second]);
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 2);
assert!(!app.tabs.asking());
// The shown one has changes: the question, and Cancel keeps it.
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
close_active(&mut app);
settle(&ctx, &mut app);
assert!(app.tabs.asking() && app.modal_open(), "unsaved changes ask first (ADR 0004)");
assert_eq!(asked_about(&app), ["Untitled 3"]);
answer(&mut app, Answer::Cancel);
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 2);
assert!(app.s.is_dirty(), "the work is still there");
// Don't Save closes it; the document next to it shows.
close_active(&mut app);
settle(&ctx, &mut app);
answer(&mut app, Answer::Discard);
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 1);
assert_eq!(app.s.doc.library.len(), 2, "the sample is shown");
assert!(app.tabs.closing.is_none());
}
#[test]
fn save_in_the_question_saves_then_closes_and_a_cancelled_save_as_keeps_the_tab() {
let (ctx, mut app) = app();
three(&mut app);
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
close_active(&mut app);
settle(&ctx, &mut app);
answer(&mut app, Answer::Save);
settle(&ctx, &mut app);
assert!(app.prompt.as_ref().is_some_and(|p| p.cmd == "file.save_as"), "a document without a file asks for a name");
// Cancelled: nothing closes.
app.prompt = None;
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 3);
assert!(app.tabs.closing.is_none() && app.s.is_dirty());
// Saved: the tab closes.
let dir = std::env::temp_dir().join(format!("anicraft-tabs-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("third.anicraft");
close_active(&mut app);
settle(&ctx, &mut app);
answer(&mut app, Answer::Save);
settle(&ctx, &mut app);
let p = app.prompt.take().unwrap();
app.request(p.cmd, json!({ p.key: file.display().to_string() }));
settle(&ctx, &mut app);
assert!(file.exists());
assert_eq!(app.tabs.len(), 2);
// Opening it again shows a new tab; opening it a second time shows that tab.
app.request("file.open", json!({"path": file.display().to_string()}));
assert_eq!((app.tabs.len(), app.tabs.active()), (3, 2));
assert!(activate(&mut app, 0));
app.request("file.open", json!({"path": file.display().to_string()}));
assert_eq!((app.tabs.len(), app.tabs.active()), (3, 2), "already open: its tab is shown");
// A file that can't be opened leaves no tab behind.
app.request("file.open", json!({"path": dir.join("missing.anicraft").display().to_string()}));
assert_eq!((app.tabs.len(), app.tabs.active()), (3, 2));
assert!(app.status.as_ref().is_some_and(|s| s.error));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn quitting_asks_once_for_every_unsaved_document() {
let (ctx, mut app) = app();
three(&mut app);
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
assert!(activate(&mut app, 0));
app.run("layer.new", json!({}));
quit(&mut app);
settle(&ctx, &mut app);
assert!(app.tabs.asking());
assert_eq!(asked_about(&app), ["Untitled", "Untitled 3"], "one question names both");
assert!(!app.allow_close);
// Cancel: the window stays, with everything open.
answer(&mut app, Answer::Cancel);
settle(&ctx, &mut app);
assert!(!app.allow_close && app.tabs.len() == 3);
// Don't Save: the window may go.
quit(&mut app);
settle(&ctx, &mut app);
answer(&mut app, Answer::Discard);
settle(&ctx, &mut app);
assert!(app.allow_close);
// Save All with a document that needs a name: asked, and cancelling stops the quit.
let (ctx, mut app) = self::app();
three(&mut app);
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
quit(&mut app);
settle(&ctx, &mut app);
answer(&mut app, Answer::Save);
settle(&ctx, &mut app);
assert!(app.prompt.is_some());
app.prompt = None;
settle(&ctx, &mut app);
assert!(!app.allow_close && app.tabs.closing.is_none());
}
#[test]
fn closing_the_last_document_leaves_an_empty_one() {
let (ctx, mut app) = app();
app.tabs.keep_first();
close_all(&mut app);
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 1);
assert!(app.s.doc.library.is_empty() && !app.s.is_dirty(), "a blank page");
// Which gives way to the next document opened.
app.request("file.new_sample", json!({}));
assert_eq!(app.tabs.len(), 1);
assert_eq!(app.s.doc.library.len(), 2);
}
#[test]
fn tabs_are_clicked_closed_with_the_middle_button_and_switched_with_the_keys() {
let (ctx, mut app) = app();
three(&mut app);
settle(&ctx, &mut app);
assert_eq!(app.tabs.rects.len(), 3);
// A click shows the document.
let at = tab_rect(&app, 0).left_center() + vec2(30.0, 0.0);
click(&ctx, &mut app, at, egui::PointerButton::Primary);
assert_eq!(app.tabs.active(), 0);
// Ctrl+Tab and Ctrl+Shift+Tab go round; Ctrl+PageDown and Ctrl+PageUp too.
frame(&ctx, &mut app, key(Key::Tab, ctrl()));
assert_eq!(app.tabs.active(), 1);
frame(&ctx, &mut app, key(Key::Tab, Modifiers { shift: true, ..ctrl() }));
frame(&ctx, &mut app, key(Key::Tab, Modifiers { shift: true, ..ctrl() }));
assert_eq!(app.tabs.active(), 2, "round the end");
frame(&ctx, &mut app, key(Key::PageDown, ctrl()));
assert_eq!(app.tabs.active(), 0);
frame(&ctx, &mut app, key(Key::PageUp, ctrl()));
assert_eq!(app.tabs.active(), 2);
// The middle button closes a tab (this one has no changes).
settle(&ctx, &mut app);
let at = tab_rect(&app, 1).left_center() + vec2(30.0, 0.0);
click(&ctx, &mut app, at, egui::PointerButton::Middle);
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 2);
// Ctrl+W closes the shown one; its × does too.
frame(&ctx, &mut app, key(Key::W, ctrl()));
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 1);
app.perform("file.new", json!({}));
settle(&ctx, &mut app);
let at = pos2(tab_rect(&app, 1).right() - PAD * 0.5 - CLOSE_W * 0.5, tab_rect(&app, 1).center().y);
click(&ctx, &mut app, at, egui::PointerButton::Primary);
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 1);
}
#[test]
fn a_dragged_tab_changes_places_and_the_shown_document_stays_shown() {
let (ctx, mut app) = app();
three(&mut app);
settle(&ctx, &mut app);
let ids: Vec<u64> = infos(&app).iter().map(|t| t.id).collect();
let from = tab_rect(&app, 2).left_center() + vec2(30.0, 0.0);
let to = tab_rect(&app, 0).left_center() + vec2(10.0, 0.0);
frame(&ctx, &mut app, input(Modifiers::NONE, vec![Event::PointerMoved(from)]));
frame(&ctx, &mut app, input(Modifiers::NONE, vec![Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]));
for step in 1..=12 {
let at = from + (to - from) * (step as f32 / 12.0);
frame(&ctx, &mut app, input(Modifiers::NONE, vec![Event::PointerMoved(at)]));
}
frame(&ctx, &mut app, input(Modifiers::NONE, vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]));
settle(&ctx, &mut app);
let now: Vec<u64> = infos(&app).iter().map(|t| t.id).collect();
assert_eq!(now, [ids[2], ids[0], ids[1]], "the third tab is first");
assert_eq!(app.tabs.active(), 0, "and still the one shown");
assert_eq!(app.s.doc.stage.width, 800);
}
#[test]
fn the_tabs_are_a_tab_list_for_screen_readers() {
use egui::accesskit::Role;
let (ctx, mut app) = app();
ctx.enable_accesskit();
three(&mut app);
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
settle(&ctx, &mut app);
let update = frame(&ctx, &mut app, input(Modifiers::NONE, vec![])).platform_output.accesskit_update.unwrap();
let list = update.nodes.iter().find(|(_, n)| n.role() == Role::TabList).expect("a tab list");
assert_eq!(list.1.label(), Some("Open documents"));
let tabs: Vec<_> = update.nodes.iter().filter(|(_, n)| n.role() == Role::Tab).collect();
assert_eq!(tabs.len(), 3);
assert!(tabs.iter().all(|(id, _)| list.1.children().contains(id)), "the tabs are the list's");
let mut said: Vec<(&str, Option<bool>)> = tabs.iter().filter_map(|(_, n)| Some((n.label()?, n.is_selected()))).collect();
said.sort();
assert_eq!(said, [("Untitled", Some(false)), ("Untitled 2", Some(false)), ("Untitled 3, unsaved changes", Some(true))]);
// Each has a named button to close it.
assert!(update.nodes.iter().any(|(_, n)| n.role() == Role::Button && n.label() == Some("Close Untitled 2")));
}
#[test]
fn a_document_that_is_not_shown_keeps_no_pictures() {
let (ctx, mut app) = app();
app.tabs.keep_first();
settle(&ctx, &mut app);
let _ = app.s.display_list();
app.perform("file.new", json!({}));
assert_eq!(app.stage_cache.tile_count(), 0, "the tiles of the document put aside are gone");
assert!(app.stage_cache.stats().is_none_or(|(n, _, _)| n == 0), "and the render cache's pictures");
assert!(app.stage_cache.shown_state.is_none());
}
/// In a recovery folder of this test's own.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn autosave_and_recovery_cover_every_open_document() {
use anicraft_engine::recovery;
let dir = std::env::temp_dir().join(format!("anicraft-tabs-recovery-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let wait = |saver_ids: &[String]| {
for _ in 0..200 {
if saver_ids.iter().all(|id| recovery::document_path(&dir, id).exists()) {
return;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
panic!("the copies were not written");
};
crate::platform::set_recovery_dir_for_tests(Some(dir.clone()));
{
let (ctx, mut app) = app();
three(&mut app);
let ids = recovery_sessions(&app);
assert_eq!(ids.len(), 3, "each open document is its own recovery session");
assert_eq!(ids.iter().collect::<HashSet<_>>().len(), 3);
// Unsaved work in the third and the first; the second is untouched.
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
assert!(activate(&mut app, 0), "putting a document aside copies its unsaved work");
app.run("layer.new", json!({}));
settle(&ctx, &mut app);
// The window goes without a decision (a crash, as far as the copies can tell).
finish_all(&mut app, false);
// (The shown document's session comes first, then the others in tab order.)
wait(&[ids[0].clone(), ids[1].clone()]);
assert!(!recovery::document_path(&dir, &ids[2]).exists(), "nothing to recover for the untouched one");
}
// The next start finds both and restores each into a tab of its own.
let (ctx, mut app) = app();
assert_eq!(app.recovery.found.len(), 2);
let found: Vec<String> = app.recovery.found.iter().map(|e| e.session.clone()).collect();
for id in &found {
app.request("file.recover", json!({"dir": dir.display().to_string(), "session": id}));
}
settle(&ctx, &mut app);
assert_eq!(app.tabs.len(), 2, "the first takes the sample's place, the second gets a tab");
assert!(infos(&app).iter().all(|t| t.dirty), "restored work is unsaved work");
assert!(app.recovery.found.is_empty());
// A clean end removes this session's copies.
app.allow_close = true;
finish_all(&mut app, true);
crate::platform::set_recovery_dir_for_tests(None);
let _ = std::fs::remove_dir_all(&dir);
}
+3 -3
View File
@@ -351,12 +351,12 @@ mod tests {
assert!(app.start.is_none(), "the start screen goes once the document is there");
assert_eq!((app.s.doc.stage.width, app.s.doc.stage.height), (300, 250));
assert!(app.status.as_ref().is_some_and(|s| !s.error && s.text.contains("Rectangle banner")), "{:?}", app.status.as_ref().map(|s| &s.text));
// Over unsaved work it asks first.
// Over unsaved work it opens in a tab of its own (ADR 0112).
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
app.request("file.new_from_template", json!({"template": "storyboard"}));
assert!(app.confirm.is_some());
assert!(app.confirm.is_none());
assert_eq!(app.tabs.len(), 2);
// The section draws every built-in template with its picture.
app.confirm = None;
crate::start::open(&mut app);
sample_user(&mut app);
let screen = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() };