mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-23 19:12:08 +01:00
Merge pull request #170 from storytold/m8/files-and-start
feat(shell): drop files onto the window, Open Recent and a start screen (M8)
This commit is contained in:
33 files changed
+2242
-28
No files matched your search
@@ -2,6 +2,24 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Files from the desktop, recent files and a start screen** (ADR 0059, M8).
|
||||
* **Drop files onto the window**: `.anicraft`, `.fla` and `.xfl` open (asking first over
|
||||
unsaved work); SVG drawings, PNG and JPEG images and WAV, Ogg and MP3 sounds dropped on the
|
||||
**stage** go onto the active layer at the playhead, centred where they were dropped, and
|
||||
dropped on the **Library** go into the folder under the pointer. One undo step per drop.
|
||||
A highlight shows where they will land; anything AniCraft can't take gets one clear
|
||||
status line. In the web editor too.
|
||||
* **File › Open Recent**: the last 10 documents opened or saved, with pinned favourites on
|
||||
top, missing files greyed out with Remove, and Clear Recent Files. Kept in the
|
||||
preferences (browser storage on the web).
|
||||
* **Start screen** when AniCraft starts without a document: New with HD, Full HD, square
|
||||
and vertical presets or a custom size and frame rate, Open, the sample animation, and the
|
||||
recent files with a picture of their first frame (captured on save). Esc goes back to the
|
||||
document; File › Start Screen brings it back; it can be switched off.
|
||||
* New commands for the CLI and MCP: `file.drop`, `file.open_recent`, `file.recent_list`,
|
||||
`prefs.recent_pin`, `prefs.recent_remove`, `prefs.recent_clear`; `file.import` takes
|
||||
`cx`/`cy` and `layer: "active"`.
|
||||
|
||||
* **Buttons, complete: sounds on button frames and hit-area editing** (ADR 0057, M5).
|
||||
* A sound on a button's **Over** or **Down** frame plays when the pointer goes over or
|
||||
presses the button, in Test Movie and in the HTML canvas page (Web Audio). As the SWF format
|
||||
|
||||
+1
-1
@@ -123,7 +123,7 @@ wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
# In the browser the page's language (navigator.languages) is the system's.
|
||||
sys-locale = { version = "0.3", features = ["js"] }
|
||||
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] }
|
||||
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] }
|
||||
|
||||
[build-dependencies]
|
||||
# Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets.
|
||||
|
||||
@@ -222,6 +222,7 @@ pub(crate) mod base64_bytes {
|
||||
}
|
||||
}
|
||||
|
||||
pub use base64_bytes::decode as base64_decode;
|
||||
pub use base64_bytes::encode as base64_encode;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -26,7 +26,7 @@ pub mod sample;
|
||||
pub mod sound;
|
||||
|
||||
pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at};
|
||||
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png};
|
||||
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png};
|
||||
pub use easing::Easing;
|
||||
pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform};
|
||||
pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre};
|
||||
|
||||
@@ -916,7 +916,7 @@ const MAX_PLACE: usize = 1_000;
|
||||
/// does (ADR 0053): an instance of each symbol, a rectangle of each bitmap's size showing it,
|
||||
/// in the active layer's keyframe at the playhead, all selected; a sound goes onto that
|
||||
/// keyframe. One command, so one undo step however many items.
|
||||
fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let items: Vec<LibraryItem> = match p.get("items") {
|
||||
Some(list) => {
|
||||
let list = list.as_array().ok_or_else(|| EngineError::Param("param 'items' must be a list of {\"symbol\" | \"bitmap\" | \"sound\": id}".into()))?;
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Files dropped onto the window (ADR 0059). What a file is, and where it was dropped, decide
|
||||
//! what happens: documents open (`file.open`, which asks first over unsaved work); drawings,
|
||||
//! images and sounds dropped on the stage go onto the active layer at the playhead at the drop
|
||||
//! point, and dropped on the Library go into the Library (into the folder under the pointer).
|
||||
//! The routing is a pure function the shell and tests share; `file.drop` does the import, so a
|
||||
//! drop of several files is one undo step however many it brings in.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{FolderId, LibraryEntry, LibraryItem};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Most files one drop brings in.
|
||||
pub const MAX_DROPPED: usize = 64;
|
||||
|
||||
/// What a dropped file is, by its name (and, for an XFL folder, what is inside it).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DropKind {
|
||||
/// `.anicraft`, `.fla`, `.xfl` (or an XFL folder): opens as the document.
|
||||
Document,
|
||||
/// `.svg`.
|
||||
Drawing,
|
||||
/// `.png`, `.jpg`, `.jpeg`.
|
||||
Image,
|
||||
/// `.wav`, `.ogg`, `.mp3`.
|
||||
Sound,
|
||||
/// Anything else.
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
/// Where a file was dropped.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DropTarget {
|
||||
Stage,
|
||||
Library,
|
||||
/// Anywhere else on the window (panels, the timeline, the menu bar).
|
||||
Window,
|
||||
}
|
||||
|
||||
/// What a drop does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DropAction {
|
||||
/// Open it as the document (`file.open`).
|
||||
Open,
|
||||
/// `file.drop` with `to: "stage"`.
|
||||
ImportToStage,
|
||||
/// `file.drop` with `to: "library"`.
|
||||
ImportToLibrary,
|
||||
/// Nothing; the message (English, translated where it is shown) says why.
|
||||
Refuse(&'static str),
|
||||
}
|
||||
|
||||
pub fn kind_of(path: &Path) -> DropKind {
|
||||
if crate::cmds_file::is_animate(path) {
|
||||
return DropKind::Document;
|
||||
}
|
||||
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
match ext.as_deref() {
|
||||
Some("anicraft") => DropKind::Document,
|
||||
Some("svg") => DropKind::Drawing,
|
||||
Some("png" | "jpg" | "jpeg") => DropKind::Image,
|
||||
_ if crate::cmds_sound::is_sound(path) => DropKind::Sound,
|
||||
_ => DropKind::Unsupported,
|
||||
}
|
||||
}
|
||||
|
||||
/// The message for a file AniCraft can't take.
|
||||
pub const UNSUPPORTED: &str = "AniCraft opens .anicraft, .fla and .xfl documents, and imports SVG drawings, PNG and JPEG images, and WAV, Ogg and MP3 sounds";
|
||||
|
||||
/// What dropping a file of `kind` on `target` does.
|
||||
pub fn route(kind: DropKind, target: DropTarget) -> DropAction {
|
||||
match (kind, target) {
|
||||
(DropKind::Document, _) => DropAction::Open,
|
||||
(DropKind::Unsupported, _) => DropAction::Refuse(UNSUPPORTED),
|
||||
(DropKind::Drawing, DropTarget::Library) => DropAction::Refuse("SVG drawings import to the stage: drop it there"),
|
||||
(_, DropTarget::Library) => DropAction::ImportToLibrary,
|
||||
(_, DropTarget::Stage) => DropAction::ImportToStage,
|
||||
// Not over the stage or the Library: drop it on one of them.
|
||||
(_, DropTarget::Window) => DropAction::Refuse("Drop drawings, images and sounds on the stage to place them, or on the Library to add them"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![CommandSpec {
|
||||
id: "file.drop",
|
||||
label: "Import Dropped Files",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{paths: [..] (or path; SVG, PNG, JPEG, WAV, OGG, MP3; at most 64), to: stage | library, x?, y? (stage: the drop point in the edited space, default the stage centre), folder? (library: a folder id)} → {elements, items, layers}: on the stage each drawing, image and sound goes onto the active layer's keyframe at the playhead, centred on the drop point (a drawing with several layers or masks gets its own layers, as Import to Stage); in the Library images and sounds are added, into `folder`. One undo step",
|
||||
mutates: true,
|
||||
run: drop,
|
||||
}]
|
||||
}
|
||||
|
||||
fn paths(p: &Value) -> Result<Vec<PathBuf>> {
|
||||
let list: Vec<PathBuf> = match (p.get("paths"), opt_str(p, "path")?) {
|
||||
(Some(v), None) => {
|
||||
let a = v.as_array().ok_or_else(|| EngineError::Param("param 'paths' must be a list of file paths".into()))?;
|
||||
a.iter().map(|x| x.as_str().map(PathBuf::from).ok_or_else(|| EngineError::Param("param 'paths' must be a list of file paths".into()))).collect::<Result<_>>()?
|
||||
}
|
||||
(None, Some(one)) => vec![PathBuf::from(one)],
|
||||
_ => return Err(EngineError::Param("name the files with 'paths' (or one with 'path')".into())),
|
||||
};
|
||||
if list.is_empty() || list.len() > MAX_DROPPED {
|
||||
return Err(EngineError::Param(format!("drop 1 to {MAX_DROPPED} files at once")));
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
fn drop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let files = paths(p)?;
|
||||
let target = match str_req(p, "to")? {
|
||||
"stage" => DropTarget::Stage,
|
||||
"library" => DropTarget::Library,
|
||||
other => return Err(EngineError::Param(format!("param 'to' must be stage or library, not '{other}'"))),
|
||||
};
|
||||
// Everything is checked before anything is imported (the command is atomic anyway).
|
||||
for f in &files {
|
||||
match route(kind_of(f), target) {
|
||||
DropAction::Open => return Err(EngineError::Param(format!("{} is a document: open it with file.open", f.display()))),
|
||||
DropAction::Refuse(why) => return Err(EngineError::Param(format!("{}: {why}", f.display()))),
|
||||
DropAction::ImportToStage | DropAction::ImportToLibrary => {}
|
||||
}
|
||||
}
|
||||
let folder = match opt_u64(p, "folder")? {
|
||||
Some(f) if target == DropTarget::Library => {
|
||||
let id = FolderId(f);
|
||||
if s.doc.folder(id).is_none() {
|
||||
return Err(EngineError::State(format!("no Library folder with id {f}")));
|
||||
}
|
||||
Some(id)
|
||||
}
|
||||
Some(_) => return Err(EngineError::Param("'folder' is for drops on the Library".into())),
|
||||
None => None,
|
||||
};
|
||||
let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0);
|
||||
let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0);
|
||||
if !(x.is_finite() && y.is_finite()) || x.abs() > 1.0e6 || y.abs() > 1.0e6 {
|
||||
return Err(EngineError::Param("'x' and 'y' must be within a million pixels of the origin".into()));
|
||||
}
|
||||
let (mut elements, mut items, mut layers) = (Vec::new(), Vec::new(), 0u64);
|
||||
for f in &files {
|
||||
let path = f.display().to_string();
|
||||
if target == DropTarget::Library {
|
||||
let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?;
|
||||
let item = match (v["bitmap"].as_u64(), v["sound"].as_u64()) {
|
||||
(Some(b), _) => LibraryItem::Bitmap(anicraft_doc::BitmapId(b)),
|
||||
(None, Some(snd)) => LibraryItem::Sound(anicraft_doc::SoundId(snd)),
|
||||
_ => return Err(EngineError::State(format!("{path} added nothing to the Library"))),
|
||||
};
|
||||
if let Some(folder) = folder {
|
||||
// Into the folder under the pointer, numbered if it has an item of that name.
|
||||
let name = s.doc.item_name(item).unwrap_or("").to_string();
|
||||
let free = s.doc.unique_name(Some(folder), &name);
|
||||
s.doc.place_entry(LibraryEntry::Item(item), Some(folder));
|
||||
if free != name {
|
||||
let mut params = crate::cmds_library::entry_json(LibraryEntry::Item(item));
|
||||
params["name"] = json!(free);
|
||||
crate::cmds_library::rename(s, ¶ms)?;
|
||||
}
|
||||
}
|
||||
items.push(crate::cmds_library::entry_json(LibraryEntry::Item(item)));
|
||||
continue;
|
||||
}
|
||||
match kind_of(f) {
|
||||
DropKind::Drawing => {
|
||||
// A drawing's own shapes, on the active layer (or its own layers when it has
|
||||
// several or masks), centred on the drop point.
|
||||
let v = crate::cmds_file::import_to_stage(s, &json!({"path": path, "cx": x, "cy": y, "layer": "active"}))?;
|
||||
layers += v["layers"].as_u64().unwrap_or(0);
|
||||
elements.extend(s.selection.ids());
|
||||
}
|
||||
_ => {
|
||||
// An image or a sound: into the Library, then placed as Place on Stage does.
|
||||
let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?;
|
||||
let item = match (v["bitmap"].as_u64(), v["sound"].as_u64()) {
|
||||
(Some(b), _) => json!({"bitmap": b}),
|
||||
(None, Some(snd)) => json!({"sound": snd}),
|
||||
_ => return Err(EngineError::State(format!("{path} added nothing to the Library"))),
|
||||
};
|
||||
items.push(item.clone());
|
||||
let mut place = item;
|
||||
place["x"] = json!(x);
|
||||
place["y"] = json!(y);
|
||||
let placed = crate::cmds_draw::place(s, &place)?;
|
||||
if let Some(list) = placed["elements"].as_array() {
|
||||
elements.extend(list.iter().filter_map(Value::as_u64).map(anicraft_doc::ElementId));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !elements.is_empty() {
|
||||
s.select_only(elements.iter().copied());
|
||||
}
|
||||
Ok(json!({"elements": elements.iter().map(|e| e.0).collect::<Vec<_>>(), "items": items, "layers": layers, "files": files.len()}))
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
label: "Import to Stage…",
|
||||
menu: "File/Import",
|
||||
shortcut: Some("Ctrl+R"),
|
||||
params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred)}",
|
||||
params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead)}",
|
||||
mutates: true,
|
||||
run: import_to_stage,
|
||||
},
|
||||
@@ -149,7 +149,7 @@ pub fn is_animate(path: &std::path::Path) -> bool {
|
||||
matches!(ext.as_deref(), Some("fla" | "xfl")) || (crate::vfs::is_dir(path) && crate::vfs::is_file(&path.join("DOMDocument.xml")))
|
||||
}
|
||||
|
||||
fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
let unsaved = opt_bool(p, "unsaved")?.unwrap_or(false);
|
||||
let untitled = opt_bool(p, "untitled")?.unwrap_or(false);
|
||||
@@ -173,6 +173,8 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// as it was in Animate (ADR 0042).
|
||||
let merged = crate::merge::merge_document(&mut doc);
|
||||
s.replace_document(doc, None);
|
||||
// Open Recent reopens the Animate file (ADR 0059).
|
||||
s.recent.add(&path);
|
||||
let mut info = s.info();
|
||||
info["imported"] = json!(path.display().to_string());
|
||||
info["report"] = json!(report.summary());
|
||||
@@ -184,9 +186,11 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(info);
|
||||
}
|
||||
let doc = format::load(&path)?;
|
||||
s.replace_document(doc, (!untitled).then_some(path));
|
||||
s.replace_document(doc, (!untitled).then(|| path.clone()));
|
||||
if unsaved {
|
||||
s.mark_unsaved();
|
||||
} else if !untitled {
|
||||
s.recent.add(&path);
|
||||
}
|
||||
Ok(s.info())
|
||||
}
|
||||
@@ -199,6 +203,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
format::save(&s.doc, &path)?;
|
||||
s.path = Some(path.clone());
|
||||
s.mark_saved();
|
||||
s.recent.add(&path);
|
||||
Ok(json!({"saved": path.display().to_string()}))
|
||||
}
|
||||
|
||||
@@ -233,7 +238,7 @@ const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024;
|
||||
/// named after the file, in a keyframe at the playhead, selected, as one undo step. A drawing
|
||||
/// with clip paths or masks becomes a folder named after the file, with mask layers over the
|
||||
/// artwork they clip (ADR 0021). Centred on the stage unless `x`/`y` give its top-left corner.
|
||||
fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
if crate::cmds_sound::is_sound(&path) {
|
||||
return crate::cmds_sound::import_to_stage(s, &path);
|
||||
@@ -257,8 +262,20 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary())));
|
||||
}
|
||||
let stage = s.doc.stage;
|
||||
let x = opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5);
|
||||
let y = opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5);
|
||||
// `cx`/`cy` centre it on a point (a drop, ADR 0059); `x`/`y` give its top-left corner.
|
||||
let x = match opt_f32(p, "cx")? {
|
||||
Some(cx) => cx - drawing.width * 0.5,
|
||||
None => opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5),
|
||||
};
|
||||
let y = match opt_f32(p, "cy")? {
|
||||
Some(cy) => cy - drawing.height * 0.5,
|
||||
None => opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5),
|
||||
};
|
||||
let onto_active = match opt_str(p, "layer")? {
|
||||
None | Some("new") => false,
|
||||
Some("active") => true,
|
||||
Some(other) => return Err(EngineError::Param(format!("param 'layer' must be new or active, not '{other}'"))),
|
||||
};
|
||||
if !(x.is_finite() && y.is_finite()) {
|
||||
return Err(EngineError::Param("'x' and 'y' must be numbers".into()));
|
||||
}
|
||||
@@ -285,7 +302,13 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let masks = drawing.layers.iter().filter(|l| l.mask.is_some()).count();
|
||||
let (width, height, report) = (drawing.width, drawing.height, drawing.report);
|
||||
let mut layers = drawing.layers;
|
||||
let (layer_id, ids, made, folder) = if layers.len() == 1 && masks == 0 {
|
||||
let (layer_id, ids, made, folder) = if onto_active && layers.len() == 1 && masks == 0 {
|
||||
// Onto the active layer's keyframe at the playhead, as a drop on the stage puts it.
|
||||
let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default());
|
||||
let ids: Vec<anicraft_doc::ElementId> = els.iter().map(|e| e.id).collect();
|
||||
s.editable_keyframe()?.elements.extend(els);
|
||||
(s.layer, ids, 0, None)
|
||||
} else if layers.len() == 1 && masks == 0 {
|
||||
// One layer, named after the file, as Import to Stage always made.
|
||||
crate::cmds_timeline::new_layer(s, &json!({"name": name}))?;
|
||||
let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default());
|
||||
|
||||
@@ -182,7 +182,7 @@ fn new_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"folder": id.0, "name": name}))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let e = entry_of(p)?;
|
||||
if !s.doc.has_entry(e) {
|
||||
return Err(EngineError::State(format!("the Library has no {}", describe(e))));
|
||||
|
||||
@@ -39,6 +39,7 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> {
|
||||
}
|
||||
_ => match id.split('.').next().unwrap_or("") {
|
||||
"file" => Err("plug-ins can't open, save, import or export files"),
|
||||
"prefs" => Err("plug-ins can't read or change your preferences"),
|
||||
"plugin" => Err("plug-ins can't install, run or remove plug-ins"),
|
||||
"control" => Err("plug-ins can't play the movie"),
|
||||
ns if DOCUMENT.contains(&ns) => Ok(()),
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Recent files (ADR 0059): the documents opened or saved last, most recent first, with pinned
|
||||
//! favourites kept above them. The list belongs to the session (it survives New and Open) and
|
||||
//! is plain data: the desktop app keeps it in its preferences and puts it back at start, so the
|
||||
//! engine never reads or writes the settings folder. `file.open` and `file.save` add to it;
|
||||
//! these commands open, pin, remove and clear entries for menus, the CLI and MCP alike.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Most recent (unpinned) files kept, as Animate's Open Recent shows.
|
||||
pub const MAX_RECENT: usize = 10;
|
||||
/// Most pinned favourites.
|
||||
pub const MAX_PINNED: usize = 10;
|
||||
/// Longest path kept (anything longer is not a path a user picked).
|
||||
const MAX_PATH_BYTES: usize = 4096;
|
||||
|
||||
/// One file in the list.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct RecentFile {
|
||||
pub path: PathBuf,
|
||||
/// A favourite: it stays at the top, and adding or clearing recent files leaves it alone.
|
||||
pub pinned: bool,
|
||||
}
|
||||
|
||||
/// Pinned favourites first (in the order they were pinned), then the recent files, most recent
|
||||
/// first. At most [`MAX_PINNED`] + [`MAX_RECENT`] entries, never the same file twice.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct RecentFiles {
|
||||
entries: Vec<RecentFile>,
|
||||
}
|
||||
|
||||
/// Whether two paths name the same file as the user sees it: Windows and macOS file names
|
||||
/// ignore case (by default), and Windows takes either slash.
|
||||
pub fn same_file(a: &Path, b: &Path) -> bool {
|
||||
if cfg!(any(windows, target_os = "macos")) {
|
||||
let norm = |p: &Path| p.to_string_lossy().replace('\\', "/").to_lowercase();
|
||||
norm(a) == norm(b)
|
||||
} else {
|
||||
a == b
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a recent file is still there to open (a file, or an XFL folder).
|
||||
pub fn exists(path: &Path) -> bool {
|
||||
crate::vfs::is_file(path) || crate::vfs::is_dir(path)
|
||||
}
|
||||
|
||||
/// A short, stable key for a path (64-bit FNV-1a of its normalised text, as hex): the name its
|
||||
/// thumbnail is kept under.
|
||||
pub fn thumb_key(path: &Path) -> String {
|
||||
let text = if cfg!(any(windows, target_os = "macos")) { path.to_string_lossy().replace('\\', "/").to_lowercase() } else { path.to_string_lossy().into_owned() };
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in text.bytes() {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
format!("{h:016x}")
|
||||
}
|
||||
|
||||
/// Largest edge of a recent file's thumbnail, in pixels.
|
||||
pub const THUMB_W: u32 = 240;
|
||||
pub const THUMB_H: u32 = 135;
|
||||
|
||||
/// The document's first frame as a small PNG that fits [`THUMB_W`] × [`THUMB_H`] (the start
|
||||
/// screen's picture of a recent file), rendered by the CPU oracle.
|
||||
pub fn thumbnail_png(doc: &anicraft_doc::Document) -> Result<Vec<u8>> {
|
||||
let (w, h) = (doc.stage.width.max(1) as f32, doc.stage.height.max(1) as f32);
|
||||
let scale = (THUMB_W as f32 / w).min(THUMB_H as f32 / h).min(1.0);
|
||||
crate::cmds_file::render_png(doc, 0, scale)
|
||||
}
|
||||
|
||||
impl RecentFiles {
|
||||
pub fn entries(&self) -> &[RecentFile] {
|
||||
&self.entries
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
fn position(&self, path: &Path) -> Option<usize> {
|
||||
self.entries.iter().position(|e| same_file(&e.path, path))
|
||||
}
|
||||
|
||||
fn pinned_count(&self) -> usize {
|
||||
self.entries.iter().take_while(|e| e.pinned).count()
|
||||
}
|
||||
|
||||
/// A file was opened or saved: it becomes the most recent. A pinned file keeps its place;
|
||||
/// the oldest recent file beyond [`MAX_RECENT`] drops off. Returns whether the list changed.
|
||||
pub fn add(&mut self, path: &Path) -> bool {
|
||||
if path.as_os_str().is_empty() || path.as_os_str().len() > MAX_PATH_BYTES {
|
||||
return false;
|
||||
}
|
||||
let before = self.entries.clone();
|
||||
if let Some(i) = self.position(path) {
|
||||
if self.entries.get(i).is_some_and(|e| e.pinned) {
|
||||
return false;
|
||||
}
|
||||
self.entries.remove(i);
|
||||
}
|
||||
let at = self.pinned_count();
|
||||
self.entries.insert(at, RecentFile { path: path.to_path_buf(), pinned: false });
|
||||
self.entries.truncate(at + MAX_RECENT);
|
||||
before != self.entries
|
||||
}
|
||||
|
||||
/// Takes a file off the list (pinned or not). Returns whether it was there.
|
||||
pub fn remove(&mut self, path: &Path) -> bool {
|
||||
match self.position(path) {
|
||||
Some(i) => {
|
||||
self.entries.remove(i);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins a file (it goes below the other pinned files) or unpins it (it becomes the most
|
||||
/// recent file). A file not on the list is added pinned.
|
||||
pub fn pin(&mut self, path: &Path, pinned: bool) -> std::result::Result<(), String> {
|
||||
let current = self.position(path).and_then(|i| self.entries.get(i)).map(|e| e.pinned);
|
||||
if current == Some(pinned) {
|
||||
return Ok(());
|
||||
}
|
||||
if pinned && self.pinned_count() >= MAX_PINNED {
|
||||
return Err(format!("at most {MAX_PINNED} files can be pinned; unpin one first"));
|
||||
}
|
||||
if path.as_os_str().is_empty() || path.as_os_str().len() > MAX_PATH_BYTES {
|
||||
return Err("that is not a file path".into());
|
||||
}
|
||||
self.remove(path);
|
||||
let at = self.pinned_count();
|
||||
self.entries.insert(at, RecentFile { path: path.to_path_buf(), pinned });
|
||||
let pins = self.pinned_count();
|
||||
self.entries.truncate(pins + MAX_RECENT);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clears the recent files; pinned favourites stay unless `pinned` too. Returns how many
|
||||
/// were taken off.
|
||||
pub fn clear(&mut self, pinned: bool) -> usize {
|
||||
let before = self.entries.len();
|
||||
self.entries.retain(|e| e.pinned && !pinned);
|
||||
before - self.entries.len()
|
||||
}
|
||||
|
||||
/// The list as read from a preferences file that anyone may have edited: empty and overlong
|
||||
/// paths and repeats dropped, pinned files first, each part within its limit.
|
||||
pub fn sanitized(self) -> RecentFiles {
|
||||
let mut out = RecentFiles::default();
|
||||
let (pins, recents): (Vec<RecentFile>, Vec<RecentFile>) = self.entries.into_iter().partition(|e| e.pinned);
|
||||
for e in pins.into_iter().chain(recents) {
|
||||
let bad = e.path.as_os_str().is_empty() || e.path.as_os_str().len() > MAX_PATH_BYTES;
|
||||
if bad || out.position(&e.path).is_some() {
|
||||
continue;
|
||||
}
|
||||
let pins = out.pinned_count();
|
||||
if (e.pinned && pins >= MAX_PINNED) || (!e.pinned && out.entries.len() - pins >= MAX_RECENT) {
|
||||
continue;
|
||||
}
|
||||
out.entries.push(e);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec {
|
||||
id: "file.open_recent",
|
||||
label: "Open Recent",
|
||||
// The File menu shows the files themselves (a submenu the shell draws).
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{index? (in file.recent_list order, from 0) | path?, confirm? (needed over unsaved changes)}: opens it as file.open does; a file that is no longer there stays on the list, marked missing",
|
||||
mutates: false,
|
||||
run: open_recent,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "file.recent_list",
|
||||
label: "Recent Files",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{} → {files: [{index, path, name, pinned, missing, thumb}]}: pinned favourites first, then the last 10 files opened or saved, most recent first (`thumb` names the start screen's picture)",
|
||||
mutates: false,
|
||||
run: list,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "prefs.recent_pin",
|
||||
label: "Pin to Recent Files",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{index? | path?, pinned? (default: toggle)}: a pinned file stays at the top of Open Recent",
|
||||
mutates: false,
|
||||
run: pin,
|
||||
},
|
||||
CommandSpec { id: "prefs.recent_remove", label: "Remove from Recent Files", menu: "", shortcut: None, params: "{index? | path?}", mutates: false, run: remove },
|
||||
CommandSpec {
|
||||
id: "prefs.recent_clear",
|
||||
label: "Clear Recent Files",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{pinned? (default false: pinned favourites stay)} → {removed}",
|
||||
mutates: false,
|
||||
run: clear,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// The entry `index` or `path` names.
|
||||
fn which(s: &Session, p: &Value) -> Result<PathBuf> {
|
||||
match (opt_u64(p, "index")?, opt_str(p, "path")?) {
|
||||
(Some(i), None) => usize::try_from(i).ok().and_then(|i| s.recent.entries().get(i)).map(|e| e.path.clone()).ok_or_else(|| EngineError::Param(format!("no recent file {i}; file.recent_list has {}", s.recent.len()))),
|
||||
(None, Some(path)) if !path.trim().is_empty() => Ok(PathBuf::from(path)),
|
||||
(None, Some(_)) => Err(EngineError::Param("param 'path' must name a file".into())),
|
||||
_ => Err(EngineError::Param("name the file with 'index' or 'path' (one of them)".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_recent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = which(s, p)?;
|
||||
if !exists(&path) {
|
||||
return Err(EngineError::State(format!("{} is no longer there (moved, renamed or deleted); remove it from Open Recent", path.display())));
|
||||
}
|
||||
crate::cmds_file::open(s, &json!({"path": path.display().to_string()}))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let files: Vec<Value> = s
|
||||
.recent
|
||||
.entries()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, e)| {
|
||||
let name = e.path.file_name().map_or_else(|| e.path.display().to_string(), |n| n.to_string_lossy().into_owned());
|
||||
json!({"index": i, "path": e.path.display().to_string(), "name": name, "pinned": e.pinned, "missing": !exists(&e.path), "thumb": thumb_key(&e.path)})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"files": files}))
|
||||
}
|
||||
|
||||
fn pin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = which(s, p)?;
|
||||
let now = s.recent.entries().iter().find(|e| same_file(&e.path, &path)).is_some_and(|e| e.pinned);
|
||||
let pinned = opt_bool(p, "pinned")?.unwrap_or(!now);
|
||||
s.recent.pin(&path, pinned).map_err(EngineError::State)?;
|
||||
Ok(json!({"path": path.display().to_string(), "pinned": pinned}))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = which(s, p)?;
|
||||
if !s.recent.remove(&path) {
|
||||
return Err(EngineError::State(format!("{} is not in the recent files", path.display())));
|
||||
}
|
||||
Ok(json!({"removed": path.display().to_string()}))
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pinned = opt_bool(p, "pinned")?.unwrap_or(false);
|
||||
Ok(json!({"removed": s.recent.clear(pinned)}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn paths(r: &RecentFiles) -> Vec<String> {
|
||||
r.entries().iter().map(|e| format!("{}{}", if e.pinned { "*" } else { "" }, e.path.display())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn most_recent_first_ten_at_most_never_twice() {
|
||||
let mut r = RecentFiles::default();
|
||||
for i in 0..14 {
|
||||
assert!(r.add(Path::new(&format!("f{i}.anicraft"))));
|
||||
}
|
||||
assert_eq!(r.len(), MAX_RECENT);
|
||||
assert_eq!(paths(&r).first().map(String::as_str), Some("f13.anicraft"));
|
||||
assert_eq!(paths(&r).last().map(String::as_str), Some("f4.anicraft"), "the oldest drop off");
|
||||
// Opening one again moves it to the top, without a second entry.
|
||||
assert!(r.add(Path::new("f8.anicraft")));
|
||||
assert_eq!(paths(&r)[..2], ["f8.anicraft", "f13.anicraft"]);
|
||||
assert_eq!(r.len(), MAX_RECENT);
|
||||
assert!(!r.add(Path::new("f8.anicraft")), "already the most recent");
|
||||
assert!(!r.add(Path::new("")), "no empty paths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_files_stay_on_top_and_survive_clearing() {
|
||||
let mut r = RecentFiles::default();
|
||||
for f in ["a", "b", "c"] {
|
||||
r.add(Path::new(f));
|
||||
}
|
||||
r.pin(Path::new("a"), true).unwrap();
|
||||
assert_eq!(paths(&r), ["*a", "c", "b"]);
|
||||
// New files go below the pins; opening a pinned file leaves it where it is.
|
||||
r.add(Path::new("d"));
|
||||
assert!(!r.add(Path::new("a")));
|
||||
assert_eq!(paths(&r), ["*a", "d", "c", "b"]);
|
||||
// Pins don't count towards the ten recent files.
|
||||
for i in 0..12 {
|
||||
r.add(Path::new(&format!("n{i}")));
|
||||
}
|
||||
assert_eq!(r.len(), 1 + MAX_RECENT);
|
||||
assert_eq!(r.clear(false), MAX_RECENT);
|
||||
assert_eq!(paths(&r), ["*a"]);
|
||||
// Unpinning makes it the most recent file.
|
||||
r.add(Path::new("z"));
|
||||
r.pin(Path::new("a"), false).unwrap();
|
||||
assert_eq!(paths(&r), ["a", "z"]);
|
||||
assert!(r.remove(Path::new("z")));
|
||||
assert!(!r.remove(Path::new("z")));
|
||||
assert_eq!(r.clear(true), 1);
|
||||
assert!(r.is_empty());
|
||||
for i in 0..MAX_PINNED {
|
||||
r.pin(Path::new(&format!("p{i}")), true).unwrap();
|
||||
}
|
||||
assert!(r.pin(Path::new("one too many"), true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hand_edited_list_is_cleaned_up() {
|
||||
let raw = r#"[{"path": "b"}, {"path": "", "pinned": true}, {"path": "a", "pinned": true}, {"path": "b"}, {"nonsense": 1}]"#;
|
||||
let r: RecentFiles = serde_json::from_str::<RecentFiles>(raw).unwrap().sanitized();
|
||||
assert_eq!(paths(&r), ["*a", "b"]);
|
||||
let many: Vec<RecentFile> = (0..40).map(|i| RecentFile { path: PathBuf::from(format!("{i}")), pinned: i % 2 == 0 }).collect();
|
||||
let r = RecentFiles { entries: many }.sanitized();
|
||||
assert_eq!(r.entries().iter().filter(|e| e.pinned).count(), MAX_PINNED);
|
||||
assert_eq!(r.entries().iter().filter(|e| !e.pinned).count(), MAX_RECENT);
|
||||
assert!(r.entries().iter().take(MAX_PINNED).all(|e| e.pinned), "pins first");
|
||||
assert!(RecentFiles { entries: vec![RecentFile { path: PathBuf::from("x".repeat(5000)), pinned: false }] }.sanitized().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thumbnail_keys_are_stable_and_distinct() {
|
||||
assert_eq!(thumb_key(Path::new("a/b.anicraft")), thumb_key(Path::new("a/b.anicraft")));
|
||||
assert_ne!(thumb_key(Path::new("a/b.anicraft")), thumb_key(Path::new("a/c.anicraft")));
|
||||
assert_eq!(thumb_key(Path::new("x")).len(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thumbnails_fit_the_start_screen() {
|
||||
let t = std::time::Instant::now();
|
||||
let png = thumbnail_png(&anicraft_doc::sample::demo()).unwrap();
|
||||
eprintln!("thumbnail of the sample: {:.2} ms, {} bytes", t.elapsed().as_secs_f64() * 1000.0, png.len());
|
||||
let img = image_size(&png);
|
||||
assert!(img.0 <= THUMB_W && img.1 <= THUMB_H && img.0 > 0 && img.1 > 0, "{img:?}");
|
||||
}
|
||||
|
||||
/// Width and height from a PNG's header.
|
||||
fn image_size(png: &[u8]) -> (u32, u32) {
|
||||
let be = |i: usize| u32::from_be_bytes([png[i], png[i + 1], png[i + 2], png[i + 3]]);
|
||||
(be(16), be(20))
|
||||
}
|
||||
}
|
||||
@@ -99,7 +99,7 @@ fn sound_json(s: &Sound) -> Value {
|
||||
}
|
||||
|
||||
/// Import to Library: a sound (or an image) goes into the library without being placed.
|
||||
fn import_to_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
if is_sound(&path) {
|
||||
let id = add_sound(s, &path, opt_str(p, "name")?)?;
|
||||
|
||||
@@ -98,7 +98,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
irreversible: true,
|
||||
})
|
||||
}
|
||||
"file.new" | "file.new_sample" | "file.open" | "file.recover" if s.is_dirty() => Some(Confirmation {
|
||||
"file.new" | "file.new_sample" | "file.open" | "file.open_recent" | "file.recover" if s.is_dirty() => Some(Confirmation {
|
||||
title: "Discard unsaved changes?".into(),
|
||||
message: format!("“{}” has changes that are not saved. They will be lost, and its undo history is cleared.", doc_name(s)),
|
||||
action: "Discard Changes".into(),
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Files dropped onto the window and recent files (ADR 0059): routing by type and target, what
|
||||
//! `file.drop` brings in and where, one undo step, and the recent list that opening and saving
|
||||
//! keep.
|
||||
|
||||
use super::*;
|
||||
use crate::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route};
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-drop-{tag}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A 4 × 2 PNG, a one-rectangle SVG and a short WAV in `dir`.
|
||||
fn media(dir: &Path) -> (String, String, String) {
|
||||
let png = dir.join("photo.png");
|
||||
std::fs::write(&png, anicraft_render::encode_png(4, 2, &[255u8; 4 * 2 * 4]).unwrap()).unwrap();
|
||||
let svg = dir.join("badge.svg");
|
||||
std::fs::write(&svg, r##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="40" height="20" fill="#f00"/></svg>"##).unwrap();
|
||||
let wav = dir.join("beep.wav");
|
||||
std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &[0.25; 4000])).unwrap();
|
||||
(png.display().to_string(), svg.display().to_string(), wav.display().to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_route_by_file_type_and_target() {
|
||||
use DropAction::*;
|
||||
use DropTarget::*;
|
||||
let k = |p: &str| kind_of(Path::new(p));
|
||||
assert_eq!(k("a.anicraft"), DropKind::Document);
|
||||
assert_eq!(k("A.FLA"), DropKind::Document);
|
||||
assert_eq!(k("b.xfl"), DropKind::Document);
|
||||
assert_eq!(k("c.svg"), DropKind::Drawing);
|
||||
assert_eq!(k("d.JPEG"), DropKind::Image);
|
||||
assert_eq!(k("d.jpg"), DropKind::Image);
|
||||
assert_eq!(k("e.png"), DropKind::Image);
|
||||
assert_eq!(k("f.mp3"), DropKind::Sound);
|
||||
assert_eq!(k("g.ogg"), DropKind::Sound);
|
||||
assert_eq!(k("h.wav"), DropKind::Sound);
|
||||
assert_eq!(k("i.psd"), DropKind::Unsupported);
|
||||
assert_eq!(k("no extension"), DropKind::Unsupported);
|
||||
// An XFL package is a folder with a DOMDocument.xml.
|
||||
let dir = temp_dir("xfl").join("Movie");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
assert_eq!(kind_of(&dir), DropKind::Unsupported, "a plain folder");
|
||||
std::fs::write(dir.join("DOMDocument.xml"), "<DOMDocument/>").unwrap();
|
||||
assert_eq!(kind_of(&dir), DropKind::Document);
|
||||
// Documents open wherever they land; media go where they are dropped.
|
||||
for t in [Stage, Library, Window] {
|
||||
assert_eq!(route(DropKind::Document, t), Open);
|
||||
assert!(matches!(route(DropKind::Unsupported, t), Refuse(_)));
|
||||
}
|
||||
for kind in [DropKind::Drawing, DropKind::Image, DropKind::Sound] {
|
||||
assert_eq!(route(kind, Stage), ImportToStage);
|
||||
assert!(matches!(route(kind, Window), Refuse(_)), "only the stage and the Library take media");
|
||||
}
|
||||
assert_eq!(route(DropKind::Image, Library), ImportToLibrary);
|
||||
assert_eq!(route(DropKind::Sound, Library), ImportToLibrary);
|
||||
assert!(matches!(route(DropKind::Drawing, Library), Refuse(m) if m.contains("stage")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_dropped_on_the_stage_land_on_the_active_layer_at_the_drop_point_in_one_step() {
|
||||
let dir = temp_dir("stage");
|
||||
let (png, svg, wav) = media(&dir);
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "timeline.insert_frame", json!({"count": 20}));
|
||||
s.set_frame(5);
|
||||
let layers = s.timeline().layers.len();
|
||||
let history = s.history_len();
|
||||
let v = run(&mut s, "file.drop", json!({"paths": [png, svg, wav], "to": "stage", "x": 100, "y": 60}));
|
||||
assert_eq!(s.history_len(), history + 1, "one undo step for the whole drop");
|
||||
assert_eq!(s.timeline().layers.len(), layers, "everything went onto the active layer");
|
||||
assert_eq!(v["elements"].as_array().map(Vec::len), Some(2), "{v}");
|
||||
assert_eq!(s.selection.len(), 2, "what was dropped is selected");
|
||||
// Centred on the drop point, in the keyframe that shows at the playhead.
|
||||
let layer = s.active_layer().unwrap();
|
||||
let key = layer.keyframe_at(5).unwrap();
|
||||
assert!(s.selection.ids().all(|id| key.elements.iter().any(|e| e.id == id)));
|
||||
for id in s.selection.ids().collect::<Vec<_>>() {
|
||||
let b = s.element_bounds(id);
|
||||
assert!((b.center().x - 100.0).abs() < 0.01 && (b.center().y - 60.0).abs() < 0.01, "{b:?}");
|
||||
}
|
||||
assert!(key.sound.is_some(), "the sound is on the keyframe at the playhead");
|
||||
assert_eq!((s.doc.bitmaps.len(), s.doc.sounds.len()), (1, 1), "the image and the sound are in the Library");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(s.doc.bitmaps.is_empty() && s.doc.sounds.is_empty() && s.active_layer().unwrap().keyframe_at(5).is_none_or(|k| k.elements.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_dropped_on_the_library_go_into_the_folder_under_the_pointer() {
|
||||
let dir = temp_dir("library");
|
||||
let (png, svg, wav) = media(&dir);
|
||||
let mut s = Session::default();
|
||||
let folder = run(&mut s, "library.new_folder", json!({"name": "Props"}))["folder"].as_u64().unwrap();
|
||||
let history = s.history_len();
|
||||
let v = run(&mut s, "file.drop", json!({"paths": [png.clone(), wav], "to": "library", "folder": folder}));
|
||||
assert_eq!(s.history_len(), history + 1);
|
||||
assert_eq!(v["items"].as_array().map(Vec::len), Some(2));
|
||||
let in_folder = s.doc.folder_contents(anicraft_doc::FolderId(folder));
|
||||
assert_eq!(in_folder.len(), 2, "{in_folder:?}");
|
||||
assert!(s.timeline().layers.iter().all(|l| l.keyframes.iter().all(|k| k.elements.is_empty() && k.sound.is_none())), "nothing placed on the stage");
|
||||
// The same image again: numbered, not refused.
|
||||
run(&mut s, "file.drop", json!({"path": png.clone(), "to": "library", "folder": folder}));
|
||||
let names: Vec<String> = s.doc.folder_contents(anicraft_doc::FolderId(folder)).into_iter().filter_map(|e| s.doc.entry_name(e).map(str::to_string)).collect();
|
||||
assert!(names.contains(&"photo.png".to_string()) && names.contains(&"photo.png 2".to_string()), "{names:?}");
|
||||
// At the top level without a folder.
|
||||
run(&mut s, "file.drop", json!({"path": png, "to": "library"}));
|
||||
assert_eq!(s.doc.bitmaps.len(), 3);
|
||||
// A drawing can't go into the Library; nothing is imported when one file is refused.
|
||||
let before = s.doc.clone();
|
||||
assert!(s.execute("file.drop", &json!({"paths": [svg], "to": "library"})).is_err());
|
||||
assert!(s.doc == before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawings_with_layers_keep_them_and_bad_drops_change_nothing() {
|
||||
let dir = temp_dir("bad");
|
||||
let (png, _, _) = media(&dir);
|
||||
let masked = dir.join("masked.svg");
|
||||
std::fs::write(&masked, r##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><clipPath id="c"><circle cx="20" cy="20" r="10"/></clipPath><rect width="40" height="40" fill="#0f0" clip-path="url(#c)"/></svg>"##).unwrap();
|
||||
let mut s = Session::default();
|
||||
let layers = s.timeline().layers.len();
|
||||
run(&mut s, "file.drop", json!({"path": masked.display().to_string(), "to": "stage", "x": 10, "y": 10}));
|
||||
assert!(s.timeline().layers.len() > layers + 1, "a masked drawing brings its folder and mask layer");
|
||||
let before = s.doc.clone();
|
||||
let doc = dir.join("x.anicraft");
|
||||
for p in [
|
||||
json!({"path": doc.display().to_string(), "to": "stage"}),
|
||||
json!({"path": dir.join("y.psd").display().to_string(), "to": "stage"}),
|
||||
json!({"paths": [png.clone(), dir.join("gone.png").display().to_string()], "to": "stage"}),
|
||||
json!({"path": png.clone(), "to": "timeline"}),
|
||||
json!({"path": png.clone(), "to": "library", "folder": u64::MAX}),
|
||||
json!({"path": png.clone(), "to": "stage", "folder": 1}),
|
||||
json!({"path": png.clone(), "to": "stage", "x": f64::MAX, "y": 0}),
|
||||
json!({"paths": [], "to": "stage"}),
|
||||
json!({"paths": vec![png.clone(); 65], "to": "stage"}),
|
||||
json!({"paths": "x", "to": "stage"}),
|
||||
json!({"paths": [1, 2], "to": "library"}),
|
||||
json!({"to": "stage"}),
|
||||
json!({}),
|
||||
Value::Null,
|
||||
] {
|
||||
assert!(s.execute("file.drop", &p).is_err(), "{p}");
|
||||
assert!(s.doc == before, "{p} changed the document");
|
||||
}
|
||||
// A locked layer refuses the drop and says why.
|
||||
let top = s.timeline().layers.len() - 1;
|
||||
run(&mut s, "layer.select", json!({"index": top}));
|
||||
run(&mut s, "layer.toggle_lock", json!({}));
|
||||
let e = s.execute("file.drop", &json!({"path": png, "to": "stage"})).unwrap_err();
|
||||
assert!(e.to_string().contains("locked"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_and_saving_keep_the_recent_list_and_open_recent_reopens() {
|
||||
let dir = temp_dir("recent");
|
||||
let a = dir.join("a.anicraft");
|
||||
let b = dir.join("b.anicraft");
|
||||
let mut s = Session::new(anicraft_doc::sample::demo());
|
||||
run(&mut s, "file.save_as", json!({"path": a.display().to_string()}));
|
||||
run(&mut s, "file.new", json!({"width": 1280, "height": 720}));
|
||||
run(&mut s, "file.save_as", json!({"path": b.display().to_string()}));
|
||||
let list = run(&mut s, "file.recent_list", json!({}));
|
||||
let names: Vec<&str> = list["files"].as_array().unwrap().iter().filter_map(|f| f["name"].as_str()).collect();
|
||||
assert_eq!(names, ["b.anicraft", "a.anicraft"], "most recent first; New doesn't clear it");
|
||||
// Open Recent by index opens it, and moves it to the top.
|
||||
run(&mut s, "file.open_recent", json!({"index": 1}));
|
||||
assert_eq!(s.path.as_deref(), Some(a.as_path()));
|
||||
assert_eq!(s.doc.stage.width, anicraft_doc::sample::demo().stage.width);
|
||||
assert_eq!(s.recent.entries().first().map(|e| e.path.clone()), Some(a.clone()));
|
||||
// Over unsaved work it asks first, like Open.
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5}));
|
||||
assert!(s.confirmation("file.open_recent", &json!({"index": 1})).is_some_and(|c| c.irreversible));
|
||||
assert!(s.execute("file.open_recent", &json!({"index": 1})).is_err());
|
||||
run(&mut s, "file.open_recent", json!({"index": 1, "confirm": true}));
|
||||
assert_eq!(s.path.as_deref(), Some(b.as_path()));
|
||||
// A file that is gone stays listed, marked missing, and says so when opened.
|
||||
std::fs::remove_file(&a).unwrap();
|
||||
let list = run(&mut s, "file.recent_list", json!({}));
|
||||
let gone = list["files"].as_array().unwrap().iter().find(|f| f["name"] == "a.anicraft").unwrap();
|
||||
assert_eq!(gone["missing"], true);
|
||||
let e = s.execute("file.open_recent", &json!({"path": a.display().to_string()})).unwrap_err();
|
||||
assert!(e.to_string().contains("no longer there"), "{e}");
|
||||
// Pin, remove, clear.
|
||||
run(&mut s, "prefs.recent_pin", json!({"path": a.display().to_string()}));
|
||||
assert!(s.recent.entries().first().is_some_and(|e| e.pinned));
|
||||
run(&mut s, "prefs.recent_clear", json!({}));
|
||||
assert_eq!(s.recent.len(), 1, "the pinned file stays");
|
||||
run(&mut s, "prefs.recent_remove", json!({"index": 0}));
|
||||
assert!(s.recent.is_empty());
|
||||
// Hostile params never panic and never change the list.
|
||||
run(&mut s, "file.open", json!({"path": b.display().to_string()}));
|
||||
let before = s.recent.clone();
|
||||
for id in ["file.open_recent", "prefs.recent_pin", "prefs.recent_remove"] {
|
||||
for p in [json!({"index": u64::MAX}), json!({"index": -1}), json!({"path": ""}), json!({"index": 0, "path": "x"}), json!({"pinned": "x"}), json!("x"), Value::Null] {
|
||||
let _ = s.execute(id, &p);
|
||||
assert_eq!(s.recent, before, "{id} {p}");
|
||||
}
|
||||
}
|
||||
// Restored autosaves and untitled opens aren't recent files.
|
||||
let mut t = Session::default();
|
||||
run(&mut t, "file.open", json!({"path": b.display().to_string(), "unsaved": true}));
|
||||
run(&mut t, "file.open", json!({"path": b.display().to_string(), "untitled": true, "confirm": true}));
|
||||
assert!(t.recent.is_empty());
|
||||
}
|
||||
@@ -10,6 +10,7 @@ mod cmds_bone;
|
||||
pub mod cmds_brush;
|
||||
mod cmds_camera;
|
||||
mod cmds_draw;
|
||||
pub mod cmds_drop;
|
||||
pub mod cmds_erase;
|
||||
mod cmds_file;
|
||||
mod cmds_frames;
|
||||
@@ -22,6 +23,7 @@ mod cmds_path;
|
||||
pub mod cmds_raw;
|
||||
pub mod cmds_rawsub;
|
||||
mod cmds_rawpoints;
|
||||
pub mod cmds_recent;
|
||||
mod cmds_recovery;
|
||||
mod cmds_script;
|
||||
pub mod cmds_plugin;
|
||||
@@ -110,6 +112,8 @@ impl CommandSpec {
|
||||
pub fn commands() -> Vec<CommandSpec> {
|
||||
let mut v = Vec::new();
|
||||
v.extend(cmds_file::specs());
|
||||
v.extend(cmds_recent::specs());
|
||||
v.extend(cmds_drop::specs());
|
||||
v.extend(cmds_recovery::specs());
|
||||
v.extend(cmds_timeline::specs());
|
||||
v.extend(cmds_camera::specs());
|
||||
@@ -304,6 +308,10 @@ pub struct Session {
|
||||
pub hit_area: Option<(anicraft_doc::Rgba, f32)>,
|
||||
/// The last picture of an open symbol in place, by its key (ADR 0045).
|
||||
picture_cache: RefCell<Option<(u64, Arc<editing::StagePicture>)>>,
|
||||
/// The files opened and saved last, and pinned favourites (ADR 0059). They belong to the
|
||||
/// session, not the document: they survive New and Open. The desktop app keeps them in its
|
||||
/// preferences.
|
||||
pub recent: cmds_recent::RecentFiles,
|
||||
}
|
||||
|
||||
/// Each piece of a marquee's cut, with the shape it was cut from.
|
||||
@@ -370,6 +378,7 @@ impl Session {
|
||||
gesture_cut: None,
|
||||
hit_area: None,
|
||||
picture_cache: RefCell::new(None),
|
||||
recent: cmds_recent::RecentFiles::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,7 +460,9 @@ impl Session {
|
||||
let budget = self.history.budget_bytes;
|
||||
let clipboard = std::mem::take(&mut self.clipboard);
|
||||
let plugins = std::mem::take(&mut self.plugins);
|
||||
let recent = std::mem::take(&mut self.recent);
|
||||
*self = Session::new(doc);
|
||||
self.recent = recent;
|
||||
// The clipboard survives New/Open, so artwork can move between documents.
|
||||
self.clipboard = clipboard;
|
||||
self.plugins = plugins;
|
||||
@@ -995,3 +1006,5 @@ mod eyedropper_tests;
|
||||
mod selection_tests;
|
||||
#[cfg(test)]
|
||||
mod scale_grid_tests;
|
||||
#[cfg(test)]
|
||||
mod drop_tests;
|
||||
@@ -169,7 +169,7 @@ fn every_command_namespace_has_a_plugin_policy() {
|
||||
let ns = c.id.split('.').next().unwrap_or("");
|
||||
let verdict = plugin_may_call(c.id);
|
||||
match ns {
|
||||
"file" | "plugin" | "control" => assert!(verdict.is_err(), "{} must be refused", c.id),
|
||||
"file" | "plugin" | "control" | "prefs" => assert!(verdict.is_err(), "{} must be refused", c.id),
|
||||
_ => assert!(verdict.is_ok() || matches!(c.id, "edit.undo" | "edit.redo") || c.id.contains("copy") || c.id.contains("cut") || c.id.contains("paste"), "{} has no plug-in policy (add its namespace to plugin_may_call)", c.id),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# ADR 0059: Files from the desktop, recent files and a start screen
|
||||
|
||||
* Status: accepted (2026-11-11)
|
||||
* Relates to: ADR 0004 (destructive actions), ADR 0006 (platform layer), ADR 0022
|
||||
(accessibility), ADR 0036 (web build), ADR 0040 (interface languages), ADR 0050 and 0053
|
||||
(Library folders, Place on Stage), roadmap M8
|
||||
|
||||
## Context
|
||||
|
||||
Files came in only through File › Open and the Import dialogs. Artists coming from Animate expect
|
||||
the everyday paths: drop a file on the window, reopen something from File › Open Recent, and a Home
|
||||
screen when the app starts with nothing open. All three touch the shell, the platform layer and the
|
||||
engine, and two of them keep state (the recent list, its pictures) between sessions.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Routing is a pure function in the engine** (`cmds_drop::kind_of`, `cmds_drop::route`). A file's
|
||||
kind comes from its name (an XFL folder from its `DOMDocument.xml`): document (`.anicraft`, `.fla`,
|
||||
`.xfl`), drawing (SVG), image (PNG, JPEG), sound (WAV, Ogg, MP3) or unsupported. With the target
|
||||
(stage, Library, elsewhere) it gives one action: open, import to the stage, import to the Library,
|
||||
or refuse with a reason. The shell's `drop::plan` adds what only the window knows: one document
|
||||
opens at a time (the others in the drop are left out, and the status line says so), and over the
|
||||
start screen nothing imports.
|
||||
2. **`file.drop` does the import, one undo step** (`{paths, to: stage | library, x, y, folder}`).
|
||||
On the stage each image and sound goes into the Library and is placed as `library.place` places
|
||||
it: centred on the drop point in the active layer's keyframe at the playhead (sounds onto that
|
||||
keyframe). A one-layer SVG goes into the same keyframe (`file.import`'s new `layer: "active"` and
|
||||
`cx`/`cy`); a drawing with several layers or masks keeps its own layers, as Import to Stage gives
|
||||
it. On the Library, images and sounds go into the folder under the pointer, numbered when the
|
||||
folder already has that name. Every file is checked before anything is imported; a locked layer
|
||||
refuses the whole drop. Documents go through `file.open` with the unsaved-changes guard
|
||||
(`request`), never through `file.drop`.
|
||||
3. **Where a drop lands needs the pointer, which the desktop doesn't give during a drag.** winit
|
||||
0.30 reports dragged files without a position, and Windows and macOS send no pointer moves while
|
||||
a drag is over the window. So a dropped file waits up to 0.35 s for the pointer's first move
|
||||
(the system sends one as the drag ends) and is routed there; without one, media land on the stage
|
||||
in the middle of the view and the status line says so. In a browser our own `dragover` listener
|
||||
on the canvas keeps the position, so the target is exact and the highlight follows the pointer;
|
||||
the browser then reads the bytes into the in-memory store (`vfs`) and the same `file.drop` runs.
|
||||
The highlight shows the target when the position is known (the stage outlined with a crosshair
|
||||
and "Place … on <layer> at frame N", the Library folder row or panel with "Add … to <folder>",
|
||||
the whole window for a document); when it isn't, it says what each place does. winit 0.31's drag
|
||||
events carry a position: moving to it makes the desktop exact too.
|
||||
4. **The recent list is the session's, persisted by the shell.** `cmds_recent::RecentFiles` lives on
|
||||
`Session` (it survives New and Open, like plug-ins): pinned favourites first (at most 10), then
|
||||
the last 10 files opened or saved, most recent first, never twice (paths compared without case
|
||||
on Windows and macOS). `file.open` and `file.save` add to it (not restored autosaves or untitled
|
||||
opens); `file.open_recent`, `file.recent_list`, `prefs.recent_pin`, `prefs.recent_remove` and
|
||||
`prefs.recent_clear` (pinned files stay unless `pinned: true`) work in the CLI and MCP like any
|
||||
command. The window copies the list into `Prefs::recent` whenever it changes and puts it back at
|
||||
start; the engine never reads the settings folder. Preferences parse the list leniently (a bad
|
||||
entry is skipped, not every preference reset) and sanitise it. A missing file stays listed, greyed
|
||||
out with Remove, because a disconnected drive comes back; `file.open_recent` on it says it is no
|
||||
longer there. `prefs` is a new namespace: plug-ins may not call it.
|
||||
5. **Thumbnails are captured on save** (and on open when none exists): the CPU oracle renders the
|
||||
first frame to fit 240 × 135 (`cmds_recent::thumbnail_png`, about 1.2 ms and 6 KB for the sample
|
||||
in a release build), kept as `Thumbnails/<key>.png` in the settings folder (browser storage,
|
||||
base64, on the web), the key a 64-bit FNV-1a of the normalised path. Screenshot and test runs
|
||||
write nothing.
|
||||
6. **The start screen replaces the workspace, never covers it.** It shows when AniCraft starts with
|
||||
no file to open (Preferences › `start_screen`, a checkbox on the screen itself), from File › Start
|
||||
Screen, and from Open Recent in the palette. The menus and status bar stay; Esc or "Back to the
|
||||
document" returns to the document behind, untouched. New offers HD 1280 × 720, Full HD 1920 ×
|
||||
1080, Square 1080 × 1080, Vertical 1080 × 1920 and a custom size with a frame rate; Open…, the
|
||||
sample animation and the recent files (picture, name, folder, Pin or Remove) sit beside it. Every
|
||||
choice goes through `request`, so unsaved work asks first, and the screen goes once the document
|
||||
is there (a refused or cancelled New leaves it up).
|
||||
|
||||
## Consequences
|
||||
|
||||
* Drops, recent files and the start screen work headless and from scripts; the shell only decides
|
||||
where the pointer was.
|
||||
* On the desktop the drop target depends on the system's first pointer move after a drag. Where it
|
||||
doesn't come, media land in the middle of the view: never lost, but not where they were dropped.
|
||||
* On the web a recent file can be reopened while the page keeps its bytes; after a reload it shows
|
||||
as missing (the browser never gives a path back), its picture still there.
|
||||
* The start screen at every launch is the default; artists who want the sample or their last
|
||||
document straight away switch it off on the screen.
|
||||
|
||||
## Not yet
|
||||
|
||||
* Exact desktop drop positions (winit 0.31), and dropping folders of images as a sequence.
|
||||
* SVG into the Library (as a graphic symbol), and dropping onto the timeline (a layer and frame).
|
||||
* Opening several dropped documents (needs document tabs), and reopening the last document at start.
|
||||
* Templates on the start screen, and thumbnails that follow the poster frame.
|
||||
+3
-3
@@ -16,7 +16,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. |
|
||||
| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. |
|
||||
| Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. |
|
||||
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and Line truncated
|
||||
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and Line truncated
|
||||
| Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. |
|
||||
| Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. |
|
||||
| Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. |
|
||||
@@ -40,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. |
|
||||
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); documentation book. |
|
||||
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. |
|
||||
|
||||
## Releases
|
||||
|
||||
@@ -61,7 +61,7 @@ titled with its milestone.
|
||||
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe |
|
||||
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe |
|
||||
|
||||
Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and
|
||||
ActionScript (on M6's plug-in host).
|
||||
|
||||
+6
-1
@@ -54,7 +54,12 @@ autosave) work. On another host, serve over HTTPS for the same reason. Compressi
|
||||
a crash. Copies of tabs that are still open are never offered. Browsers keep only a few MB per
|
||||
site, so documents with large images or sounds may not fit; the status bar says when a copy
|
||||
fails.
|
||||
* **Preferences** are kept in the browser's storage too.
|
||||
* **Dropping files** on the page works as on the desktop (ADR 0059): documents open, drawings,
|
||||
images and sounds land where they are dropped on the stage or in the Library. An XFL folder
|
||||
can't be dropped (the browser hands over files, not folders): drop the `.fla`.
|
||||
* **Preferences** are kept in the browser's storage too, with Open Recent and the start
|
||||
screen's pictures. A recent file reopens while the page still holds it; after a reload it
|
||||
shows as missing (the browser never gives its path back): open it again with Open.
|
||||
* **Leaving the page** with unsaved changes asks first.
|
||||
* **Shortcuts** are the desktop ones; on a Mac they use ⌘.
|
||||
|
||||
|
||||
+1
-1
@@ -352,7 +352,7 @@ mod tests {
|
||||
for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
|
||||
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
|
||||
}
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer"] {
|
||||
for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer"] {
|
||||
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
// The layer depth row shows on artwork layers once the scene has a camera.
|
||||
|
||||
+65
-3
@@ -427,6 +427,12 @@ pub struct App {
|
||||
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 start screen, while it is up (ADR 0059).
|
||||
pub start: Option<crate::start::StartScreen>,
|
||||
/// Files dragged over and dropped onto the window (ADR 0059).
|
||||
pub drop: crate::drop::DropState,
|
||||
/// Recent files' pictures for the start screen.
|
||||
pub thumbs: crate::recent::Thumbs,
|
||||
}
|
||||
|
||||
/// How finished this version is, shown next to the version number (docs/release.md). English:
|
||||
@@ -482,6 +488,8 @@ impl App {
|
||||
let _ = anicraft_engine::text::Fonts::get();
|
||||
});
|
||||
let mut session = session;
|
||||
// Open Recent is the session's list, kept in the preferences (ADR 0059).
|
||||
session.recent = prefs.recent.clone();
|
||||
// The editor draws as Animate does: merge drawing, until Object Drawing (J) is switched on.
|
||||
session.style.object_drawing = false;
|
||||
let mut app = App {
|
||||
@@ -578,6 +586,9 @@ impl App {
|
||||
audio_clock: false,
|
||||
heard: None,
|
||||
last_panel: None,
|
||||
start: None,
|
||||
drop: Default::default(),
|
||||
thumbs: Default::default(),
|
||||
};
|
||||
app.apply_prefs(ctx);
|
||||
app.decode_sounds();
|
||||
@@ -781,6 +792,18 @@ impl App {
|
||||
self.run("scene.select", json!({"scene": last}));
|
||||
}
|
||||
Some("files") => self.show_files = true,
|
||||
Some("start") => {
|
||||
// The start screen with sample recent files (one pinned, one missing).
|
||||
crate::start::open(self);
|
||||
if self.shot.is_some() {
|
||||
crate::recent::sample_entries(self);
|
||||
}
|
||||
}
|
||||
Some("drop") => self.drop.preview = Some((vec![PathBuf::from("sunset.png")], crate::drop::PreviewAt::Stage)), // i18n-exempt: a sample file name
|
||||
Some("droplibrary") => {
|
||||
self.run("library.new_folder", json!({"name": "Backgrounds"})); // i18n-exempt: a sample folder name
|
||||
self.drop.preview = Some((vec![PathBuf::from("sunset.png")], crate::drop::PreviewAt::Library)); // i18n-exempt: a sample file name
|
||||
}
|
||||
Some("recovery") => {
|
||||
// Work left behind by a session that didn't close cleanly (sample entries
|
||||
// unless ANICRAFT_RECOVERY_DIR holds real ones).
|
||||
@@ -1536,7 +1559,15 @@ impl App {
|
||||
/// new document resets. `selected` is how many elements were selected before it ran.
|
||||
pub(crate) fn announce(&mut self, id: &str, v: &Value, selected: usize) {
|
||||
match id {
|
||||
"file.new" | "file.new_sample" | "file.open" => {
|
||||
"file.new" | "file.new_sample" | "file.open" | "file.open_recent" => {
|
||||
// The document is here: the start screen has done its job (ADR 0059).
|
||||
self.start = None;
|
||||
if id != "file.new"
|
||||
&& id != "file.new_sample"
|
||||
&& let Some(path) = self.s.path.clone().or_else(|| v["imported"].as_str().map(PathBuf::from))
|
||||
{
|
||||
crate::recent::captured_on_open(self, &path);
|
||||
}
|
||||
self.view.fit = true;
|
||||
self.library_sel = crate::library::first_item(&self.s.doc);
|
||||
self.decode_sounds();
|
||||
@@ -1544,7 +1575,7 @@ impl App {
|
||||
// An imported file: say what came across and what didn't, and that saving
|
||||
// makes a new .anicraft document.
|
||||
Some(r) => self.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)),
|
||||
None => self.status_ok(if id == "file.open" { tr!("Opened") } else { tr!("New document") }),
|
||||
None => self.status_ok(if id == "file.open" || id == "file.open_recent" { tr!("Opened") } else { tr!("New document") }),
|
||||
}
|
||||
}
|
||||
"file.recover" => {
|
||||
@@ -1564,6 +1595,10 @@ impl App {
|
||||
self.status_ok(tr!("Discarded the autosaved copy"));
|
||||
}
|
||||
"file.save" | "file.save_as" => {
|
||||
// The start screen's picture of it (ADR 0059).
|
||||
if let Some(saved) = v["saved"].as_str() {
|
||||
crate::recent::capture(self, std::path::Path::new(saved));
|
||||
}
|
||||
// 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) });
|
||||
@@ -1715,6 +1750,11 @@ impl App {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if matches!(id, "file.open_recent" | "file.recent_list") {
|
||||
// The recent files with their pictures (the File menu lists them too).
|
||||
crate::start::open(self);
|
||||
return;
|
||||
}
|
||||
if id == "tween.add_hint" {
|
||||
crate::shape_hints::add(self);
|
||||
return;
|
||||
@@ -2224,7 +2264,7 @@ impl App {
|
||||
|
||||
/// The app icon (`assets/app-icon/`; the PNG carries its rounded corners) as a texture, decoded on
|
||||
/// first use and kept in the context. 128 px stays sharp at 64 pt on a 2× display.
|
||||
fn app_mark(ctx: &egui::Context) -> egui::TextureHandle {
|
||||
pub(crate) fn app_mark(ctx: &egui::Context) -> egui::TextureHandle {
|
||||
const PNG: &[u8] = include_bytes!("../assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png");
|
||||
let id = egui::Id::new("anicraft-app-mark");
|
||||
if let Some(tex) = ctx.data(|d| d.get_temp::<egui::TextureHandle>(id)) {
|
||||
@@ -2313,7 +2353,22 @@ impl App {
|
||||
}
|
||||
|
||||
let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2));
|
||||
crate::drop::begin_frame(self);
|
||||
egui::Panel::top("menu_bar").frame(bar(T.chrome)).show(ui, |ui| menus::bar(self, ui));
|
||||
if self.start.is_some() {
|
||||
// The start screen takes the workspace's place (ADR 0059); the menus stay.
|
||||
egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui));
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(T.pasteboard)).show(ui, |ui| crate::start::show(self, ui));
|
||||
} else {
|
||||
self.workspace(ui);
|
||||
}
|
||||
self.windows(&ctx);
|
||||
}
|
||||
|
||||
/// The editor's panels: tools, stage, timeline, properties and Library.
|
||||
fn workspace(&mut self, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2));
|
||||
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));
|
||||
// Docks start at their usual size, but never take most of a small window or a large
|
||||
@@ -2328,7 +2383,12 @@ impl App {
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(T.pasteboard)).show(ui, |ui| stage::show(self, ui));
|
||||
crate::a11y::name_splitter(&ctx, "properties", tr!("Resize the right-hand panels"));
|
||||
crate::a11y::name_splitter(&ctx, "timeline", tr!("Resize the timeline"));
|
||||
}
|
||||
|
||||
/// Dialogs and floating windows, the close guard and the end-of-frame upkeep.
|
||||
fn windows(&mut self, ctx: &egui::Context) {
|
||||
let ctx = ctx.clone();
|
||||
crate::drop::frame(self, &ctx);
|
||||
self.prompt_window(&ctx);
|
||||
crate::convert_symbol::window(self, &ctx);
|
||||
self.about_window(&ctx);
|
||||
@@ -2362,6 +2422,8 @@ impl App {
|
||||
|
||||
// After this frame's edits: start a recovery copy when one is due (off this thread).
|
||||
autosave::tick(self, &ctx);
|
||||
// Open Recent changed (an open, a save, a pin): into the preferences.
|
||||
crate::recent::sync(self);
|
||||
// A browser asks before leaving a page with unsaved work (its close guard).
|
||||
platform::set_unsaved(self.s.is_dirty());
|
||||
|
||||
|
||||
+538
@@ -0,0 +1,538 @@
|
||||
//! Files dropped onto the window from the desktop or a browser (ADR 0059). Documents open (the
|
||||
//! unsaved-changes guard as with File › Open); drawings, images and sounds dropped on the stage
|
||||
//! go onto the active layer at the playhead where they were dropped, and dropped on the Library
|
||||
//! go into it, into the folder under the pointer. While files are dragged over the window a
|
||||
//! highlight shows where they will land. The routing is `anicraft_engine::cmds_drop::route`;
|
||||
//! the import is the `file.drop` command, one undo step.
|
||||
//!
|
||||
//! Where a drop lands needs the pointer. Browsers report it while dragging (our own `dragover`
|
||||
//! listener, `web::drag_pos`), but winit 0.30 gives no position with dragged files, and Windows
|
||||
//! and macOS send no pointer moves during a drag. So a drop waits a moment for the pointer's
|
||||
//! first move after it (the system sends one as the drag ends); without one it lands at the
|
||||
//! centre of the view, and says so.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::theme::{T, Type, color, font};
|
||||
use anicraft_engine::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route};
|
||||
use anicraft_engine::doc::FolderId;
|
||||
use egui::{Pos2, Rect, Stroke, StrokeKind, vec2};
|
||||
use serde_json::json;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// How long a drop waits for the pointer to say where it is, in seconds.
|
||||
const WAIT_FOR_POINTER: f64 = 0.35;
|
||||
|
||||
/// Where the stage was drawn this frame and how it maps to the edited space.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct StageGeo {
|
||||
pub canvas: Rect,
|
||||
pub origin: Pos2,
|
||||
pub zoom: f32,
|
||||
/// Previewing through the camera: artwork edits are paused.
|
||||
pub paused: bool,
|
||||
}
|
||||
|
||||
impl StageGeo {
|
||||
pub fn to_stage(self, p: Pos2) -> (f32, f32) {
|
||||
let z = self.zoom.max(1e-6);
|
||||
((p.x - self.origin.x) / z, (p.y - self.origin.y) / z)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a drop at a point lands.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Spot {
|
||||
/// On the stage, at this point of the edited space.
|
||||
Stage(f32, f32),
|
||||
/// On the Library, into this folder (`None`: the top level).
|
||||
Library(Option<FolderId>),
|
||||
/// Somewhere else on the window.
|
||||
Window,
|
||||
/// The start screen is up: documents open, nothing imports.
|
||||
Start,
|
||||
/// The pointer's position isn't known (a drop on the desktop without a pointer move).
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// What a drop does, worked out from its files and where it landed.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Plan {
|
||||
/// The document to open (the first one dropped).
|
||||
pub open: Option<PathBuf>,
|
||||
/// Files to import, and where.
|
||||
pub import: Vec<PathBuf>,
|
||||
pub to: Option<DropTarget>,
|
||||
/// Files left out, each with why (in the interface language).
|
||||
pub left_out: Vec<(PathBuf, String)>,
|
||||
}
|
||||
|
||||
/// Why a file can't go there, in the interface language.
|
||||
fn refusal(kind: DropKind, to: DropTarget, start: bool) -> String {
|
||||
match kind {
|
||||
DropKind::Unsupported => tr!("AniCraft opens .anicraft, .fla and .xfl documents, and imports SVG drawings, PNG and JPEG images, and WAV, Ogg and MP3 sounds").into(),
|
||||
_ if start => tr!("Open or create a document first, then drop drawings, images and sounds on its stage").into(),
|
||||
DropKind::Drawing if to == DropTarget::Library => tr!("SVG drawings import to the stage: drop it there").into(),
|
||||
_ => tr!("Drop drawings, images and sounds on the stage to place them, or on the Library to add them").into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What dropping `files` at `spot` does. One document opens (AniCraft has one document
|
||||
/// window); other files in the same drop are left out then.
|
||||
pub fn plan(files: &[PathBuf], spot: Spot) -> Plan {
|
||||
let mut out = Plan::default();
|
||||
if let Some(doc) = files.iter().find(|f| kind_of(f) == DropKind::Document) {
|
||||
out.open = Some(doc.clone());
|
||||
for f in files.iter().filter(|f| *f != doc) {
|
||||
out.left_out.push((f.clone(), tr!("AniCraft opens one document at a time; drop the others on their own").into()));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
let to = match spot {
|
||||
Spot::Library(_) => DropTarget::Library,
|
||||
// Without a position, the stage (at the centre of the view).
|
||||
Spot::Stage(..) | Spot::Unknown => DropTarget::Stage,
|
||||
Spot::Window | Spot::Start => DropTarget::Window,
|
||||
};
|
||||
for f in files {
|
||||
let kind = kind_of(f);
|
||||
match route(kind, to) {
|
||||
DropAction::ImportToStage | DropAction::ImportToLibrary => out.import.push(f.clone()),
|
||||
DropAction::Open => {}
|
||||
DropAction::Refuse(_) => out.left_out.push((f.clone(), refusal(kind, to, spot == Spot::Start))),
|
||||
}
|
||||
}
|
||||
if !out.import.is_empty() {
|
||||
out.to = Some(to);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A drop waiting for the pointer (desktop), or for the browser to read the files (web).
|
||||
struct Waiting {
|
||||
files: Vec<PathBuf>,
|
||||
since: f64,
|
||||
/// Browser files still being read, by ticket.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
ticket: Option<u64>,
|
||||
}
|
||||
|
||||
/// The drop state the window keeps between frames.
|
||||
#[derive(Default)]
|
||||
pub struct DropState {
|
||||
/// Where the stage was drawn this frame (set by `stage::show`).
|
||||
pub stage: Option<StageGeo>,
|
||||
waiting: Option<Waiting>,
|
||||
/// The pointer moved while files were dragged over the window: its position is current.
|
||||
tracked: bool,
|
||||
/// A drag shown without one (screenshots and tests): the files and where they hover.
|
||||
pub preview: Option<(Vec<PathBuf>, PreviewAt)>,
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
web_spot: Option<Spot>,
|
||||
}
|
||||
|
||||
/// Where a previewed drag hovers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PreviewAt {
|
||||
Stage,
|
||||
Library,
|
||||
}
|
||||
|
||||
/// Where a drop at `p` lands, from this frame's layout.
|
||||
pub fn spot_at(app: &App, p: Option<Pos2>) -> Spot {
|
||||
if app.start.is_some() {
|
||||
return Spot::Start;
|
||||
}
|
||||
let Some(p) = p else { return Spot::Unknown };
|
||||
if let Some(folder) = app.library.drop_zone.folder_at(p) {
|
||||
return Spot::Library(folder);
|
||||
}
|
||||
match app.drop.stage {
|
||||
Some(g) if g.canvas.contains(p) => {
|
||||
let (x, y) = g.to_stage(p);
|
||||
Spot::Stage(x, y)
|
||||
}
|
||||
_ => Spot::Window,
|
||||
}
|
||||
}
|
||||
|
||||
/// Before the panels draw: forget last frame's targets (a hidden panel takes nothing).
|
||||
pub fn begin_frame(app: &mut App) {
|
||||
app.drop.stage = None;
|
||||
app.library.drop_zone = Default::default();
|
||||
}
|
||||
|
||||
/// The pointer's position over a dragged file, if it is known.
|
||||
fn drag_pointer(app: &App, ctx: &egui::Context) -> Option<Pos2> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = app;
|
||||
let z = ctx.zoom_factor().max(1e-3);
|
||||
crate::web::drag_pos().map(|(x, y)| egui::pos2(x / z, y / z))
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if app.drop.tracked { ctx.input(|i| i.pointer.latest_pos()) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
/// After the panels drew: the highlight while files hover, and what was dropped.
|
||||
pub fn frame(app: &mut App, ctx: &egui::Context) {
|
||||
let (hovered, dropped, moved, now) = ctx.input(|i| {
|
||||
let hovered: Vec<PathBuf> = i.raw.hovered_files.iter().map(|h| h.path.clone().unwrap_or_else(|| PathBuf::from(guess_name(&h.mime)))).collect();
|
||||
let moved = i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_)));
|
||||
(hovered, i.raw.dropped_files.clone(), moved, i.time)
|
||||
});
|
||||
if !hovered.is_empty() {
|
||||
app.drop.tracked |= moved;
|
||||
let p = drag_pointer(app, ctx);
|
||||
highlight(app, ctx, &hovered, p);
|
||||
} else if let Some((files, at)) = app.drop.preview.clone() {
|
||||
let p = preview_point(app, at);
|
||||
highlight(app, ctx, &files, p);
|
||||
}
|
||||
if !dropped.is_empty() {
|
||||
let files: Vec<PathBuf> = dropped.iter().take(anicraft_engine::cmds_drop::MAX_DROPPED).map(|f| f.path().to_path_buf()).collect();
|
||||
if dropped.len() > anicraft_engine::cmds_drop::MAX_DROPPED {
|
||||
app.status_err(tr!("Drop at most {n} files at once", n = anicraft_engine::cmds_drop::MAX_DROPPED));
|
||||
app.drop.tracked = false;
|
||||
return;
|
||||
}
|
||||
app.playing = false;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
// The browser said where the drop is; it reads the files' bytes, which arrive later.
|
||||
let spot = spot_at(app, drag_pointer(app, ctx));
|
||||
let handles: Vec<web_sys::File> = dropped.iter().filter_map(|f| f.web_file().cloned()).collect();
|
||||
let ticket = crate::web::read_dropped(handles);
|
||||
app.drop.web_spot = Some(spot);
|
||||
app.drop.waiting = Some(Waiting { files, since: now, ticket: Some(ticket) });
|
||||
crate::web::clear_drag_pos();
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if app.drop.tracked {
|
||||
let spot = spot_at(app, ctx.input(|i| i.pointer.latest_pos()));
|
||||
run(app, &files, spot);
|
||||
} else {
|
||||
app.drop.waiting = Some(Waiting { files, since: now });
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
app.drop.tracked = false;
|
||||
return;
|
||||
}
|
||||
if hovered.is_empty() {
|
||||
// A drag that left the window (or was cancelled) starts over.
|
||||
app.drop.tracked = false;
|
||||
}
|
||||
resolve_waiting(app, ctx, moved, now);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn resolve_waiting(app: &mut App, ctx: &egui::Context, moved: bool, now: f64) {
|
||||
let Some(w) = &app.drop.waiting else { return };
|
||||
let timed_out = now - w.since > WAIT_FOR_POINTER;
|
||||
if !moved && !timed_out {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
return;
|
||||
}
|
||||
let Some(w) = app.drop.waiting.take() else { return };
|
||||
let p = if moved { ctx.input(|i| i.pointer.latest_pos()) } else { None };
|
||||
run(app, &w.files, spot_at(app, p));
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn resolve_waiting(app: &mut App, _ctx: &egui::Context, _moved: bool, _now: f64) {
|
||||
let Some((ticket, read)) = crate::web::take_dropped() else { return };
|
||||
if app.drop.waiting.as_ref().and_then(|w| w.ticket) != Some(ticket) {
|
||||
return;
|
||||
}
|
||||
let (Some(w), Some(spot)) = (app.drop.waiting.take(), app.drop.web_spot.take()) else { return };
|
||||
let _ = WAIT_FOR_POINTER;
|
||||
let mut files = Vec::new();
|
||||
for (name, data) in read {
|
||||
// Only the name: the browser never says which folder a file came from.
|
||||
let path = PathBuf::from(&name);
|
||||
match data.and_then(|d| anicraft_engine::vfs::put(&path, d).map_err(|e| e.to_string())) {
|
||||
Ok(()) => files.push(path),
|
||||
Err(e) => app.status_err(tr!("Could not open {name}: {e}", name = name, e = e)),
|
||||
}
|
||||
}
|
||||
let _ = w.files;
|
||||
if !files.is_empty() {
|
||||
run(app, &files, spot);
|
||||
}
|
||||
}
|
||||
|
||||
/// Carries out a drop.
|
||||
pub fn run(app: &mut App, files: &[PathBuf], spot: Spot) {
|
||||
let plan = plan(files, spot);
|
||||
let names = |list: &[PathBuf]| list.iter().map(|p| crate::recent::display_name(p)).collect::<Vec<_>>().join(", ");
|
||||
if let Some(doc) = &plan.open {
|
||||
app.start = None;
|
||||
app.request("file.open", json!({"path": doc.display().to_string()}));
|
||||
if let Some((_, why)) = plan.left_out.first() {
|
||||
app.status_ok(tr!("Left out {files}: {why}", files = names(&plan.left_out.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>()), why = why));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(to) = plan.to else {
|
||||
// Nothing to import: one message says why.
|
||||
if let Some((p, why)) = plan.left_out.first() {
|
||||
app.status_err(tr!("Can't import {file}: {why}", file = crate::recent::display_name(p), why = why));
|
||||
}
|
||||
return;
|
||||
};
|
||||
let paths: Vec<String> = plan.import.iter().map(|p| p.display().to_string()).collect();
|
||||
let n = plan.import.len();
|
||||
let done = match (to, spot) {
|
||||
(DropTarget::Library, Spot::Library(folder)) => {
|
||||
let v = app.run("file.drop", json!({"paths": paths, "to": "library", "folder": folder.map(|f| f.0)}));
|
||||
if let Some(f) = folder {
|
||||
app.library.expanded.extend(app.s.doc.folder_chain(f));
|
||||
}
|
||||
v.map(|v| {
|
||||
// The last file added is the Library's current item.
|
||||
let last = v["items"].as_array().and_then(|a| a.last()).cloned().unwrap_or_default();
|
||||
match (last["bitmap"].as_u64(), last["sound"].as_u64()) {
|
||||
(Some(b), _) => app.library_sel = Some(anicraft_engine::doc::LibraryItem::Bitmap(anicraft_engine::doc::BitmapId(b))),
|
||||
(None, Some(snd)) => app.library_sel = Some(anicraft_engine::doc::LibraryItem::Sound(anicraft_engine::doc::SoundId(snd))),
|
||||
_ => {}
|
||||
}
|
||||
match folder.and_then(|f| app.s.doc.folder(f)).map(|f| f.name.clone()) {
|
||||
Some(name) => trn!("Added {n} file to “{folder}” in the Library", "Added {n} files to “{folder}” in the Library", n, folder = name),
|
||||
None => trn!("Added {n} file to the Library", "Added {n} files to the Library", n),
|
||||
}
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
let geo = app.drop.stage;
|
||||
if geo.is_some_and(|g| g.paused) {
|
||||
app.status_ok(tr!("Previewing through the camera: artwork edits are paused. Turn off View › Preview Through Camera to edit."));
|
||||
return;
|
||||
}
|
||||
let (centred, (x, y)) = match spot {
|
||||
Spot::Stage(x, y) => (false, (x, y)),
|
||||
_ => {
|
||||
let c = app.view_center_stage();
|
||||
let c = match app.s.edit_view() {
|
||||
Some(v) if v.scale.abs() > 1e-6 => ((c.x - v.origin.x) / v.scale, (c.y - v.origin.y) / v.scale),
|
||||
_ => (c.x, c.y),
|
||||
};
|
||||
(true, c)
|
||||
}
|
||||
};
|
||||
let v = app.run("file.drop", json!({"paths": paths, "to": "stage", "x": x, "y": y}));
|
||||
v.map(|_| {
|
||||
let layer = app.s.active_layer().map(|l| l.name.clone()).unwrap_or_default();
|
||||
let (frame, undo) = (app.s.frame + 1, app.undo_key());
|
||||
if centred {
|
||||
trn!("Placed {n} file on {layer} at frame {frame}, in the middle of the view — {undo} to undo", "Placed {n} files on {layer} at frame {frame}, in the middle of the view — {undo} to undo", n, layer = layer, frame = frame, undo = undo)
|
||||
} else {
|
||||
trn!("Placed {n} file on {layer} at frame {frame} — {undo} to undo", "Placed {n} files on {layer} at frame {frame} — {undo} to undo", n, layer = layer, frame = frame, undo = undo)
|
||||
}
|
||||
})
|
||||
}
|
||||
};
|
||||
if let Some(msg) = done {
|
||||
app.decode_sounds();
|
||||
match plan.left_out.first() {
|
||||
Some((p, why)) => app.status_ok(tr!("{done}. Left out {file}: {why}", done = msg, file = crate::recent::display_name(p), why = why)),
|
||||
None => app.status_ok(msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A name for a file the browser describes only by its type while it is dragged.
|
||||
fn guess_name(mime: &str) -> &'static str {
|
||||
match mime {
|
||||
"image/svg+xml" => "drawing.svg",
|
||||
"image/png" => "image.png",
|
||||
"image/jpeg" => "image.jpg",
|
||||
"audio/wav" | "audio/x-wav" | "audio/wave" => "sound.wav",
|
||||
"audio/ogg" => "sound.ogg",
|
||||
"audio/mpeg" | "audio/mp3" => "sound.mp3",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a previewed drag hovers on screen: the stage's middle, or the Library's first folder.
|
||||
fn preview_point(app: &App, at: PreviewAt) -> Option<Pos2> {
|
||||
match at {
|
||||
PreviewAt::Stage => app.drop.stage.map(|g| g.canvas.center() + vec2(-g.canvas.width() * 0.12, -g.canvas.height() * 0.08)),
|
||||
PreviewAt::Library => app.library.drop_zone.rows.iter().find(|(_, f)| f.is_some()).map(|(r, _)| r.center()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The drop highlight: what lands where, drawn over everything.
|
||||
fn highlight(app: &App, ctx: &egui::Context, files: &[PathBuf], p: Option<Pos2>) {
|
||||
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("file_drop")));
|
||||
let screen = ctx.content_rect().shrink(3.0);
|
||||
// Only the names are known while a browser drags (and sometimes not even those).
|
||||
let known: Vec<&PathBuf> = files.iter().filter(|f| !f.as_os_str().is_empty()).collect();
|
||||
let docs: Vec<&&PathBuf> = known.iter().filter(|f| kind_of(f) == DropKind::Document).collect();
|
||||
let stroke = Stroke::new(2.0, T.accent);
|
||||
let label = |at: Pos2, text: String, ok: bool| {
|
||||
let c = if ok { color(Type::Body) } else { T.error };
|
||||
let galley = painter.layout_no_wrap(text, font(Type::Label), c);
|
||||
let r = Rect::from_min_size(at, vec2(galley.rect.width(), galley.rect.height())).expand(6.0);
|
||||
// Kept on screen.
|
||||
let r = r.translate(vec2((screen.right() - r.right()).min(0.0), (screen.bottom() - r.bottom()).min(0.0)));
|
||||
painter.rect_filled(r, T.rc(), T.panel);
|
||||
painter.rect_stroke(r, T.rc(), Stroke::new(1.0, if ok { T.accent } else { T.error }), StrokeKind::Inside);
|
||||
painter.galley(r.min + vec2(6.0, 6.0), galley, c);
|
||||
};
|
||||
if let Some(doc) = docs.first() {
|
||||
painter.rect_stroke(screen, T.rc(), stroke, StrokeKind::Inside);
|
||||
let text = if app.s.is_dirty() { tr!("Open {name} (you'll be asked about unsaved changes)", name = crate::recent::display_name(doc)) } else { tr!("Open {name}", name = crate::recent::display_name(doc)) };
|
||||
label(screen.center_top() + vec2(-120.0, 12.0), text, true);
|
||||
return;
|
||||
}
|
||||
let spot = spot_at(app, p);
|
||||
let what = match known.len() {
|
||||
0 => tr!("these files").to_string(),
|
||||
1 => crate::recent::display_name(known[0]),
|
||||
n => trn!("{n} file", "{n} files", n),
|
||||
};
|
||||
let fits = |to: DropTarget| known.iter().all(|f| matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary));
|
||||
match (spot, p) {
|
||||
(Spot::Stage(..), Some(p)) => {
|
||||
if let Some(g) = app.drop.stage {
|
||||
painter.rect_stroke(g.canvas.shrink(1.0), crate::theme::SQUARE, stroke, StrokeKind::Inside);
|
||||
}
|
||||
let r = 8.0;
|
||||
painter.line_segment([p - vec2(r, 0.0), p + vec2(r, 0.0)], Stroke::new(1.5, T.accent));
|
||||
painter.line_segment([p - vec2(0.0, r), p + vec2(0.0, r)], Stroke::new(1.5, T.accent));
|
||||
let ok = fits(DropTarget::Stage);
|
||||
let layer = app.s.active_layer().map(|l| l.name.clone()).unwrap_or_default();
|
||||
let text = if ok { tr!("Place {what} on {layer} at frame {frame}", what = what, layer = layer, frame = app.s.frame + 1) } else { refusal(DropKind::Unsupported, DropTarget::Stage, false) };
|
||||
label(p + vec2(14.0, 12.0), text, ok);
|
||||
}
|
||||
(Spot::Library(folder), Some(p)) => {
|
||||
let zone = &app.library.drop_zone;
|
||||
match zone.row_at(p).filter(|_| folder.is_some()) {
|
||||
Some(row) => {
|
||||
painter.rect_stroke(row, T.rc(), stroke, StrokeKind::Inside);
|
||||
}
|
||||
None => {
|
||||
if let Some(panel) = zone.panel {
|
||||
painter.rect_stroke(panel, T.rc(), stroke, StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = fits(DropTarget::Library);
|
||||
let text = match (ok, folder.and_then(|f| app.s.doc.folder(f))) {
|
||||
(true, Some(f)) => tr!("Add {what} to “{folder}”", what = what, folder = f.name),
|
||||
(true, None) => tr!("Add {what} to the Library", what = what),
|
||||
(false, _) => match known.iter().find(|f| !fits_one(f, DropTarget::Library)) {
|
||||
Some(f) => refusal(kind_of(f), DropTarget::Library, false),
|
||||
None => refusal(DropKind::Unsupported, DropTarget::Library, false),
|
||||
},
|
||||
};
|
||||
label(p + vec2(14.0, 12.0), text, ok);
|
||||
}
|
||||
(Spot::Unknown, _) => {
|
||||
// The desktop doesn't say where the pointer is during a drag: say what each place does.
|
||||
painter.rect_stroke(screen, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside);
|
||||
label(screen.center_top() + vec2(-180.0, 12.0), tr!("Drop {what} on the stage to place it, or on the Library to add it", what = what), true);
|
||||
}
|
||||
(spot, p) => {
|
||||
let at = p.unwrap_or(screen.center_top()) + vec2(14.0, 12.0);
|
||||
label(at, refusal(known.first().map_or(DropKind::Image, |f| kind_of(f)), DropTarget::Window, spot == Spot::Start), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fits_one(f: &Path, to: DropTarget) -> bool {
|
||||
matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn p(s: &str) -> PathBuf {
|
||||
PathBuf::from(s)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_are_routed_by_type_and_target() {
|
||||
// A document opens wherever it lands, and only one at a time.
|
||||
for spot in [Spot::Stage(1.0, 2.0), Spot::Library(None), Spot::Window, Spot::Start, Spot::Unknown] {
|
||||
let plan = plan(&[p("walk.anicraft"), p("photo.png"), p("old.fla")], spot);
|
||||
assert_eq!(plan.open, Some(p("walk.anicraft")), "{spot:?}");
|
||||
assert!(plan.import.is_empty());
|
||||
assert_eq!(plan.left_out.len(), 2);
|
||||
}
|
||||
let plan_at = |spot| plan(&[p("a.svg"), p("b.png"), p("c.mp3"), p("d.psd")], spot);
|
||||
// On the stage: everything AniCraft reads, the rest left out with a reason.
|
||||
let on_stage = plan_at(Spot::Stage(10.0, 20.0));
|
||||
assert_eq!((on_stage.to, on_stage.import.len(), on_stage.left_out.len()), (Some(DropTarget::Stage), 3, 1));
|
||||
assert!(on_stage.left_out[0].1.contains("SVG"), "says what AniCraft reads");
|
||||
// On the Library: images and sounds; a drawing is pointed to the stage.
|
||||
let in_library = plan_at(Spot::Library(Some(FolderId(7))));
|
||||
assert_eq!((in_library.to, in_library.import.len(), in_library.left_out.len()), (Some(DropTarget::Library), 2, 2));
|
||||
assert!(in_library.left_out.iter().any(|(f, why)| f == &p("a.svg") && why.contains("stage")));
|
||||
// Elsewhere on the window, or over the start screen: nothing imports.
|
||||
for spot in [Spot::Window, Spot::Start] {
|
||||
let plan = plan_at(spot);
|
||||
assert!(plan.import.is_empty() && plan.to.is_none() && plan.left_out.len() == 4, "{spot:?}");
|
||||
}
|
||||
// No pointer position: the stage, at the middle of the view.
|
||||
assert_eq!(plan_at(Spot::Unknown).to, Some(DropTarget::Stage));
|
||||
// Only unsupported files: nothing to do but say why.
|
||||
let plan = plan(&[p("notes.txt")], Spot::Stage(0.0, 0.0));
|
||||
assert!(plan.to.is_none() && plan.open.is_none() && plan.left_out.len() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_lands_where_the_layout_says() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(PathBuf::from("unused.png")));
|
||||
app.run("library.new_folder", json!({"name": "Props"}));
|
||||
let screen = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() };
|
||||
for _ in 0..3 {
|
||||
let mut out = ctx.run_ui(screen.clone(), |ui| app.frame(ui));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
let geo = app.drop.stage.expect("the stage drew");
|
||||
// The middle of the canvas maps into the stage.
|
||||
match spot_at(&app, Some(geo.canvas.center())) {
|
||||
Spot::Stage(x, y) => assert!(x.is_finite() && y.is_finite()),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let (row, folder) = *app.library.drop_zone.rows.iter().find(|(_, f)| f.is_some()).expect("the folder row drew");
|
||||
assert_eq!(spot_at(&app, Some(row.center())), Spot::Library(folder));
|
||||
assert_eq!(spot_at(&app, Some(egui::pos2(1.0, 1.0))), Spot::Window, "the menu bar takes nothing");
|
||||
assert_eq!(spot_at(&app, None), Spot::Unknown);
|
||||
crate::start::open(&mut app);
|
||||
assert_eq!(spot_at(&app, Some(geo.canvas.center())), Spot::Start);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_media_land_on_the_stage_or_in_a_library_folder() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-shell-drop-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let png = dir.join("dot.png");
|
||||
std::fs::write(&png, anicraft_engine::render::encode_png(2, 2, &[200u8; 16]).unwrap()).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(PathBuf::from("unused.png")));
|
||||
let bitmaps = app.s.doc.bitmaps.len();
|
||||
run(&mut app, std::slice::from_ref(&png), Spot::Stage(50.0, 40.0));
|
||||
assert_eq!(app.s.doc.bitmaps.len(), bitmaps + 1);
|
||||
assert_eq!(app.s.selection.len(), 1);
|
||||
assert!(app.status.as_ref().is_some_and(|s| !s.error), "{:?}", app.status.as_ref().map(|s| &s.text));
|
||||
let folder = app.run("library.new_folder", json!({"name": "Props"})).and_then(|v| v["folder"].as_u64()).map(FolderId).unwrap();
|
||||
run(&mut app, std::slice::from_ref(&png), Spot::Library(Some(folder)));
|
||||
assert_eq!(app.s.doc.folder_contents(folder).len(), 1);
|
||||
assert!(app.library.expanded.contains(&folder), "the folder opens to show it");
|
||||
// An unsupported file: one clear message, nothing changes.
|
||||
let before = app.s.doc.clone();
|
||||
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.
|
||||
run(&mut app, &[dir.join("other.anicraft")], Spot::Stage(0.0, 0.0));
|
||||
assert!(app.confirm.is_some());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values.
|
||||
|
||||
const SOURCES: [(&str, &str); 22] = [
|
||||
const SOURCES: [(&str, &str); 25] = [
|
||||
("drop.rs", include_str!("drop.rs")),
|
||||
("recent.rs", include_str!("recent.rs")),
|
||||
("start.rs", include_str!("start.rs")),
|
||||
("actions_panel.rs", include_str!("actions_panel.rs")),
|
||||
("test_movie.rs", include_str!("test_movie.rs")),
|
||||
("autosave.rs", include_str!("autosave.rs")),
|
||||
|
||||
+2
-2
@@ -587,7 +587,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() {
|
||||
a.run("element.set_color_effect", serde_json::json!({"style": style}));
|
||||
}));
|
||||
}
|
||||
for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer"] {
|
||||
for panel in ["start", "sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer"] {
|
||||
found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] {
|
||||
@@ -777,7 +777,7 @@ fn screen_reader_names_are_translated_too() {
|
||||
found.extend(untranslated_names("library item", |a, _| {
|
||||
a.library_sel = a.s.doc.library.first().map(|s| crate::app::LibraryItem::Symbol(s.id));
|
||||
}));
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testscript", "exporthtml", "envelope"] {
|
||||
for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testscript", "exporthtml", "envelope"] {
|
||||
found.extend(untranslated_names(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
assert!(found.is_empty(), "{} screen-reader names not translated in the pseudo-locale:\n{}", found.len(), found.join("\n"));
|
||||
|
||||
@@ -58,6 +58,33 @@ pub struct LibraryView {
|
||||
list_rect: Option<Rect>,
|
||||
uses: Option<(StateId, HashMap<LibraryItem, usize>, HashSet<LibraryItem>)>,
|
||||
preview: Option<Preview>,
|
||||
/// Where files dropped from the desktop land this frame (ADR 0059).
|
||||
pub drop_zone: DropZone,
|
||||
}
|
||||
|
||||
/// The Library as a target for files dropped from the desktop (ADR 0059): the panel, and each
|
||||
/// row with the folder a file dropped on it goes into. Cleared every frame before the panels
|
||||
/// draw, so a hidden panel takes nothing.
|
||||
#[derive(Default)]
|
||||
pub struct DropZone {
|
||||
pub panel: Option<Rect>,
|
||||
pub rows: Vec<(Rect, Option<FolderId>)>,
|
||||
}
|
||||
|
||||
impl DropZone {
|
||||
/// The folder a file dropped at `p` goes into (`None` inside: the top level), or `None`
|
||||
/// outside the panel.
|
||||
pub fn folder_at(&self, p: Pos2) -> Option<Option<FolderId>> {
|
||||
if !self.panel.is_some_and(|r| r.contains(p)) {
|
||||
return None;
|
||||
}
|
||||
Some(self.rows.iter().find(|(r, _)| r.contains(p)).and_then(|(_, f)| *f))
|
||||
}
|
||||
|
||||
/// The row a drop at `p` lands on (a folder row, or the row inside that folder).
|
||||
pub fn row_at(&self, p: Pos2) -> Option<Rect> {
|
||||
self.rows.iter().find(|(r, _)| r.contains(p)).map(|(r, _)| *r)
|
||||
}
|
||||
}
|
||||
|
||||
/// The current item's preview picture, and what it was made from.
|
||||
@@ -558,6 +585,7 @@ fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet<Libr
|
||||
LibraryEntry::Folder(f) => Some(f),
|
||||
e => app.s.doc.parent_of(e),
|
||||
};
|
||||
app.library.drop_zone.rows.push((r.intersect(ui.clip_rect()), target));
|
||||
if let Some(payload) = resp.dnd_hover_payload::<Vec<LibraryEntry>>()
|
||||
&& !payload.contains(&row.entry)
|
||||
{
|
||||
|
||||
+10
-1
@@ -33,6 +33,7 @@ mod bone_tool;
|
||||
mod camera_tool;
|
||||
mod convert_symbol;
|
||||
mod dialogs;
|
||||
mod drop;
|
||||
mod gpu_stage;
|
||||
mod icons;
|
||||
mod keymap;
|
||||
@@ -48,10 +49,12 @@ mod pathtools;
|
||||
mod platform;
|
||||
mod plugins_ui;
|
||||
mod prefs;
|
||||
mod recent;
|
||||
mod scale_grid;
|
||||
mod sound;
|
||||
mod shape_hints;
|
||||
mod stage;
|
||||
mod start;
|
||||
mod test_movie;
|
||||
mod theme;
|
||||
mod timeline;
|
||||
@@ -110,11 +113,17 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option<PathBuf>, o
|
||||
// `--lang` before the window exists, so its first status line is in that language too.
|
||||
i18n::force(look.lang.as_deref());
|
||||
let (session, report) = open_session(file);
|
||||
let file_given = file.map(Path::to_path_buf);
|
||||
eframe::run_native(
|
||||
"AniCraft",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let starting_fresh = file_given.is_none() && shot.is_none();
|
||||
let mut a = app::App::new(cc, session, shot);
|
||||
// No document to open: the start screen, unless it was switched off (ADR 0059).
|
||||
if starting_fresh && a.prefs.start_screen {
|
||||
start::open(&mut a);
|
||||
}
|
||||
a.preview_look(&cc.egui_ctx, look.theme, look.scale);
|
||||
a.open_panel(open.as_deref());
|
||||
// An imported document says what came across, as opening it from the menu does.
|
||||
@@ -182,7 +191,7 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!( // i18n-exempt: the --help console text
|
||||
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|button|testhits|exporthtml|sound|envelope|library|librarymenu|colour]\n\
|
||||
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|button|testhits|exporthtml|sound|envelope|library|librarymenu|colour]\n\
|
||||
--renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\
|
||||
|
||||
@@ -140,6 +140,13 @@ fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option<bool>
|
||||
fn registry_items(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpec]) {
|
||||
for spec in cmds.iter().filter(|c| c.menu == top) {
|
||||
item(app, ui, spec);
|
||||
if spec.id == "file.open" {
|
||||
// Below Open, as in Animate: the recent files, and the start screen (ADR 0059).
|
||||
ui.menu_button(tr!("Open Recent"), |ui| crate::recent::menu(app, ui));
|
||||
if ui_item(ui, tr!("Start Screen"), "", None) {
|
||||
crate::start::open(app);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut subs: Vec<&str> = Vec::new();
|
||||
for c in cmds {
|
||||
|
||||
+3
-1
@@ -2105,5 +2105,7 @@ fn ease_curve(ui: &mut egui::Ui, e: anicraft_engine::doc::Easing) {
|
||||
}
|
||||
|
||||
fn library(app: &mut App, ui: &mut egui::Ui) {
|
||||
crate::library::panel(app, ui);
|
||||
// Where the panel is, for files dropped on it (ADR 0059).
|
||||
let r = ui.scope(|ui| crate::library::panel(app, ui)).response.rect;
|
||||
app.library.drop_zone.panel = Some(r);
|
||||
}
|
||||
@@ -167,6 +167,29 @@ pub fn save_settings(json: &str) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A recent file's start-screen picture (ADR 0059): `Thumbnails/<key>.png` in the settings
|
||||
/// folder, or browser storage on the web. `None` when there is none yet.
|
||||
pub fn load_thumbnail(key: &str) -> Option<Vec<u8>> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return crate::web::storage_get(&format!("anicraft.thumb.{key}")).and_then(|t| anicraft_engine::doc::base64_decode(&t));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
config_dir().and_then(|d| std::fs::read(d.join("Thumbnails").join(format!("{key}.png"))).ok()) // i18n-exempt: a folder name
|
||||
}
|
||||
|
||||
/// Keeps a recent file's picture (a small PNG) for the start screen.
|
||||
pub fn save_thumbnail(key: &str, png: &[u8]) -> Result<(), String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return crate::web::storage_set(&format!("anicraft.thumb.{key}"), &anicraft_engine::doc::base64_encode(png));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let dir = config_dir().ok_or(tr!("no settings folder on this system"))?.join("Thumbnails"); // i18n-exempt: a folder name
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let (path, tmp) = (dir.join(format!("{key}.png")), dir.join(format!("{key}.png.tmp")));
|
||||
std::fs::write(&tmp, png).map_err(|e| e.to_string())?;
|
||||
std::fs::rename(&tmp, &path).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Why this build can't run `cmd`, if it can't: a web page can't start ffmpeg or keep files in
|
||||
/// a folder of the computer (ADR 0036). The desktop app runs everything.
|
||||
pub fn unavailable(cmd: &str) -> Option<&'static str> {
|
||||
|
||||
@@ -90,6 +90,12 @@ pub struct Prefs {
|
||||
pub autosave_edits: u32,
|
||||
/// Onion skin options (ADR 0047), kept from session to session.
|
||||
pub onion: OnionPrefs,
|
||||
/// File › Open Recent and the start screen's list (ADR 0059): pinned favourites, then the
|
||||
/// last 10 documents opened or saved.
|
||||
#[serde(deserialize_with = "lenient_recent")]
|
||||
pub recent: anicraft_engine::cmds_recent::RecentFiles,
|
||||
/// Show the start screen when AniCraft starts without a document to open (ADR 0059).
|
||||
pub start_screen: bool,
|
||||
}
|
||||
|
||||
/// Onion skin options that carry over between sessions (ADR 0047). Whether onion skin and Edit
|
||||
@@ -140,10 +146,25 @@ impl Default for Prefs {
|
||||
autosave_secs: 60,
|
||||
autosave_edits: 25,
|
||||
onion: OnionPrefs::default(),
|
||||
recent: Default::default(),
|
||||
start_screen: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The recent files as written, skipping entries that aren't one (a hand-edited file): one bad
|
||||
/// entry must not reset every preference.
|
||||
fn lenient_recent<'de, D: serde::Deserializer<'de>>(d: D) -> Result<anicraft_engine::cmds_recent::RecentFiles, D::Error> {
|
||||
use anicraft_engine::cmds_recent::{RecentFile, RecentFiles};
|
||||
let v = serde_json::Value::deserialize(d)?;
|
||||
let list: Vec<serde_json::Value> = match v {
|
||||
serde_json::Value::Array(a) => a.into_iter().take(1000).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let good: Vec<RecentFile> = list.into_iter().filter_map(|x| serde_json::from_value::<RecentFile>(x).ok()).collect();
|
||||
Ok(serde_json::from_value::<RecentFiles>(serde_json::to_value(good).unwrap_or_default()).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Autosave intervals offered in Preferences: `(seconds, label)`.
|
||||
pub const AUTOSAVE_INTERVALS: [(u32, &str); 5] = [(30, tr_noop!("30 seconds")), (60, tr_noop!("1 minute")), (120, tr_noop!("2 minutes")), (300, tr_noop!("5 minutes")), (600, tr_noop!("10 minutes"))];
|
||||
pub const AUTOSAVE_SECS_RANGE: std::ops::RangeInclusive<u32> = 15..=600;
|
||||
@@ -171,6 +192,7 @@ impl Prefs {
|
||||
self.autosave_edits = self.autosave_edits.min(*AUTOSAVE_EDITS_RANGE.end());
|
||||
self.onion.before = self.onion.before.min(ONION_REACH_MAX);
|
||||
self.onion.after = self.onion.after.min(ONION_REACH_MAX);
|
||||
self.recent = std::mem::take(&mut self.recent).sanitized();
|
||||
self
|
||||
}
|
||||
|
||||
@@ -273,5 +295,16 @@ mod tests {
|
||||
let p = Prefs::from_json(r#"{"autosave": false, "autosave_secs": 1, "autosave_edits": 99999999}"#);
|
||||
assert!(!p.autosave);
|
||||
assert_eq!((p.autosave_secs, p.autosave_edits), (15, 1000));
|
||||
// Older files have no recent files and show the start screen (ADR 0059); a list
|
||||
// someone edited by hand is cleaned up.
|
||||
let p = Prefs::from_json(r#"{"ui_scale": 1.25}"#);
|
||||
assert!(p.recent.is_empty() && p.start_screen);
|
||||
let p = Prefs::from_json(r#"{"recent": [{"path": "a.anicraft"}, {"path": "a.anicraft"}, {"path": ""}, 7], "start_screen": false}"#);
|
||||
let paths: Vec<_> = p.recent.entries().iter().map(|e| e.path.display().to_string()).collect();
|
||||
assert_eq!(paths, ["a.anicraft"], "bad entries are skipped, the rest kept");
|
||||
assert!(!p.start_screen, "and the other preferences with them");
|
||||
let p = Prefs::from_json(r#"{"recent": [{"path": "b.anicraft"}, {"path": "a.anicraft", "pinned": true}, {"path": "b.anicraft"}]}"#);
|
||||
let paths: Vec<_> = p.recent.entries().iter().map(|e| (e.path.display().to_string(), e.pinned)).collect();
|
||||
assert_eq!(paths, [("a.anicraft".to_string(), true), ("b.anicraft".to_string(), false)]);
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
//! Recent files in the window (ADR 0059): File › Open Recent, the list kept in the preferences,
|
||||
//! and the thumbnails the start screen shows. The list itself is the session's
|
||||
//! (`anicraft_engine::cmds_recent`): `file.open` and `file.save` add to it, the `prefs.recent_*`
|
||||
//! commands change it, and the window copies it into the preferences whenever it changes.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::platform;
|
||||
use crate::theme::{Type, text};
|
||||
use anicraft_engine::cmds_recent::{self, RecentFile};
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
/// Thumbnails loaded for the start screen, by thumbnail key (`None`: there is none).
|
||||
#[derive(Default)]
|
||||
pub struct Thumbs {
|
||||
loaded: HashMap<String, Option<egui::TextureHandle>>,
|
||||
/// Pictures made in memory (screenshot runs show sample entries without touching disk).
|
||||
pub(crate) seeded: HashMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Thumbs {
|
||||
/// The picture of `path`, decoded and uploaded once.
|
||||
pub fn get(&mut self, ctx: &egui::Context, path: &Path) -> Option<egui::TextureHandle> {
|
||||
let key = cmds_recent::thumb_key(path);
|
||||
if let Some(t) = self.loaded.get(&key) {
|
||||
return t.clone();
|
||||
}
|
||||
let png = self.seeded.get(&key).cloned().or_else(|| platform::load_thumbnail(&key));
|
||||
let tex = png.and_then(|png| anicraft_engine::doc::decode_png(&png)).and_then(|px| {
|
||||
let (w, h) = (usize::try_from(px.width).ok()?, usize::try_from(px.height).ok()?);
|
||||
(w > 0 && h > 0 && px.rgba.len() == w * h * 4).then(|| ctx.load_texture(format!("recent-{key}"), egui::ColorImage::from_rgba_unmultiplied([w, h], &px.rgba), egui::TextureOptions::LINEAR))
|
||||
});
|
||||
self.loaded.insert(key, tex.clone());
|
||||
tex
|
||||
}
|
||||
|
||||
/// Forgets `path`'s picture, so the next look reads the new one.
|
||||
pub fn invalidate(&mut self, path: &Path) {
|
||||
self.loaded.remove(&cmds_recent::thumb_key(path));
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture of the open document's first frame, kept for `path` (after a save or an open).
|
||||
/// Screenshot and test runs keep nothing on disk.
|
||||
pub fn capture(app: &mut App, path: &Path) {
|
||||
if app.shot.is_some() {
|
||||
return;
|
||||
}
|
||||
let t = web_time::Instant::now();
|
||||
match cmds_recent::thumbnail_png(&app.s.doc) {
|
||||
Ok(png) => {
|
||||
if let Err(e) = platform::save_thumbnail(&cmds_recent::thumb_key(path), &png) {
|
||||
eprintln!("could not keep the thumbnail of {}: {e}", path.display());
|
||||
}
|
||||
app.thumbs.invalidate(path);
|
||||
}
|
||||
Err(e) => eprintln!("could not draw the thumbnail of {}: {e}", path.display()),
|
||||
}
|
||||
if cfg!(debug_assertions) {
|
||||
eprintln!("thumbnail of {} in {:.1} ms", path.display(), t.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// After a document was opened: a picture if it has none yet (one made on save is kept).
|
||||
pub fn captured_on_open(app: &mut App, path: &Path) {
|
||||
if app.shot.is_none() && platform::load_thumbnail(&cmds_recent::thumb_key(path)).is_none() {
|
||||
capture(app, path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the session's list into the preferences when a command changed it, and saves them
|
||||
/// (not in screenshot or test runs, which never write the user's preferences).
|
||||
pub fn sync(app: &mut App) {
|
||||
if app.s.recent == app.prefs.recent {
|
||||
return;
|
||||
}
|
||||
app.prefs.recent = app.s.recent.clone();
|
||||
if app.shot.is_none()
|
||||
&& let Err(e) = app.prefs.save()
|
||||
{
|
||||
app.status_err(tr!("Could not save preferences: {e}", e = e));
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's name, as the menu and the start screen show it.
|
||||
pub fn display_name(path: &Path) -> String {
|
||||
path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// The name of the folder it is in.
|
||||
pub fn folder_name(path: &Path) -> String {
|
||||
path.parent().and_then(Path::file_name).map_or_else(String::new, |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// The recent files with whether each is still there.
|
||||
pub fn entries(app: &App) -> Vec<(usize, RecentFile, bool)> {
|
||||
app.s.recent.entries().iter().enumerate().map(|(i, e)| (i, e.clone(), !cmds_recent::exists(&e.path))).collect()
|
||||
}
|
||||
|
||||
/// File › Open Recent: pinned favourites, then the last files; a missing file is greyed out
|
||||
/// with Remove beside it. Every action is a command.
|
||||
pub fn menu(app: &mut App, ui: &mut egui::Ui) {
|
||||
ui.set_min_width(320.0);
|
||||
let list = entries(app);
|
||||
if list.is_empty() {
|
||||
ui.label(text(Type::Caption, tr!("No recent files yet. Documents you open or save show here.")));
|
||||
return;
|
||||
}
|
||||
let mut act: Option<(&'static str, serde_json::Value)> = None;
|
||||
let mut last_pinned = list.first().is_some_and(|(_, e, _)| e.pinned);
|
||||
if last_pinned {
|
||||
ui.label(text(Type::Caption, tr!("Pinned")));
|
||||
}
|
||||
for (i, e, missing) in &list {
|
||||
if last_pinned && !e.pinned {
|
||||
ui.separator();
|
||||
last_pinned = false;
|
||||
}
|
||||
let name = display_name(&e.path);
|
||||
ui.horizontal(|ui| {
|
||||
let label = if *missing { tr!("{name} (missing)", name = name) } else { name.clone() };
|
||||
let r = ui.add_enabled(!*missing, egui::Button::new(label).min_size(egui::vec2(200.0, 0.0)));
|
||||
let tip = e.path.display().to_string();
|
||||
let r = if *missing { r.on_disabled_hover_text(tr!("{path} is no longer there", path = tip)) } else { r.on_hover_text(tip) };
|
||||
if r.clicked() {
|
||||
act = Some(("file.open_recent", json!({"index": i})));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if *missing {
|
||||
if ui.small_button(tr!("Remove")).on_hover_text(tr!("Take it off the list")).clicked() {
|
||||
act = Some(("prefs.recent_remove", json!({"index": i})));
|
||||
}
|
||||
} else if ui.small_button(if e.pinned { tr!("Unpin") } else { tr!("Pin") }).on_hover_text(if e.pinned { tr!("Let it move down the list again") } else { tr!("Keep it at the top of the list") }).clicked() {
|
||||
act = Some(("prefs.recent_pin", json!({"index": i})));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr!("Clear Recent Files")).on_hover_text(tr!("Pinned files stay")).clicked() {
|
||||
act = Some(("prefs.recent_clear", json!({})));
|
||||
}
|
||||
if let Some((id, params)) = act {
|
||||
// Opening keeps the menu's promise; pinning and removing keep the menu open.
|
||||
if id == "file.open_recent" {
|
||||
ui.close();
|
||||
}
|
||||
open_or_run(app, id, params);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a recent-files command from a menu or the start screen; opening goes through
|
||||
/// `request`, so unsaved work asks first.
|
||||
pub fn open_or_run(app: &mut App, id: &str, params: serde_json::Value) {
|
||||
if id == "file.open_recent" {
|
||||
app.request(id, params);
|
||||
} else if let Some(v) = app.run(id, params)
|
||||
&& id == "prefs.recent_clear"
|
||||
{
|
||||
let n = v["removed"].as_u64().unwrap_or(0) as usize;
|
||||
app.status_ok(trn!("Cleared {n} recent file", "Cleared {n} recent files", n));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sample entries for screenshot and test runs (`--open start`): two documents made from the
|
||||
/// samples in a scratch folder (one pinned), and one that is missing. Their pictures stay in
|
||||
/// memory; nothing goes into the settings folder.
|
||||
pub fn sample_entries(app: &mut App) {
|
||||
let folder = std::env::temp_dir().join("AniCraft samples"); // i18n-exempt: a folder name
|
||||
let _ = anicraft_engine::vfs::create_dir_all(&folder);
|
||||
let docs = [("Bouncing ball.anicraft", Some(anicraft_engine::doc::sample::demo()), true), ("Title card.anicraft", Some(anicraft_engine::doc::sample::interactive()), false), ("Old walk cycle.anicraft", None, false)]; // i18n-exempt: sample file names
|
||||
let mut list = anicraft_engine::cmds_recent::RecentFiles::default();
|
||||
for (name, doc, pinned) in docs.into_iter().rev() {
|
||||
let path = folder.join(name);
|
||||
match doc {
|
||||
Some(doc) => {
|
||||
if let Ok(png) = cmds_recent::thumbnail_png(&doc) {
|
||||
app.thumbs.seeded.insert(cmds_recent::thumb_key(&path), png);
|
||||
}
|
||||
let _ = anicraft_engine::format::save(&doc, &path);
|
||||
}
|
||||
None => {
|
||||
let _ = anicraft_engine::vfs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
list.add(&path);
|
||||
if pinned {
|
||||
let _ = list.pin(&path, true);
|
||||
}
|
||||
}
|
||||
app.s.recent = list;
|
||||
}
|
||||
@@ -264,6 +264,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let cam_geo = crate::camera_tool::Geo { origin: st_origin, zoom: st_zoom, stage_rect, preview };
|
||||
// Library items dragged onto the stage land at the pointer (ADR 0053).
|
||||
crate::library::stage_drop(app, ui, &resp, to_stage, preview);
|
||||
// Files dropped from the desktop land here too (ADR 0059).
|
||||
app.drop.stage = Some(crate::drop::StageGeo { canvas, origin, zoom, paused: preview });
|
||||
|
||||
|
||||
// ---- tools ----------------------------------------------------------------------------
|
||||
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
//! The start screen (ADR 0059): what AniCraft shows when it starts without a document to open,
|
||||
//! as Animate's Home screen does. New with stage-size presets (and a custom size), Open, the
|
||||
//! recent files with their pictures, and the sample animation. It takes the place of the
|
||||
//! workspace, never sits over it as a dialog: the menus keep working, Esc goes back to the
|
||||
//! document, and New, Open or a recent file dismisses it once the document is there.
|
||||
|
||||
use crate::a11y::{self, Named};
|
||||
use crate::app::App;
|
||||
use crate::icons::{self, Icon};
|
||||
use crate::theme::{T, TARGET, Type, color, font, text};
|
||||
use egui::{Align2, Rect, Sense, Stroke, StrokeKind, Vec2, WidgetType, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
/// A New preset: its name (English, translated where drawn), stage width and height.
|
||||
pub struct Preset {
|
||||
pub name: &'static str,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
/// The sizes artists start from most: video in HD and Full HD, square and vertical social posts.
|
||||
pub const PRESETS: [Preset; 4] = [
|
||||
Preset { name: tr_noop!("HD video"), width: 1280, height: 720 },
|
||||
Preset { name: tr_noop!("Full HD video"), width: 1920, height: 1080 },
|
||||
Preset { name: tr_noop!("Square post"), width: 1080, height: 1080 },
|
||||
Preset { name: tr_noop!("Vertical story"), width: 1080, height: 1920 },
|
||||
];
|
||||
|
||||
/// The frame rates offered for a new document.
|
||||
pub const RATES: [f32; 5] = [12.0, 24.0, 25.0, 30.0, 60.0];
|
||||
|
||||
/// What the start screen holds between frames: the custom size being typed.
|
||||
pub struct StartScreen {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: f32,
|
||||
}
|
||||
|
||||
impl Default for StartScreen {
|
||||
fn default() -> Self {
|
||||
let d = anicraft_engine::doc::Stage::default();
|
||||
StartScreen { width: d.width, height: d.height, fps: d.fps }
|
||||
}
|
||||
}
|
||||
|
||||
/// `file.new`'s params for a size and rate.
|
||||
pub fn new_params(width: u32, height: u32, fps: f32) -> serde_json::Value {
|
||||
json!({"width": width, "height": height, "fps": fps})
|
||||
}
|
||||
|
||||
/// Shows the start screen (File › Start Screen, and at launch).
|
||||
pub fn open(app: &mut App) {
|
||||
app.playing = false;
|
||||
app.start = Some(StartScreen { fps: app.s.doc.stage.fps, ..StartScreen::default() });
|
||||
app.status_ok(tr!("Pick a size to start a new animation, or open one you made. Esc goes back to the document."));
|
||||
}
|
||||
|
||||
/// The start screen in the space the workspace normally takes.
|
||||
pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
if ui.input(|i| i.key_pressed(egui::Key::Escape)) && !app.modal_open() {
|
||||
app.start = None;
|
||||
return;
|
||||
}
|
||||
let ctx = ui.ctx().clone();
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
let width = ui.available_width().min(1120.0);
|
||||
let pad = ((ui.available_width() - width) / 2.0).max(24.0);
|
||||
ui.add_space(28.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(pad);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(width - 48.0);
|
||||
header(app, ui, &ctx);
|
||||
ui.add_space(20.0);
|
||||
ui.columns(2, |cols| {
|
||||
if let [left, right] = cols {
|
||||
new_column(app, left);
|
||||
open_column(app, right, &ctx);
|
||||
}
|
||||
});
|
||||
ui.add_space(16.0);
|
||||
footer(app, ui);
|
||||
});
|
||||
});
|
||||
ui.add_space(28.0);
|
||||
});
|
||||
}
|
||||
|
||||
fn header(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::Image::new((crate::app::app_mark(ctx).id(), vec2(44.0, 44.0))));
|
||||
ui.add_space(8.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.label(text(Type::Title, "AniCraft")); // i18n-exempt: the product name
|
||||
ui.label(text(Type::Caption, tr!("Version {version} · {stage}", version = env!("CARGO_PKG_VERSION"), stage = crate::i18n::t(crate::app::RELEASE_STAGE))));
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let back = ui.add(egui::Button::new(tr!("Back to the document")).shortcut_text(text(Type::Key, "Esc"))); // i18n-exempt: a key name
|
||||
if back.on_hover_text(tr!("The document that is open stays as it is")).clicked() {
|
||||
app.start = None;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// A preset tile: the stage's shape drawn to scale, its name and size.
|
||||
fn tile(ui: &mut egui::Ui, name: &str, w: u32, h: u32) -> egui::Response {
|
||||
let size = vec2(118.0, 112.0);
|
||||
let (r, resp) = ui.allocate_exact_size(size, Sense::click());
|
||||
let size_text = format!("{w} × {h}");
|
||||
a11y::control(ui, &resp, WidgetType::Button, &tr!("New {name}, {size}", name = name, size = size_text), None);
|
||||
let p = ui.painter();
|
||||
let hot = resp.hovered() || resp.has_focus();
|
||||
p.rect_filled(r, T.rc(), if hot { T.hover } else { T.panel_alt });
|
||||
p.rect_stroke(r, T.rc(), Stroke::new(1.0, if hot { T.accent } else { T.border }), StrokeKind::Inside);
|
||||
// The stage's aspect, in a 64-point box.
|
||||
let box_ = Rect::from_center_size(pos2(r.center().x, r.top() + 38.0), vec2(64.0, 52.0));
|
||||
let aspect = w.max(1) as f32 / h.max(1) as f32;
|
||||
let shape = if aspect >= box_.width() / box_.height() { vec2(box_.width(), box_.width() / aspect) } else { vec2(box_.height() * aspect, box_.height()) };
|
||||
p.rect_filled(Rect::from_center_size(box_.center(), shape), crate::theme::SQUARE, T.text_faint);
|
||||
p.text(pos2(r.center().x, r.bottom() - 34.0), Align2::CENTER_CENTER, name, font(Type::Label), color(Type::Body));
|
||||
p.text(pos2(r.center().x, r.bottom() - 16.0), Align2::CENTER_CENTER, size_text, font(Type::DataSmall), T.text_dim);
|
||||
a11y::focus_ring(ui, &resp);
|
||||
resp
|
||||
}
|
||||
|
||||
fn new_column(app: &mut App, ui: &mut egui::Ui) {
|
||||
ui.label(text(Type::Heading, tr!("Create new")));
|
||||
ui.add_space(6.0);
|
||||
let fps = app.start.as_ref().map_or(24.0, |s| s.fps);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(10.0, 10.0);
|
||||
for p in &PRESETS {
|
||||
if tile(ui, crate::i18n::t(p.name), p.width, p.height).clicked() {
|
||||
app.request("file.new", new_params(p.width, p.height, fps));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(12.0);
|
||||
ui.label(text(Type::Label, tr!("Custom size")));
|
||||
let Some(st) = app.start.as_mut() else { return };
|
||||
let max = anicraft_engine::doc::MAX_STAGE_EDGE;
|
||||
let mut create = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut st.width).range(1..=max).suffix(" px")).named(tr!("Custom width")); // i18n-exempt: a unit
|
||||
ui.label(text(Type::Data, "×")); // i18n-exempt: a symbol
|
||||
ui.add(egui::DragValue::new(&mut st.height).range(1..=max).suffix(" px")).named(tr!("Custom height")); // i18n-exempt: a unit
|
||||
ui.add_space(8.0);
|
||||
egui::ComboBox::from_id_salt("start_fps")
|
||||
.selected_text(text(Type::Data, tr!("{fps} fps", fps = st.fps)))
|
||||
.show_ui(ui, |ui| {
|
||||
for r in RATES {
|
||||
ui.selectable_value(&mut st.fps, r, text(Type::Data, tr!("{fps} fps", fps = r)));
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Frame rate"));
|
||||
ui.add_space(8.0);
|
||||
create = ui.add(egui::Button::new(tr!("Create")).min_size(vec2(0.0, TARGET))).clicked();
|
||||
});
|
||||
ui.label(text(Type::Caption, tr!("The frame rate is for every new document made here. Change the size later in Modify › Document Settings.")));
|
||||
let (w, h, f) = (st.width, st.height, st.fps);
|
||||
if create {
|
||||
app.request("file.new", new_params(w, h, f));
|
||||
}
|
||||
}
|
||||
|
||||
fn open_column(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context) {
|
||||
ui.label(text(Type::Heading, tr!("Open")));
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add(egui::Button::new(tr!("Open…")).min_size(vec2(0.0, TARGET))).on_hover_text(tr!("An AniCraft document, or an Animate .fla or .xfl")).clicked() {
|
||||
app.invoke("file.open");
|
||||
}
|
||||
if ui.add(egui::Button::new(tr!("Sample animation")).min_size(vec2(0.0, TARGET))).on_hover_text(tr!("A short animation to look at and take apart")).clicked() {
|
||||
app.request("file.new_sample", json!({}));
|
||||
}
|
||||
});
|
||||
ui.label(text(Type::Caption, tr!("Or drop a document anywhere on this window.")));
|
||||
ui.add_space(14.0);
|
||||
ui.label(text(Type::Heading, tr!("Recent")));
|
||||
ui.add_space(6.0);
|
||||
let list = crate::recent::entries(app);
|
||||
if list.is_empty() {
|
||||
ui.label(text(Type::Caption, tr!("Documents you open or save show here, with a picture of their first frame.")));
|
||||
return;
|
||||
}
|
||||
let mut act: Option<(&'static str, serde_json::Value)> = None;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(10.0, 10.0);
|
||||
for (i, e, missing) in &list {
|
||||
card(app, ui, ctx, *i, e, *missing, &mut act);
|
||||
}
|
||||
});
|
||||
if let Some((id, params)) = act {
|
||||
crate::recent::open_or_run(app, id, params);
|
||||
}
|
||||
}
|
||||
|
||||
/// A recent file: its picture, name and folder. A click opens it; a missing file is dimmed with
|
||||
/// Remove; Pin keeps it first.
|
||||
fn card(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context, i: usize, e: &anicraft_engine::cmds_recent::RecentFile, missing: bool, act: &mut Option<(&'static str, serde_json::Value)>) {
|
||||
let thumb = Vec2::new(anicraft_engine::cmds_recent::THUMB_W as f32 * 0.66, anicraft_engine::cmds_recent::THUMB_H as f32 * 0.66);
|
||||
let name = crate::recent::display_name(&e.path);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(thumb.x);
|
||||
let (r, resp) = ui.allocate_exact_size(thumb, if missing { Sense::hover() } else { Sense::click() });
|
||||
let label = if missing { tr!("{name}, missing", name = name) } else if e.pinned { tr!("Open {name}, pinned", name = name) } else { tr!("Open {name}", name = name) };
|
||||
a11y::control(ui, &resp, WidgetType::Button, &label, None);
|
||||
let hot = !missing && (resp.hovered() || resp.has_focus());
|
||||
let p = ui.painter();
|
||||
p.rect_filled(r, T.rc(), T.panel_alt);
|
||||
match (!missing).then(|| app.thumbs.get(ctx, &e.path)).flatten() {
|
||||
Some(tex) => {
|
||||
let s = tex.size_vec2();
|
||||
let fit = (r.width() / s.x.max(1.0)).min(r.height() / s.y.max(1.0));
|
||||
let img = Rect::from_center_size(r.center(), s * fit);
|
||||
p.image(tex.id(), img, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE);
|
||||
}
|
||||
None => icons::paint(p, Rect::from_center_size(r.center(), vec2(28.0, 28.0)), Icon::Image, T.text_faint),
|
||||
}
|
||||
p.rect_stroke(r, T.rc(), Stroke::new(if hot { 1.5 } else { 1.0 }, if hot { T.accent } else { T.border }), StrokeKind::Inside);
|
||||
a11y::focus_ring(ui, &resp);
|
||||
let tip = e.path.display().to_string();
|
||||
let resp = if missing { resp.on_hover_text(tr!("{path} is no longer there", path = tip)) } else { resp.on_hover_text(tip) };
|
||||
if resp.clicked() {
|
||||
*act = Some(("file.open_recent", json!({"index": i})));
|
||||
}
|
||||
let c = if missing { T.text_dim } else { color(Type::Body) };
|
||||
ui.add(egui::Label::new(text(Type::Body, name.clone()).color(c)).truncate());
|
||||
ui.horizontal(|ui| {
|
||||
let note = if missing { tr!("Missing").to_string() } else if e.pinned { tr!("Pinned").to_string() } else { crate::recent::folder_name(&e.path) };
|
||||
ui.add(egui::Label::new(text(if missing || e.pinned { Type::Caption } else { Type::Path }, note).color(T.text_dim)).truncate());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if missing {
|
||||
if ui.small_button(tr!("Remove")).on_hover_text(tr!("Take it off the list")).clicked() {
|
||||
*act = Some(("prefs.recent_remove", json!({"index": i})));
|
||||
}
|
||||
} else if ui.small_button(if e.pinned { tr!("Unpin") } else { tr!("Pin") }).on_hover_text(if e.pinned { tr!("Let it move down the list again") } else { tr!("Keep it at the top of the list") }).clicked() {
|
||||
*act = Some(("prefs.recent_pin", json!({"index": i})));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn footer(app: &mut App, ui: &mut egui::Ui) {
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
let mut on = app.prefs.start_screen;
|
||||
if crate::theme::checkbox(ui, &mut on, tr!("Show this screen when AniCraft starts")).changed() {
|
||||
let mut p = app.prefs.clone();
|
||||
p.start_screen = on;
|
||||
let ctx = ui.ctx().clone();
|
||||
app.set_prefs(&ctx, p);
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(text(Type::Caption, tr!("File › Start Screen brings it back")));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_engine::Session;
|
||||
|
||||
fn app() -> (App, egui::Context) {
|
||||
let ctx = egui::Context::default();
|
||||
let app = App::with_context(&ctx, Session::new(anicraft_engine::doc::sample::demo()), Some(std::path::PathBuf::from("unused.png")));
|
||||
(app, ctx)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preset_makes_a_document_of_its_size() {
|
||||
let (mut app, _) = app();
|
||||
for p in &PRESETS {
|
||||
for fps in [24.0, 30.0] {
|
||||
crate::start::open(&mut app);
|
||||
app.request("file.new", new_params(p.width, p.height, fps));
|
||||
let st = app.s.doc.stage;
|
||||
assert_eq!((st.width, st.height, st.fps), (p.width, p.height, fps), "{}", p.name);
|
||||
assert!(app.start.is_none(), "New dismisses the start screen");
|
||||
}
|
||||
}
|
||||
let names: Vec<(u32, u32)> = PRESETS.iter().map(|p| (p.width, p.height)).collect();
|
||||
for want in [(1280, 720), (1920, 1080), (1080, 1080)] {
|
||||
assert!(names.contains(&want), "{want:?} is a preset");
|
||||
}
|
||||
// A custom size, and one past the limit that the engine refuses (the screen stays).
|
||||
crate::start::open(&mut app);
|
||||
app.request("file.new", new_params(640, 480, 12.0));
|
||||
assert_eq!((app.s.doc.stage.width, app.s.doc.stage.height, app.s.doc.stage.fps), (640, 480, 12.0));
|
||||
crate::start::open(&mut app);
|
||||
app.request("file.new", new_params(anicraft_engine::doc::MAX_STAGE_EDGE + 1, 10, 24.0));
|
||||
assert!(app.start.is_some(), "a refused New leaves the start screen up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_unsaved_work_new_asks_first_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;
|
||||
// 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));
|
||||
out.textures_delta.clear();
|
||||
assert!(app.start.is_none());
|
||||
assert!(app.s.is_dirty(), "the work is still there");
|
||||
}
|
||||
}
|
||||
+77
-1
@@ -36,6 +36,9 @@ const PICKER_ID: &str = "anicraft_file_input";
|
||||
/// Largest file taken from the picker (the engine's own limits are lower for most kinds).
|
||||
const MAX_PICK_BYTES: f64 = 512.0 * 1024.0 * 1024.0;
|
||||
|
||||
/// Files read from a drop: each one's name, and its bytes or why the browser couldn't read it.
|
||||
pub type ReadFiles = Vec<(String, Result<Vec<u8>, String>)>;
|
||||
|
||||
thread_local! {
|
||||
/// Files the picker delivered, waiting for the next frame.
|
||||
static PICKED: RefCell<Vec<Picked>> = const { RefCell::new(Vec::new()) };
|
||||
@@ -44,6 +47,12 @@ thread_local! {
|
||||
static UNSAVED: Cell<bool> = const { Cell::new(false) };
|
||||
/// Sessions whose tab is still open (they hold their lock); `None` until the browser said.
|
||||
static LIVE: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
|
||||
/// Where the pointer is over the canvas while files are dragged (CSS pixels from its
|
||||
/// top-left corner), ADR 0059: egui is told only that something hovers.
|
||||
static DRAG_POS: Cell<Option<(f32, f32)>> = const { Cell::new(None) };
|
||||
/// Dropped files read so far, by ticket: each file's name and bytes.
|
||||
static DROPPED: RefCell<Vec<(u64, ReadFiles)>> = const { RefCell::new(Vec::new()) };
|
||||
static TICKET: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Starts the editor on the page's canvas.
|
||||
@@ -75,13 +84,19 @@ async fn run() -> Result<(), String> {
|
||||
// Text needs a face to lay out with, and a page can't see the computer's fonts.
|
||||
anicraft_engine::text::Fonts::register(fonts());
|
||||
let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo());
|
||||
track_drags(&canvas);
|
||||
eframe::WebRunner::new()
|
||||
.start(
|
||||
canvas,
|
||||
eframe::WebOptions::default(),
|
||||
Box::new(move |cc| {
|
||||
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
|
||||
Ok(Box::new(crate::app::App::new(cc, session, None)))
|
||||
let mut app = crate::app::App::new(cc, session, None);
|
||||
// The start screen, unless it was switched off (ADR 0059).
|
||||
if app.prefs.start_screen {
|
||||
crate::start::open(&mut app);
|
||||
}
|
||||
Ok(Box::new(app))
|
||||
}),
|
||||
)
|
||||
.await
|
||||
@@ -169,6 +184,67 @@ pub fn take_picked() -> Option<Picked> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Keeps where the pointer is while files are dragged over the canvas (eframe's own listener
|
||||
/// tells egui only that files hover, ADR 0059).
|
||||
fn track_drags(canvas: &web_sys::HtmlCanvasElement) {
|
||||
let target = canvas.clone();
|
||||
let on_over = Closure::<dyn FnMut(web_sys::DragEvent)>::new(move |e: web_sys::DragEvent| {
|
||||
let r = target.get_bounding_client_rect();
|
||||
DRAG_POS.with(|p| p.set(Some((e.client_x() as f32 - r.left() as f32, e.client_y() as f32 - r.top() as f32))));
|
||||
});
|
||||
if canvas.add_event_listener_with_callback("dragover", on_over.as_ref().unchecked_ref()).is_ok() {
|
||||
on_over.forget();
|
||||
}
|
||||
let on_leave = Closure::<dyn FnMut(web_sys::DragEvent)>::new(|_e: web_sys::DragEvent| DRAG_POS.with(|p| p.set(None)));
|
||||
if canvas.add_event_listener_with_callback("dragleave", on_leave.as_ref().unchecked_ref()).is_ok() {
|
||||
on_leave.forget();
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the pointer was over the canvas during the drag, in CSS pixels.
|
||||
pub fn drag_pos() -> Option<(f32, f32)> {
|
||||
DRAG_POS.with(Cell::get)
|
||||
}
|
||||
|
||||
pub fn clear_drag_pos() {
|
||||
DRAG_POS.with(|p| p.set(None));
|
||||
}
|
||||
|
||||
/// Reads dropped files' bytes; they arrive together through [`take_dropped`] with the ticket
|
||||
/// returned here.
|
||||
pub fn read_dropped(files: Vec<web_sys::File>) -> u64 {
|
||||
let ticket = TICKET.with(|t| {
|
||||
t.set(t.get().wrapping_add(1));
|
||||
t.get()
|
||||
});
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let mut out = Vec::with_capacity(files.len());
|
||||
for file in files {
|
||||
let name = file.name();
|
||||
let data = if file.size() > MAX_PICK_BYTES {
|
||||
Err(tr!("it is larger than {size} MB", size = MAX_PICK_BYTES as u64 >> 20))
|
||||
} else {
|
||||
match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await {
|
||||
Ok(buf) => Ok(js_sys::Uint8Array::new(&buf).to_vec()),
|
||||
Err(_) => Err(tr!("the browser could not read it").to_string()),
|
||||
}
|
||||
};
|
||||
out.push((name, data));
|
||||
}
|
||||
DROPPED.with(|d| d.borrow_mut().push((ticket, out)));
|
||||
repaint();
|
||||
});
|
||||
ticket
|
||||
}
|
||||
|
||||
/// The next dropped files the browser finished reading.
|
||||
pub fn take_dropped() -> Option<(u64, ReadFiles)> {
|
||||
DROPPED.with(|d| {
|
||||
let mut d = d.borrow_mut();
|
||||
(!d.is_empty()).then(|| d.remove(0))
|
||||
})
|
||||
}
|
||||
|
||||
/// Offers `data` as a download named after `path`'s file name.
|
||||
pub fn download(path: &Path, data: &[u8]) {
|
||||
let name = path.file_name().map_or_else(|| "download".to_string(), |n| n.to_string_lossy().into_owned());
|
||||
|
||||
Reference in new issue
Block a user