mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-29 09:34:20 +01:00
chore: merge main (colour picker, drawing-tool and start-up fixes) into the gradient tools; one colour picker (M1)
The fill's colour picker (the Tools panel's Fill square and every Fill swatch in Properties) now starts with the fill's type (None, Solid, Linear, Radial, Bitmap): Solid is main's picker as it was; a gradient shows its stop bar, overflow, Linear RGB and focal point above the same swatches, mixer and hex, which edit the picked stop. The separate Properties Colour section is gone. Picker popups are named dialogs and the swatch grid a named control; the accessibility audit covers the swatches state too. Help text, Drag::Width's new fields and the guide pages are reconciled.
This commit is contained in:
commit
acb650a355
44 files changed
+2405
-474
No files matched your search
@@ -34,7 +34,8 @@ jobs:
|
||||
app-name: anicraft
|
||||
app-title: AniCraft
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# No WebAssembly build of the editor yet (roadmap M8).
|
||||
# The web editor builds (ADR 0036) and packaging/web/package.sh makes its zip (#210), but
|
||||
# releases don't carry it until the team decides where it is hosted: off for now.
|
||||
has-web: false
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# The web build (ADR 0036, docs/web.md), so it never regresses: every crate of the workspace
|
||||
# builds for wasm32-unknown-unknown, the engine's tests/wasm.rs runs inside WebAssembly in Node
|
||||
# (what a build can't catch: clock, thread and file calls that compile but trap), and
|
||||
# scripts/build-web.sh produces the web/ bundle. Nothing is deployed.
|
||||
# packaging/web/package.sh produces the web/ bundle and its release zip. Nothing is deployed.
|
||||
name: Web
|
||||
|
||||
on:
|
||||
@@ -52,7 +52,8 @@ jobs:
|
||||
CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner
|
||||
run: cargo test -p anicraft-engine --target wasm32-unknown-unknown --test wasm --locked
|
||||
|
||||
- name: The web editor bundle
|
||||
# The release download too (#210): what the release workflow's web job runs.
|
||||
- name: The web editor bundle and its release zip
|
||||
run: |
|
||||
scripts/build-web.sh
|
||||
ls -l web
|
||||
packaging/web/package.sh
|
||||
ls -l web dist/release
|
||||
+53
-5
@@ -3,11 +3,14 @@
|
||||
## Unreleased
|
||||
|
||||
* **Gradient editor, the Gradient Transform tool and Lock Fill** (M1, ADR 0074; #208, #203).
|
||||
* **Added**: a **Colour** section in Properties for the selected fill, or the fill swatch while
|
||||
a drawing tool is in hand: Solid colour, Linear gradient, Radial gradient or Bitmap fill; a
|
||||
bar of colour stops (click to add, drag to move, drag off to remove; arrow keys and Delete
|
||||
on a focused stop), each stop's colour, opacity, hex and position; overflow (Extend,
|
||||
Reflect, Repeat), Linear RGB and a radial gradient's focal point.
|
||||
* **Added**: gradients in the colour picker. The fill's picker (the Tools panel's Fill square,
|
||||
and every Fill swatch in Properties) starts with the fill's type: None, Solid, Linear,
|
||||
Radial or Bitmap. A gradient shows a bar of colour stops (click to add, drag to move, drag
|
||||
off to remove; arrow keys and Delete on a focused stop), overflow (Extend, Reflect, Repeat),
|
||||
Linear RGB and a radial gradient's focal point, above the same swatches, mixer and hex
|
||||
field, which then set the picked stop's colour and opacity. A gradient's swatch in
|
||||
Properties shows its ramp. One picker, as Animate has one Color panel; the fill's No Colour
|
||||
is its type None.
|
||||
* **Added**: the **Gradient Transform** tool (**F**): move, turn, stretch and resize a gradient,
|
||||
move a radial gradient's focal point, and scale, turn and skew a bitmap fill. Each drag is
|
||||
one undo step.
|
||||
@@ -18,6 +21,51 @@
|
||||
* **Improved**: gradients keep their overflow, Linear RGB, focal point and elliptical shape
|
||||
from Animate files and SVG drawings, on the GPU stage and in SVG export (HTML canvas draws
|
||||
them as near as canvas can). Radial gradients on skewed shapes are now drawn exactly.
|
||||
* **Fixed: start-up, files and display, from user reports** (M8).
|
||||
* Fixed: Flash files that opened in 0.1 no longer opening (#226). One damaged or unreadable
|
||||
part of a `.fla` (a bitmap, a sound, a library symbol) no longer stops the whole file from
|
||||
opening: the rest opens and the report says what was left out. A file double-clicked or
|
||||
opened with **Open With** that can't be opened now says why in the status bar instead of
|
||||
quietly showing the sample, and `anicraft-cli info`, `render` and the export commands open
|
||||
`.fla` and `.xfl` files too.
|
||||
* Fixed: Animate documents opening on a black stage instead of white (#163).
|
||||
* Fixed: AniCraft not opening at all on some laptops with two graphics chips, such as the
|
||||
Surface Book 2 (#207). If a way of drawing the window fails, AniCraft now tries the next one
|
||||
(on Windows: DirectX 12 on the built-in chip, then OpenGL) instead of exiting, and a start that
|
||||
crashed inside a graphics driver tries that way last next time. If nothing works, a message
|
||||
says so. A start-up log in the settings folder (`Logs/anicraft.log`) records what was tried,
|
||||
to attach to a bug report.
|
||||
* New: **Preferences › Stage › Window graphics** chooses how the window is drawn (Automatic,
|
||||
DirectX 12, Vulkan, Metal or OpenGL), for windows that flicker or flash black (#255).
|
||||
`--renderer dx12`, `vulkan` and `metal` now pick that interface; before, they all meant the
|
||||
default.
|
||||
* Fixed: the selection shading on shapes stopping part way down when zoomed in or on a big
|
||||
shape (#204). The dot pattern now covers the whole shape and its outline at any zoom, and
|
||||
costs the same however much of the screen it covers.
|
||||
* The web version's download is now built by `packaging/web/package.sh` and checked in CI; the
|
||||
README no longer suggests releases carry it yet (#210).
|
||||
* **Drawing tools and colour fixes from user reports** (M1).
|
||||
* **Fixed**: the Fill and Stroke colour squares in the Tools panel did nothing when clicked.
|
||||
They open the colour picker now, with No Colour, and recolour selected shapes (#246).
|
||||
* **Fixed**: the colour picker had no hex field. Every colour swatch's picker shows the colour
|
||||
as `#rrggbb` and takes one you type (#201).
|
||||
* **Fixed**: the colour picker had no web-safe palette. It opens on Animate's 216 web-safe
|
||||
swatches, with greys and primaries beside them and the colours you mix or type in a row
|
||||
below; **Mixer** has the full picker (#248).
|
||||
* **Fixed**: the Pencil's Properties showed a Fill swatch, though the Pencil only draws lines.
|
||||
The Pencil and the Line tool show only the stroke now (#252).
|
||||
* **Fixed**: a squiggle drawn with Object Drawing on was trapped in its object. **Modify ›
|
||||
Break Apart** (Ctrl+B) now turns a drawing object into merged drawing you can edit (#253).
|
||||
* **Fixed**: the Width tool didn't thicken a line when you dragged on it, the pointer didn't
|
||||
change, and the marker was a tiny dark box. A drag on the line widens it there, the pointer
|
||||
is a crosshair (an add pointer over a line), and the marker is a white box with handles
|
||||
(#250).
|
||||
* **Fixed**: every new line segment came with a scale gizmo whose handles couldn't be dragged,
|
||||
and a box appeared after every brush or pencil stroke. As in Animate, what you draw isn't
|
||||
left selected, and the Selection tool's box no longer shows handles that do nothing (#205,
|
||||
#243).
|
||||
* **Fixed**: Ctrl-dragging a shape's edge made a smooth curve. It adds a corner point where you
|
||||
pressed, with straight sides on a straight edge (#200).
|
||||
* **Filters, Subtract and Invert in HTML canvas export** (ADR 0072, M6). Exported web pages now
|
||||
show every filter (Drop Shadow, Blur, Glow, Bevel, Gradient Glow, Gradient Bevel and Adjust
|
||||
Color, with inner, knockout, hide object and Inner/Outer/Full) and the Subtract and Invert blend
|
||||
|
||||
@@ -273,7 +273,7 @@ RISC-V (riscv64): `anicraft-<ver>-linux-riscv64.tar.gz`, a tarball only.
|
||||
|
||||
| Build | File | Notes |
|
||||
|---|---|---|
|
||||
| Static site | `anicraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
|
||||
| Static site | `anicraft-web-<ver>.zip` | Not in the releases yet: build it yourself with `packaging/web/package.sh` ([docs/web.md](docs/web.md)), then host it on any static server |
|
||||
|
||||
## The Crafting Apps
|
||||
|
||||
|
||||
@@ -77,6 +77,12 @@ pub fn open_session(src: Option<&str>) -> Result<Session, String> {
|
||||
match src {
|
||||
None => Ok(Session::default()),
|
||||
Some("--sample") => Ok(Session::new(anicraft_doc::sample::demo())),
|
||||
// An Animate document imports as File › Open does (#226), untitled.
|
||||
Some(p) if anicraft_engine::is_animate(std::path::Path::new(p)) => {
|
||||
let mut s = Session::default();
|
||||
s.execute("file.open", &serde_json::json!({"path": p})).map_err(|e| e.to_string())?;
|
||||
Ok(s)
|
||||
}
|
||||
Some(p) => {
|
||||
let doc = format::load(std::path::Path::new(p)).map_err(|e| format!("{p}: {e}"))?;
|
||||
let mut s = Session::new(doc);
|
||||
@@ -478,6 +484,17 @@ pub fn serve<R: BufRead, W: Write>(s: &mut Session, input: R, out: &mut W) -> st
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #226: `info`, `render` and the other subcommands take an Animate document as File › Open
|
||||
/// does (an import, untitled), not only `.anicraft` files.
|
||||
#[test]
|
||||
fn subcommands_open_animate_documents() {
|
||||
let xfl = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../xfl/tests/corpus/shapes/shapes.xfl");
|
||||
let s = open_session(Some(&xfl.display().to_string())).unwrap();
|
||||
assert!(s.path.is_none() && !s.doc.timeline(0).layers.is_empty());
|
||||
let info = run(&["info".to_string(), xfl.display().to_string()]).unwrap();
|
||||
assert!(info.contains("\"layers\""), "{info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_round_trip() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, false))),
|
||||
c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, false))),
|
||||
c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name? (default: the next free “Symbol n”; a name the folder holds gets a number), kind?: graphic|movie_clip|button (default: graphic), folder?: Library folder id (default: the top level)} → {symbol, instance, name, layer, folder} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol),
|
||||
c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))),
|
||||
c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{} the selected symbol instances become their contents, text becomes shapes, and drawing objects become raw shapes that merge with the raw shapes they touch", true, |s, p| s.each_layer(false, |s| break_apart(s, p))),
|
||||
c("library.place", "Place on Stage", "", None, "{symbol | bitmap | sound: id, x?, y?} or {items: [{symbol | bitmap | sound: id}, ..], x?, y?} → {element, elements, sound?}: symbols and bitmaps centred on x, y (default: the stage centre; inside an open symbol, in its space) in the active layer's keyframe at the playhead, selected; a sound goes onto that keyframe, its span grown to fit (one sound per keyframe). One undo step", true, place),
|
||||
]
|
||||
}
|
||||
@@ -873,7 +873,21 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut fresh_ids = Vec::new();
|
||||
let kf_elements: Vec<Arc<Element>> = s.editable_keyframe()?.elements.clone();
|
||||
let mut out = Vec::new();
|
||||
// Drawing objects (Object Drawing) break apart into raw shapes, which then merge with the
|
||||
// raw shapes they touch, as in Animate (#253).
|
||||
let mut objects = Vec::new();
|
||||
for e in kf_elements {
|
||||
if let ElementKind::Shape(sh) = &e.kind
|
||||
&& !sh.merge
|
||||
&& sel.contains(&e.id)
|
||||
{
|
||||
let mut c = (*e).clone();
|
||||
if let ElementKind::Shape(sh) = &mut c.kind {
|
||||
sh.merge = true;
|
||||
}
|
||||
objects.push(c);
|
||||
continue;
|
||||
}
|
||||
// Text breaks apart into a shape with the same outlines.
|
||||
if let ElementKind::Text(t) = &e.kind
|
||||
&& sel.contains(&e.id)
|
||||
@@ -908,10 +922,13 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if fresh_ids.is_empty() {
|
||||
return Err(EngineError::State("the selection has no symbol instances or text to break apart".into()));
|
||||
if fresh_ids.is_empty() && objects.is_empty() {
|
||||
return Err(EngineError::State("the selection has no symbol instances, text or drawing objects to break apart".into()));
|
||||
}
|
||||
s.editable_keyframe()?.elements = out;
|
||||
if !objects.is_empty() {
|
||||
fresh_ids.extend(crate::merge::merge_in(s, objects)?);
|
||||
}
|
||||
s.select_only(fresh_ids.iter().copied());
|
||||
Ok(json!({"created": fresh_ids.len()}))
|
||||
}
|
||||
|
||||
@@ -67,6 +67,9 @@ pub use anicraft_plugins as plugins;
|
||||
pub use anicraft_text as text;
|
||||
pub use anicraft_geom as geom;
|
||||
pub use anicraft_render as render;
|
||||
/// Whether a path is an Animate document (`.fla`, `.xfl`, or an XFL folder) that `file.open`
|
||||
/// imports.
|
||||
pub use cmds_file::is_animate;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
|
||||
@@ -375,6 +375,41 @@ fn break_apart_works_on_each_layer() {
|
||||
assert_eq!(s.selected_layers(), vec![top, bottom]);
|
||||
}
|
||||
|
||||
/// #253: a drawing object (Object Drawing) breaks apart into raw shapes that merge with the raw
|
||||
/// drawing they touch, so it can be edited as a merged shape again; one undo step brings the
|
||||
/// object back.
|
||||
#[test]
|
||||
fn break_apart_turns_a_drawing_object_into_raw_shapes() {
|
||||
let mut s = Session::default();
|
||||
s.style.object_drawing = false;
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#00ff00", "stroke": null}));
|
||||
let raw = s.visible_elements().len();
|
||||
let obj = el_id(&run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null, "object": true})));
|
||||
let squiggle = el_id(&run(&mut s, "draw.freehand", json!({"points": [[300, 0], [320, 30], [340, 0], [360, 30]], "object": true})));
|
||||
let shapes = |s: &Session| -> Vec<(ElementId, bool)> {
|
||||
s.visible_elements().iter().filter_map(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => Some((e.id, sh.merge)),
|
||||
_ => None,
|
||||
}).collect()
|
||||
};
|
||||
assert!(shapes(&s).iter().filter(|(id, _)| [obj, squiggle].contains(id)).all(|(_, m)| !m), "drawn as objects");
|
||||
let before = s.doc.clone();
|
||||
let steps = s.history_len();
|
||||
run(&mut s, "element.select", json!({"ids": [obj.0, squiggle.0]}));
|
||||
let v = run(&mut s, "modify.break_apart", json!({}));
|
||||
assert!(v["created"].as_u64().unwrap() >= 2, "{v}");
|
||||
assert!(shapes(&s).iter().all(|(_, m)| *m), "every shape is raw now: {:?}", shapes(&s));
|
||||
assert!(!shapes(&s).iter().any(|(id, _)| *id == obj), "the object merged into the drawing");
|
||||
assert!(s.visible_elements().len() > raw + 1, "the red square cut the green one");
|
||||
assert!(!s.selection.is_empty(), "what came out of it is selected");
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc == before, "one undo brings the objects back");
|
||||
// Nothing to break apart: an error, not a no-op step.
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
assert!(s.execute("modify.break_apart", &json!({})).is_err());
|
||||
}
|
||||
|
||||
// ----- the marquee across layers with raw parts (ADR 0041) ------------------------------------
|
||||
|
||||
/// Raw squares on two layers: Top's 0..100, Bottom's 200..300 (both 0..100 high).
|
||||
|
||||
@@ -285,3 +285,56 @@ fn every_package_opens_from_a_fla_with_the_same_golden_frames() {
|
||||
{}", failures.len(), failures.join("
|
||||
"));
|
||||
}
|
||||
|
||||
/// #226: each package as a `.fla` opens as the same document through every way in: File › Open,
|
||||
/// the command line and a document the system hands over (all `file.open`), Open Recent and the
|
||||
/// start screen's list (`file.open_recent`), a drop anywhere on the window (routed to
|
||||
/// `file.open`), an upper-case extension, and a file a web browser hands over (`vfs`).
|
||||
#[test]
|
||||
fn every_entry_point_opens_the_corpus_as_a_fla() {
|
||||
use anicraft_engine::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route};
|
||||
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-entry-points");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (case, _) in FRAMES {
|
||||
let mut s = Session::default();
|
||||
s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}"));
|
||||
let bytes = pack::pack(&pack::package(&corpus().join(case)), &pack::VARIANTS[0]);
|
||||
let fla = dir.join(format!("{case}.fla"));
|
||||
std::fs::write(&fla, &bytes).unwrap();
|
||||
let upper = dir.join(format!("{case} COPY.FLA"));
|
||||
std::fs::write(&upper, &bytes).unwrap();
|
||||
let open = |path: &Path| {
|
||||
let mut t = Session::default();
|
||||
t.execute("file.open", &json!({"path": path.display().to_string()})).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
t
|
||||
};
|
||||
for path in [&fla, &upper] {
|
||||
let t = open(path);
|
||||
assert!(t.doc == s.doc, "{}: opens differently from its folder", path.display());
|
||||
assert!(t.path.is_none(), "{case}: imported untitled, so Save never writes over the Animate file");
|
||||
}
|
||||
// Open Recent reopens the Animate file it imported.
|
||||
let mut t = open(&fla);
|
||||
t.execute("file.new", &json!({})).unwrap();
|
||||
t.execute("file.open_recent", &json!({"index": 0, "confirm": true})).unwrap_or_else(|e| panic!("{case}: Open Recent: {e}"));
|
||||
assert!(t.doc == s.doc, "{case}: Open Recent opens it the same");
|
||||
// A drop anywhere opens it.
|
||||
for path in [&fla, &upper] {
|
||||
assert_eq!(kind_of(path), DropKind::Document, "{}", path.display());
|
||||
for target in [DropTarget::Stage, DropTarget::Timeline, DropTarget::Library, DropTarget::Window] {
|
||||
assert_eq!(route(kind_of(path), target), DropAction::Open, "{case} on {target:?}");
|
||||
}
|
||||
}
|
||||
// In a browser the file arrives in memory, on the thread that opens it (ADR 0036).
|
||||
let (name, data, want) = (format!("{case}.fla"), bytes.clone(), s.doc.clone());
|
||||
std::thread::spawn(move || {
|
||||
anicraft_engine::vfs::use_memory();
|
||||
anicraft_engine::vfs::put(Path::new(&name), data).unwrap();
|
||||
let mut w = Session::default();
|
||||
w.execute("file.open", &json!({"path": name})).unwrap_or_else(|e| panic!("{name} in a browser: {e}"));
|
||||
assert!(w.doc == want, "{name}: opens differently in a browser");
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
+40
-10
@@ -706,10 +706,19 @@ impl<'a> Builder<'a> {
|
||||
candidates.push(format!("bin/{data}"));
|
||||
}
|
||||
let short: String = name.rsplit('/').next().unwrap_or(name).chars().take(256).collect();
|
||||
let mut found_data = false;
|
||||
let (mut found_data, mut unreadable) = (false, false);
|
||||
let mut bitmap = None;
|
||||
for path in candidates {
|
||||
let Some(bytes) = (self.read)(&path)? else { continue };
|
||||
let bytes = match (self.read)(&path) {
|
||||
Ok(Some(bytes)) => bytes,
|
||||
Ok(None) => continue,
|
||||
// Damaged or over the archive's limits: this bitmap is left out, not
|
||||
// the whole document (#226).
|
||||
Err(_) => {
|
||||
unreadable = true;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
found_data = true;
|
||||
if let Ok(b) = Bitmap::from_image(BitmapId(0), short.clone(), bytes) {
|
||||
bitmap = Some(b);
|
||||
@@ -726,6 +735,7 @@ impl<'a> Builder<'a> {
|
||||
self.doc.bitmaps.push(Arc::new(b));
|
||||
}
|
||||
None if found_data => self.report.skip("bitmaps stored in Animate's own format"),
|
||||
None if unreadable => self.report.skip("bitmaps whose files couldn't be read"),
|
||||
None => self.report.skip("missing bitmap files"),
|
||||
}
|
||||
}
|
||||
@@ -747,10 +757,19 @@ impl<'a> Builder<'a> {
|
||||
candidates.push(format!("bin/{data}"));
|
||||
}
|
||||
let short: String = name.rsplit('/').next().unwrap_or(name).chars().take(256).collect();
|
||||
let mut found_data = false;
|
||||
let (mut found_data, mut unreadable) = (false, false);
|
||||
let mut sound = None;
|
||||
for path in candidates {
|
||||
let Some(bytes) = (self.read)(&path)? else { continue };
|
||||
let bytes = match (self.read)(&path) {
|
||||
Ok(Some(bytes)) => bytes,
|
||||
Ok(None) => continue,
|
||||
// Damaged or over the archive's limits: this sound is left out, not
|
||||
// the whole document (#226).
|
||||
Err(_) => {
|
||||
unreadable = true;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
found_data = true;
|
||||
if let Ok(s) = anicraft_doc::Sound::from_data(anicraft_doc::SoundId(0), short.clone(), bytes) {
|
||||
sound = Some(s);
|
||||
@@ -765,6 +784,7 @@ impl<'a> Builder<'a> {
|
||||
self.doc.sounds.push(Arc::new(s));
|
||||
}
|
||||
None if found_data => self.report.skip("sounds stored in Animate's own format"),
|
||||
None if unreadable => self.report.skip("sounds whose files couldn't be read"),
|
||||
None => self.report.skip("missing sound files"),
|
||||
}
|
||||
}
|
||||
@@ -805,11 +825,19 @@ impl<'a> Builder<'a> {
|
||||
if !seen.insert(href.to_string()) {
|
||||
continue;
|
||||
}
|
||||
let Some(bytes) = (self.read)(&format!("LIBRARY/{href}"))? else {
|
||||
self.report.skip("missing library files");
|
||||
continue;
|
||||
// A damaged symbol file is left out (its instances with it), not the whole
|
||||
// document (#226).
|
||||
let item = match (self.read)(&format!("LIBRARY/{href}")).map(|b| b.map(|b| xml::parse(&b))) {
|
||||
Ok(Some(Ok(item))) => item,
|
||||
Ok(None) => {
|
||||
self.report.skip("missing library files");
|
||||
continue;
|
||||
}
|
||||
Err(_) | Ok(Some(Err(_))) => {
|
||||
self.report.skip("library files that couldn't be read");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let item = xml::parse(&bytes)?;
|
||||
if item.name != "DOMSymbolItem" {
|
||||
continue;
|
||||
}
|
||||
@@ -872,7 +900,8 @@ impl<'a> Builder<'a> {
|
||||
/// used, else the first. A missing or unreadable file changes nothing: it is settings, not
|
||||
/// content.
|
||||
fn publish_settings(&mut self) -> Result<(), XflError> {
|
||||
let Some(bytes) = (self.read)("PublishSettings.xml")? else { return Ok(()) };
|
||||
// Optional: settings that can't be read leave the defaults (#226).
|
||||
let Ok(Some(bytes)) = (self.read)("PublishSettings.xml") else { return Ok(()) };
|
||||
let Ok(root) = xml::parse(&bytes) else { return Ok(()) };
|
||||
let profiles: Vec<&X> = root.children.iter().filter(|c| c.name == "flash_profile").collect();
|
||||
let profile = profiles.iter().find(|p| p.bool("current") == Some(true)).or(profiles.first()).copied().unwrap_or(&root);
|
||||
@@ -957,7 +986,8 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do
|
||||
width: root.f32("width").unwrap_or(550.0).clamp(1.0, 8192.0) as u32,
|
||||
height: root.f32("height").unwrap_or(400.0).clamp(1.0, 8192.0) as u32,
|
||||
fps: root.f32("frameRate").unwrap_or(24.0).clamp(1.0, 120.0),
|
||||
background: color(&root, "backgroundColor", "__none"),
|
||||
// Animate leaves the default, white, out of the file (#163).
|
||||
background: if root.attr("backgroundColor").is_some() { color(&root, "backgroundColor", "__none") } else { Rgba::WHITE },
|
||||
};
|
||||
b.register_folders(&root);
|
||||
b.register_bitmaps(&root)?;
|
||||
|
||||
@@ -565,3 +565,15 @@ fn sounds_in_the_package_come_across_on_frames_and_buttons_states() {
|
||||
let s = input(&doc, &s.state, &[Event::Move(anicraft_geom::Vec2::new(10.0, 10.0))], &mut NoScripts);
|
||||
assert_eq!(s.sounds.iter().map(|x| x.sound.sound).collect::<Vec<_>>(), [click]);
|
||||
}
|
||||
|
||||
/// #163: Animate leaves the default stage colour (white) out of `DOMDocument.xml`, so a file
|
||||
/// without `backgroundColor` has a white stage, not a black one.
|
||||
#[test]
|
||||
fn a_document_without_a_background_colour_has_a_white_stage() {
|
||||
let read = |p: &str| -> Result<Option<Vec<u8>>, XflError> {
|
||||
Ok((p == "DOMDocument.xml").then(|| br#"<DOMDocument xmlns="http://ns.adobe.com/xfl/2008/" frameRate="12"><timelines><DOMTimeline name="Scene 1"/></timelines></DOMDocument>"#.to_vec()))
|
||||
};
|
||||
let (doc, _) = import_with(&read).unwrap();
|
||||
assert_eq!(doc.stage.background, Rgba::WHITE);
|
||||
assert_eq!((doc.stage.width, doc.stage.height), (550, 400), "Animate's default size, also left out");
|
||||
}
|
||||
+46
-3
@@ -102,6 +102,46 @@ fn an_old_binary_fla_says_what_to_do() {
|
||||
assert_eq!(e, "not a zip archive (no end-of-directory record)");
|
||||
}
|
||||
|
||||
/// #226: one damaged part the document can do without (a bitmap's file, a library symbol) is
|
||||
/// left out and reported, and everything else opens, as it did before AniCraft read those
|
||||
/// parts; damage to `DOMDocument.xml` still refuses the file.
|
||||
#[test]
|
||||
fn damaged_parts_are_left_out_not_the_whole_document() {
|
||||
let fonts = no_fonts();
|
||||
let open = |case: &str, damage: &dyn Fn(&mut pack::Raw) -> bool| {
|
||||
let files = pack::package(&corpus().join(case));
|
||||
let (whole, _) = from_folder(&files, &fonts);
|
||||
let mut entries = pack::entries(&files, &pack::VARIANTS[0]);
|
||||
let hit = entries.iter_mut().map(damage).filter(|d| *d).count();
|
||||
assert_eq!(hit, 1, "{case}: one entry damaged");
|
||||
(whole, import_fla_with_fonts(&pack::write(&entries, false), &fonts))
|
||||
};
|
||||
let named = |e: &pack::Raw, f: &dyn Fn(&str) -> bool| f(&String::from_utf8_lossy(&e.name));
|
||||
|
||||
// A bitmap whose bytes fail their checksum.
|
||||
let (whole, got) = open("bitmaps", &|e| named(e, &|n| n.ends_with("checker.png")) && e.crc.replace(1).is_none());
|
||||
let (doc, report) = got.expect("the document opens without the damaged bitmap");
|
||||
assert_eq!(doc.bitmaps.len() + 1, whole.bitmaps.len(), "only the damaged bitmap is left out");
|
||||
assert_eq!(report.skipped.get("bitmaps whose files couldn't be read"), Some(&1), "{:?}", report.skipped);
|
||||
assert!(report.summary().contains("bitmaps whose files couldn't be read"), "{}", report.summary());
|
||||
|
||||
// A library symbol whose file is cut short (malformed XML), and one that lies about its size.
|
||||
for (how, damage) in [
|
||||
("malformed", &(|e: &mut pack::Raw| named(e, &|n| n.ends_with("Dot.xml")) && { e.body.truncate(e.body.len() / 2); true }) as &dyn Fn(&mut pack::Raw) -> bool),
|
||||
("a lying size", &|e: &mut pack::Raw| named(e, &|n| n.ends_with("Dot.xml")) && e.size.replace(3).is_none()),
|
||||
] {
|
||||
let (whole, got) = open("symbols", damage);
|
||||
let (doc, report) = got.unwrap_or_else(|e| panic!("{how}: the document opens without the damaged symbol: {e}"));
|
||||
assert_eq!(doc.library.len() + 1, whole.library.len(), "{how}");
|
||||
assert_eq!(report.skipped.get("library files that couldn't be read"), Some(&1), "{how}: {:?}", report.skipped);
|
||||
assert_eq!(doc.scenes.len(), whole.scenes.len(), "{how}");
|
||||
}
|
||||
|
||||
// The document itself damaged: refused, with a readable reason.
|
||||
let (_, got) = open("symbols", &|e| named(e, &|n| n == "DOMDocument.xml") && e.crc.replace(1).is_none());
|
||||
assert!(got.err().unwrap().to_string().contains("checksum"));
|
||||
}
|
||||
|
||||
/// A small deterministic generator (xorshift64*).
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
@@ -223,6 +263,9 @@ fn hostile_fla_archives_never_panic_and_fail_readably() {
|
||||
// Built hostile: names that leave the package, duplicates, overlaps, lying sizes.
|
||||
let mut entries = pack::entries(&files, &pack::VARIANTS[0]);
|
||||
let last = entries.len() - 1;
|
||||
// Damage to the document itself refuses the archive; damage to an optional part (a
|
||||
// bitmap, a symbol) leaves only that part out (`damaged_parts_are_left_out_…`).
|
||||
let doc = entries.iter().position(|e| e.name == b"DOMDocument.xml").unwrap();
|
||||
let edits: Vec<(&str, Edit)> = vec![
|
||||
("a .. name", Box::new(move |e| e[last].name = b"LIBRARY/../../../x.xml".to_vec())),
|
||||
("an absolute name", Box::new(move |e| e[last].name = b"/etc/x.xml".to_vec())),
|
||||
@@ -239,9 +282,9 @@ fn hostile_fla_archives_never_panic_and_fail_readably() {
|
||||
d.share = Some(1);
|
||||
e.push(d);
|
||||
})),
|
||||
("a lying size", Box::new(|e| e[1].size = Some(3))),
|
||||
("a lying checksum", Box::new(|e| e[1].crc = Some(1))),
|
||||
("a ratio bomb", Box::new(|e| e[1].size = Some(200 << 20))),
|
||||
("a lying size", Box::new(move |e| e[doc].size = Some(3))),
|
||||
("a lying checksum", Box::new(move |e| e[doc].crc = Some(1))),
|
||||
("a ratio bomb", Box::new(move |e| e[doc].size = Some(200 << 20))),
|
||||
("deep folders", Box::new(|e| e[1].name = "d/".repeat(200).into_bytes())),
|
||||
];
|
||||
for (what, edit) in &edits {
|
||||
|
||||
@@ -79,11 +79,21 @@ turned radial gradients. XFL import reported all four as approximations.
|
||||
|
||||
### Shell
|
||||
|
||||
13. **Colour, a section of Properties**, under the selected shape's rows (the selected fill), or
|
||||
under a fill tool's options (the swatch). Not a separate dock band: the dock has no room
|
||||
for it beside the Library at ordinary window heights, and Properties is where an artist
|
||||
looks for the selection's fill. It has the fill type, overflow, Linear RGB, a stop bar,
|
||||
the picked stop's colour with opacity and hex field, its position, and the focal point.
|
||||
13. **One colour picker, as Animate has one Color panel.** The colour picker (`src/colour.rs`:
|
||||
web-safe swatches, the mixer, hex, alpha) is where colours are chosen everywhere. A *fill's*
|
||||
picker (`src/colour_panel.rs`), opened from the Tools panel's Fill square or any Fill swatch
|
||||
in Properties (the selection's, or a tool's swatch), adds the fill's type on top, as
|
||||
Animate's Color Type menu: **None, Solid, Linear, Radial, Bitmap**. Solid shows the colour
|
||||
picker as it is; a gradient shows its stop bar, overflow, Linear RGB and focal point above
|
||||
the same colour picker, which then edits the picked stop's colour and opacity; a bitmap
|
||||
shows its Library image. The fill's No Colour is its type None; the Stroke square's picker
|
||||
keeps No Colour (strokes have no type). A gradient's swatch in Properties shows its ramp.
|
||||
The popup reports what was asked (`FillEdit`) and its caller applies it: solid colours and
|
||||
None exactly as each place did before (the Tools square recolours the selection with
|
||||
`element.set_fill`, a tool's swatch sets the tool style), everything else as
|
||||
`paint.set_fill` (from a tool's options with `selection: false`). An earlier draft of this
|
||||
PR had a separate Colour section in Properties; two places to choose a fill colour is what
|
||||
this decision avoids.
|
||||
14. **The stop bar** is keyboard-operable (ADR 0064): the bar is a button that adds a stop in the
|
||||
widest gap; each stop is a focusable, named control; arrow keys move it (Shift: 10 %),
|
||||
Delete removes it; dragging a stop off the bar removes it, as in Animate.
|
||||
@@ -98,8 +108,8 @@ turned radial gradients. XFL import reported all four as approximations.
|
||||
* Gradients round-trip exactly through `.anicraft`, SVG and XFL; files without the new options
|
||||
are unchanged. Radial fills on skewed shapes are now drawn exactly.
|
||||
* Scripts can build and place any gradient headless (`paint.set_fill`, `paint.transform_fill`).
|
||||
* The hex field is the panel's own (`Rgba::parse_hex`); when the shared colour picker of PR #257
|
||||
lands, the stop swatch can open it instead.
|
||||
* The colour picker popups are named dialogs for screen readers, and the swatch grid is a named
|
||||
control (the accessibility audit now covers the solid and gradient pickers).
|
||||
|
||||
## Not in this slice
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ most of them; they are always there.
|
||||
| Output | The Output panel inside Test Movie. |
|
||||
| Align | The Align section on the right, and **Modify › Align**. |
|
||||
| History | The History section on the right. |
|
||||
| Color and Swatches | The Fill and Stroke rows in Properties, and in each drawing tool's options. The **Colour** section of Properties is the Color panel's fill: type, gradient stops, overflow, Linear RGB (no saved swatches yet). |
|
||||
| Color and Swatches | Click the Fill or Stroke squares in the Tools panel, or any colour swatch in Properties: web-safe swatches, a mixer and a hex field. The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, overflow and Linear RGB, like the Color panel (no saved swatches yet). |
|
||||
| Transform and Info | Position, scale and rotation rows in Properties, and the Free Transform tool. |
|
||||
| Scene | The scene menu at the top left of the stage, **Insert › Scene** and **Modify › Scene**. |
|
||||
| Find and Replace | **Edit › Find and Replace** (**Ctrl+F**). |
|
||||
|
||||
+38
-17
@@ -70,7 +70,11 @@ Properties. The setting applies to the Rectangle, Oval, PolyStar, Line, Pen, Pen
|
||||
tools.
|
||||
|
||||
The Eraser only erases merged drawing. Drawing objects, symbols and text are left alone by
|
||||
it.
|
||||
it. To turn a drawing object back into merged drawing, select it and choose **Modify › Break
|
||||
Apart** (**Ctrl+B**): it merges with the merged shapes it touches.
|
||||
|
||||
As in Animate, what you've just drawn isn't selected, so no box gets in the way of the next
|
||||
stroke. Switch to the Selection tool (**V**) to pick it up.
|
||||
|
||||
### Selecting merged drawing
|
||||
|
||||
@@ -85,6 +89,8 @@ With the **Selection** tool (**V**) on merged drawing:
|
||||
changing anything, the drawing is whole again.
|
||||
* **Drag an unselected line** or the edge of a fill to **bend** it into a curve through the
|
||||
pointer. Its ends stay put.
|
||||
* **Ctrl-drag** (**⌘-drag** on a Mac) a line or the edge of a fill to add a **corner point**
|
||||
where you pressed and pull it into a peak: on a straight edge, both sides stay straight.
|
||||
* **Drag an unselected corner or end** to move it. Every shape that shares the point moves
|
||||
with it, so the drawing stays joined.
|
||||
* **Drag a fill** to move just that fill, without its outline. Drag anything already selected
|
||||
@@ -150,18 +156,30 @@ A line's thickness can change along its length. To give a line a profile, select
|
||||
one under **Width** in Properties: Uniform, Taper both ends, Taper start, Taper end, Bulge or
|
||||
Pinch. Set a profile in a drawing tool's options to make new lines start that way.
|
||||
|
||||
For finer control, use the **Width** tool (**U**). Hover over a line to see its width points.
|
||||
Drag a point's handle to make the line wider or narrower there (**Alt**: one side only), drag
|
||||
its dot to slide it along, or drag anywhere on the line to add a point. Click a point and
|
||||
press **Delete** to remove it.
|
||||
For finer control, use the **Width** tool (**U**); the pointer becomes a crosshair. Hover over a
|
||||
line: a white box on it shows where a drag adds a width point, and the line's points show
|
||||
their handles. Drag on the line to make it wider or narrower there, drag a point's handle to
|
||||
change it (**Alt**: one side only), or drag its dot to slide it along. Click a point and press
|
||||
**Delete** to remove it.
|
||||
|
||||
## Fills and strokes
|
||||
|
||||
### Choosing colours
|
||||
|
||||
Set the colours for new artwork in the drawing tool's options in Properties: the **Fill**
|
||||
swatch and its on/off checkbox, and the **Stroke** swatch, its checkbox and its width. The
|
||||
two squares at the bottom of the Tools panel show the current fill and stroke.
|
||||
Set the colours for new artwork with the two squares at the bottom of the Tools panel (the
|
||||
stroke's frame and the fill behind it), or in the drawing tool's options in Properties: the
|
||||
**Fill** swatch and its on/off checkbox, and the **Stroke** swatch, its checkbox and its
|
||||
width. The Pencil and the Line tool only draw lines, so they show no fill.
|
||||
|
||||
Click any colour swatch to open the colour picker. **Swatches**, the default, shows the 216
|
||||
web-safe colours with greys and primaries beside them; a shade or highlight of a colour is
|
||||
usually one cell away. The colours you mix or type are kept in the row below for this session.
|
||||
**Mixer** sets any colour by hue, saturation and brightness (and alpha where the colour has
|
||||
one). The hex field shows the colour as `#rrggbb` and takes one you type. A fill's picker
|
||||
starts with the fill's type: **None** (no fill), **Solid**, **Linear**, **Radial** or
|
||||
**Bitmap** (see [Gradients and bitmap fills](#gradients-and-bitmap-fills)); the stroke's picker
|
||||
has **No colour** instead. In the Tools panel's picker, with shapes selected, the colour you
|
||||
pick goes onto them too.
|
||||
|
||||
To recolour existing artwork, select it and change **Fill** and **Stroke** in Properties.
|
||||
For transparency, use the colour effect's **Alpha** (see
|
||||
@@ -176,17 +194,18 @@ corner can get before it's bevelled.
|
||||
|
||||
### Gradients and bitmap fills
|
||||
|
||||
The **Colour** section of Properties sets a fill's type: **Solid colour**, **Linear
|
||||
gradient**, **Radial gradient** or **Bitmap fill**. With a shape selected it changes that
|
||||
shape's fill; with a drawing tool in your hand it sets what new shapes, the Paint Bucket and
|
||||
the Brush pour.
|
||||
Choose **Linear**, **Radial** or **Bitmap** at the top of a fill's colour picker: the Tools
|
||||
panel's Fill square, or the **Fill** swatch in Properties. With a shape selected it changes
|
||||
that shape's fill; with a drawing tool in your hand, the Fill swatch in its options sets what
|
||||
new shapes, the Paint Bucket and the Brush pour. A gradient's swatch shows its ramp.
|
||||
|
||||
A gradient shows as a bar with its colour stops under it:
|
||||
|
||||
* **Click the bar** to add a stop there. **Drag a stop** to move it, or drag it down off the
|
||||
bar to remove it. A gradient has 2 to 15 stops.
|
||||
* Click a stop to edit it below the bar: its colour and opacity, its **hex** value (type
|
||||
`#rrggbb`, or `#rrggbbaa` with opacity) and its **Position**.
|
||||
* Click a stop to pick it. Its **position** and **Remove** show under the bar, and the colour
|
||||
picker below them (Swatches, Mixer, the **hex** field and **alpha**) sets its colour and
|
||||
opacity. Type `#rrggbbaa` for a colour with opacity.
|
||||
* From the keyboard, **Tab** to a stop, move it with the **arrow keys** (**Shift** for bigger
|
||||
steps) and press **Delete** to remove it. The bar itself adds a stop in the widest gap.
|
||||
* **Overflow** sets what shows past the ends: **Extend** (the end colours carry on),
|
||||
@@ -263,7 +282,8 @@ the proportions, **Alt** scales from the centre), just outside a corner to **rot
|
||||
| Remove Transform | **Modify › Transform** | **Ctrl+Shift+Z** |
|
||||
| Break Apart | **Modify** | **Ctrl+B** |
|
||||
|
||||
**Break Apart** turns text into shapes, and a symbol instance into the artwork inside it.
|
||||
**Break Apart** turns text into shapes, a symbol instance into the artwork inside it, and a
|
||||
drawing object into merged drawing.
|
||||
|
||||
## Copying, arranging and aligning
|
||||
|
||||
@@ -330,7 +350,8 @@ on its symbol (see [Symbols and the Library](symbols-and-library.md#9-slice-scal
|
||||
|
||||
## Not there yet
|
||||
|
||||
Not in AniCraft yet: rulers, a grid and guides; grouping (**Ctrl+G**); gradient and bitmap
|
||||
strokes, and saved colour and gradient swatches; PolyStar's Polygon option; the Paint Selection and Paint Inside
|
||||
Not in AniCraft yet: rulers, a grid and guides; grouping (**Ctrl+G**); gradient and bitmap strokes,
|
||||
and a Swatches panel (saved custom colours and gradients); entering a drawing object with a
|
||||
double-click; PolyStar's Polygon option; the Paint Selection and Paint Inside
|
||||
brush modes, brush libraries and tilt; erasing inside symbols; and Animate's ragged, stipple
|
||||
and hatched line styles (drawn solid when you open an Animate file).
|
||||
@@ -123,6 +123,12 @@ computers without the font.
|
||||
* Archives made by different zip tools open, large ones included.
|
||||
* A **damaged or suspicious** file fails with one sentence that names the problem, and never
|
||||
crashes AniCraft. Nothing from it is ever unpacked onto your disk.
|
||||
* When only **part** of a file is damaged (one bitmap, one sound or one library symbol), the rest
|
||||
opens and the report counts what was left out, such as "1 bitmaps whose files couldn't be
|
||||
read".
|
||||
* A document that opens without a stage colour gets Animate's default, white.
|
||||
* A document you double-click, or open with **Open With**, that can't be opened says why in the
|
||||
status bar.
|
||||
|
||||
## Tips
|
||||
|
||||
|
||||
@@ -45,6 +45,12 @@ bottom says which system you are on and where your settings are kept.
|
||||
Both settings are also in **View › Stage Rendering**, so you can switch without opening
|
||||
Preferences.
|
||||
|
||||
* **Window graphics**: how the whole window is drawn. **Automatic** (the default) tries the best
|
||||
way for your computer first and the next one if it doesn't work. If the window flickers or
|
||||
goes black, choose another way: **DirectX 12**, **Vulkan** or **OpenGL** on Windows, **Metal**
|
||||
or **OpenGL** on a Mac, **Vulkan** or **OpenGL** on Linux. A change takes effect the next time
|
||||
AniCraft starts. The note below names the start-up log to attach to a bug report.
|
||||
|
||||
### Timeline, Test Movie, Files and Safety
|
||||
|
||||
* **Timeline › Extra start gap** adds room before frame 1, on top of the room the playhead needs.
|
||||
|
||||
@@ -165,7 +165,7 @@ This page is generated from the command registry, so it always matches the versi
|
||||
- **Convert to Symbol…** `modify.convert_to_symbol` · **F8** · changes the document
|
||||
Parameters: `{name? (default: the next free “Symbol n”; a name the folder holds gets a number), kind?: graphic|movie_clip|button (default: graphic), folder?: Library folder id (default: the top level)} → {symbol, instance, name, layer, folder} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)`
|
||||
- **Break Apart** `modify.break_apart` · **Ctrl+B** (macOS **⌘B**) · changes the document
|
||||
Parameters: `{}`
|
||||
Parameters: `{} the selected symbol instances become their contents, text becomes shapes, and drawing objects become raw shapes that merge with the raw shapes they touch`
|
||||
- **Rotate 90° CW** `modify.rotate_cw` · Modify › Transform · **Ctrl+Shift+9** (macOS **⇧⌘9**) · changes the document
|
||||
Parameters: `{}`
|
||||
- **Rotate 90° CCW** `modify.rotate_ccw` · Modify › Transform · **Ctrl+Shift+7** (macOS **⇧⌘7**) · changes the document
|
||||
|
||||
@@ -8,17 +8,26 @@ On macOS, press ⌘ where this guide says Ctrl, and ⌥ where it says Alt.
|
||||
## The window won't open, or stays blank
|
||||
|
||||
AniCraft draws its window with your graphics card through a modern graphics interface (Vulkan,
|
||||
Metal or Direct3D 12). If that fails to start, which happens on some older cards, virtual
|
||||
machines and Linux setups, AniCraft tries once more with OpenGL by itself.
|
||||
Metal or DirectX 12). If that fails to start, which happens on some older cards, laptops with two
|
||||
graphics chips, virtual machines and Linux setups, AniCraft tries the next way by itself: on
|
||||
Windows, DirectX 12 on the built-in graphics chip, and then OpenGL everywhere. If a graphics
|
||||
driver crashes or hangs while AniCraft starts, the next start tries that way last.
|
||||
|
||||
If the window still opens blank or garbled, force OpenGL from a terminal:
|
||||
If no way works, AniCraft says so in a message and names its **start-up log**, a text file that
|
||||
records each way it tried and why it failed. Please attach it to your bug report. It is
|
||||
`anicraft.log` in the `Logs` folder of the [settings folder](#where-settings-live), with the
|
||||
previous run's beside it as `anicraft.previous.log`.
|
||||
|
||||
If the window opens but flickers, goes black for a moment or looks garbled, choose another way
|
||||
in **Preferences › Stage › Window graphics** (for example **DirectX 12** or **OpenGL** on
|
||||
Windows) and restart AniCraft. From a terminal, the same choice is:
|
||||
|
||||
```sh
|
||||
anicraft --renderer gl
|
||||
anicraft --renderer gl # or dx12, vulkan, metal
|
||||
```
|
||||
|
||||
To make that stick, set the environment variable `ANICRAFT_RENDERER=gl` for your account.
|
||||
`--renderer wgpu` (or `ANICRAFT_RENDERER=wgpu`) goes back to the default.
|
||||
To make it stick without Preferences, set the environment variable `ANICRAFT_RENDERER` for your
|
||||
account. `--renderer wgpu` (or `ANICRAFT_RENDERER=wgpu`) goes back to the automatic choice.
|
||||
|
||||
## The stage is slow, flickers or looks wrong
|
||||
|
||||
@@ -102,7 +111,8 @@ in one settings folder. Its path is shown at the bottom of the Preferences windo
|
||||
| Web version | the browser's storage for the site |
|
||||
|
||||
Inside it: `prefs.json` (preferences and shortcuts), `Recovery` (autosaved copies), `Templates`
|
||||
(your templates), `plugins` (installed plug-ins) and `Thumbnails` (start screen pictures).
|
||||
(your templates), `plugins` (installed plug-ins), `Thumbnails` (start screen pictures) and `Logs`
|
||||
(the start-up log).
|
||||
|
||||
To start over with default preferences, quit AniCraft and rename or delete `prefs.json`. A
|
||||
damaged preferences file never stops AniCraft from starting: it falls back to the defaults.
|
||||
|
||||
+4
-4
@@ -11,17 +11,17 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`<mask>` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 msLine truncated
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click Line truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click Line truncated
|
||||
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. |
|
||||
| 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. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. 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; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **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`, `tLine truncated
|
||||
| Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, 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), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **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 (sameLine 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), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **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. One damaged bitmap, sound or library symbol is left out and reported rather than refusing the whole file (#226), and a document without a stage colour gets Animate's default white (#163). 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, `ANICRLine 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. |
|
||||
| Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. |
|
||||
| Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). **CI on macOS and Windows** (ADR 0067): every code PR builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners besides Linux. Not yet: native macOS NSMenu, Linux arm64 and Windows ARM64 test legs on PRs, a GPU runner. Verified by hand on Windows only so far. |
|
||||
| Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). **CI on macOS and Windows** (ADR 0067): every code PR builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners besides Linux. Not yet: native macOS NSMenu, Linux arm64 and Windows ARM64 test legs on PRs, a GPU runner. Verified by hand on Windows only so far. **Robust start-up** (#207): the window opens through a list of ways (the one chosen in Preferences › Stage › Window graphics or `--renderer gl|wgpu|vulkan|dx12|metal`, then wgpu automatic, DirectX 12 on the low-power GPU on Windows, OpenGL), falling through on an error or a panic; a start that died inside a driver tries that way last next time; a start-up log (`Logs/anicraft.log` in the settings folder, the previous run's kept) records each way, the adapter and driver, panics and slow starts; a system message names it when nothing works. Not yet: verified on a hybrid-GPU laptop, the log from the Help menu. |
|
||||
| Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. **Opening documents on macOS** (ADR 0062): a double-click in Finder, a drop on the Dock icon or Open With opens the document, at launch or while running (the open-documents Apple Event through `platform.rs`, by `fmv-macos-events`, so no `unsafe` of ours), through the unsaved-changes guard; the Dock's Quit asks to save too; Windows and Linux command-line hand-over covered by a test. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, AppImage desktop integration, portable mode, store listings, video export inside the Flatpak. |
|
||||
| Documentation | **User guide, first slice** (ADR 0069, `docs/guide/`): eighteen chapters for artists (getting started to troubleshooting, and Coming from Animate), a command reference and a shortcut reference (Windows/Linux and macOS) generated from the registry and checked for freshness by tests, every link, anchor and picture checked, eight screenshots from `scripts/guide-shots.sh`. Help › User Guide opens the book bundled in the app, offline, in the browser; the web build serves it beside the editor; `anicraft-cli guide --out <folder>` writes it. Not yet: translated guides, search, a PDF edition, context help from panels, macOS and Linux screenshots. |
|
||||
| Languages | **First slice** (ADR 0040, `docs/localisation.md`): every shell string goes through `tr!`/`trn!` (keyed by its English; placeholders; CLDR plurals for whole numbers), menus translate the registry's labels when drawn (ids, CLI, MCP and the file format stay English), screen-reader names too. Catalogs are craft-i18n's TSV, read by our own parser and embedded from `CRAFT_I18N_DIR` (fallback app → shared → base language → English). Preferences › Appearance › Language (system language by default) and `--lang`. A **pseudo-locale** (`--lang pseudo`: accented, a third longer, bracketed) tests layout; checked by a source guideline test and a pseudo-locale accessibility audit; `scripts/i18n-extract.sh` writes the translators' template and per-locale coverage. Not yet: a real language (craft-i18n has no `anicraft.tsv` yet), engine messages and confirmation bodies (`@msg`), default document names, right to left (needs bidi and shaping in egui upstream), CJK and Georgian (need a font), shaped scripts. |
|
||||
@@ -41,7 +41,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 later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API 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; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); 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: spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~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); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~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; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: 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), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), next: live screen-reader passes on each platform, a light palette; ~~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); ~~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); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help). |
|
||||
| **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; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: 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, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, 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), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), next: live screen-reader passes on each platform, a light palette; ~~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); ~~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); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help). |
|
||||
|
||||
## Releases
|
||||
|
||||
|
||||
+3
-1
@@ -2,7 +2,9 @@
|
||||
|
||||
AniCraft also runs in a web browser: the same program, built for WebAssembly
|
||||
(`wasm32-unknown-unknown`), drawing into a page with WebGL2. How it is built, and why, is in
|
||||
[ADR 0036](adr/0036-web-build.md). Nothing is hosted yet; you build it and serve it yourself.
|
||||
[ADR 0036](adr/0036-web-build.md). Nothing is hosted yet and the releases don't carry it yet; you
|
||||
build it and serve it yourself. `packaging/web/package.sh` builds it and zips it as the release
|
||||
download `dist/release/anicraft-web-<version>.zip`, the static site to unzip onto a web server.
|
||||
|
||||
## Build
|
||||
|
||||
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# The web editor as a release download (#210, ADR 0036, docs/web.md):
|
||||
#
|
||||
# $DIST/anicraft-web-<version>.zip
|
||||
#
|
||||
# a static site (index.html, the loader, the module, the icon and the user guide) to unzip onto
|
||||
# any web server. This is the app's side of the family release workflow's web job
|
||||
# (storytold/craft-common-actions, `has-web`), which runs this script and uploads
|
||||
# dist/release/*; the Web CI job runs it too, so it never breaks unnoticed.
|
||||
#
|
||||
# Builds with scripts/build-web.sh; installs the wasm-bindgen CLI at the version Cargo.lock pins
|
||||
# when it is missing (the release runner has only Rust and the wasm32 target).
|
||||
set -euo pipefail
|
||||
# shellcheck source=../env.sh
|
||||
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
|
||||
cd "$ROOT"
|
||||
command -v zip >/dev/null || { echo "error: zip not found (apt install zip)" >&2; exit 1; }
|
||||
|
||||
WANT="$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' Cargo.lock)"
|
||||
if ! command -v wasm-bindgen >/dev/null || [[ "$(wasm-bindgen --version | awk '{ print $2 }')" != "$WANT" ]]; then
|
||||
cargo install wasm-bindgen-cli --version "$WANT" --locked
|
||||
fi
|
||||
|
||||
scripts/build-web.sh
|
||||
for f in index.html anicraft.js anicraft_bg.wasm anicraft.png guide/index.html; do
|
||||
[[ -s "web/$f" ]] || { echo "error: web/$f is missing or empty" >&2; exit 1; }
|
||||
done
|
||||
|
||||
ZIP="$DIST/anicraft-web-$VERSION.zip"
|
||||
rm -f "$ZIP"
|
||||
(cd web && zip -q -r -X "$ZIP" .)
|
||||
echo "$ZIP: $(( $(wc -c <"$ZIP" | tr -d ' ') / 1024 )) KB"
|
||||
+1
-1
@@ -374,7 +374,7 @@ mod tests {
|
||||
for tool in [Tool::Bone, Tool::Bind, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, 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", "shapebones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "brushlibrary", "brushcurve", "paintbrush"] {
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "shapebones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "brushlibrary", "brushcurve", "paintbrush"] {
|
||||
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
// Test Movie in a window of its own (ADR 0062): its controls, named in that window.
|
||||
|
||||
+38
-3
@@ -228,7 +228,8 @@ pub enum Drag {
|
||||
Eraser,
|
||||
/// Width tool: resizing (or sliding) width point `index` of shape `id`, found on subpath
|
||||
/// `sub`; `start` is its left and right width when the drag began.
|
||||
Width { id: anicraft_engine::doc::ElementId, sub: usize, index: usize, grip: crate::widthtool::Grip, start: (f32, f32) },
|
||||
/// `index` is the grabbed width point (None: one the drag adds at `t`).
|
||||
Width { id: anicraft_engine::doc::ElementId, sub: usize, index: Option<usize>, t: f32, grip: crate::widthtool::Grip, start: (f32, f32) },
|
||||
/// Gradient Transform tool (ADR 0074): dragging `grip` of shape `id`'s fill, whose frame was
|
||||
/// `frame` when the drag began at stage point `press`.
|
||||
Gradient { id: anicraft_engine::doc::ElementId, grip: crate::gradient_tool::Grip, frame: anicraft_engine::geom::Affine, press: egui::Pos2 },
|
||||
@@ -398,6 +399,8 @@ pub struct App {
|
||||
pub points: Vec<pathtools::PointRef>,
|
||||
/// Width tool: the selected width point (shape, index).
|
||||
pub width_sel: Option<(anicraft_engine::doc::ElementId, usize)>,
|
||||
/// Opens the Tools bar's fill swatch picker on the next frame (the `swatches` screenshot).
|
||||
pub open_fill_swatch: bool,
|
||||
/// The bone picked on the stage (ADR 0043; view state).
|
||||
pub bone_sel: Option<anicraft_engine::doc::BoneId>,
|
||||
/// Subselection: the selected motion path anchors, whose handles show (ADR 0030, 0038).
|
||||
@@ -627,6 +630,7 @@ impl App {
|
||||
align_to_stage: false,
|
||||
points: Vec::new(),
|
||||
width_sel: None,
|
||||
open_fill_swatch: false,
|
||||
bone_sel: None,
|
||||
motion_anchors: Vec::new(),
|
||||
motion_drag: None,
|
||||
@@ -725,6 +729,15 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a drawing tool's command and leaves nothing selected, as Animate's drawing tools
|
||||
/// do: the next stroke goes on without a box around the last one (#205, #243). The command
|
||||
/// itself selects what it drew, for scripts that style it next.
|
||||
pub fn draw(&mut self, id: &str, params: Value) -> Option<Value> {
|
||||
let v = self.run(id, params)?;
|
||||
let _ = self.s.execute("edit.deselect", &json!({}));
|
||||
Some(v)
|
||||
}
|
||||
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
|
||||
let result = self.s.execute(id, ¶ms);
|
||||
if platform::WEB && id.starts_with("file.") {
|
||||
@@ -1069,6 +1082,17 @@ impl App {
|
||||
crate::movie_explorer::expand_to(self, 3);
|
||||
}
|
||||
Some("about") => self.show_about = true,
|
||||
Some("selectzoom") => {
|
||||
// #204: a raw rectangle with a wide outline, selected and zoomed in far past the
|
||||
// window: the selection pattern covers all of it, down to the bottom.
|
||||
self.run("layer.new", json!({}));
|
||||
self.run("draw.rect", json!({"x": 60, "y": 40, "w": 840, "h": 460, "fill": "#e8594f", "stroke": "#7a1f1a", "stroke_width": 24, "object": false}));
|
||||
self.run("edit.select_all", json!({}));
|
||||
self.tool = Tool::Select;
|
||||
self.view.fit = false;
|
||||
self.view.zoom = 4.0;
|
||||
self.view.pan = egui::vec2(1820.0, 1030.0);
|
||||
}
|
||||
Some("zoom") => {
|
||||
// 300% on the ball: many tiles, edges cross shapes (seam check).
|
||||
self.view.fit = false;
|
||||
@@ -1820,6 +1844,10 @@ impl App {
|
||||
self.tl_drag = timeline::TlDrag::Span { layer: l.id, start: k.start, end: k.end(), to: k.end() + 6 };
|
||||
}
|
||||
}
|
||||
Some("swatches") => {
|
||||
// The fill swatch's colour picker open.
|
||||
self.open_fill_swatch = true;
|
||||
}
|
||||
Some("width") => {
|
||||
// A tapered brush-like stroke being shaped with the Width tool: one width point
|
||||
// pushed out on its left side and selected.
|
||||
@@ -1835,8 +1863,8 @@ impl App {
|
||||
Some(which @ ("gradient" | "gradientbucket")) => {
|
||||
// The gradient tools (ADR 0074): a reflecting linear gradient turned on a panel,
|
||||
// and an oval with a stretched radial gradient and its focal point off centre,
|
||||
// selected with the Gradient Transform tool (its handles show) while the Colour
|
||||
// panel edits its stops.
|
||||
// selected with the Gradient Transform tool (its handles show) while the colour
|
||||
// picker edits its stops.
|
||||
self.perform("file.new", json!({"width": 640, "height": 400}));
|
||||
self.run("draw.rect", json!({"x": 0, "y": 0, "w": 640, "h": 400, "fill": "#14213d", "stroke": null}));
|
||||
self.run("draw.rect", json!({"x": 40, "y": 60, "w": 200, "h": 280, "stroke": null}));
|
||||
@@ -1846,6 +1874,11 @@ impl App {
|
||||
self.run("paint.set_fill", json!({"type": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 0.45, "color": "#8ecae6"}, {"offset": 1, "color": "#023047"}], "focal": 0.55}));
|
||||
self.run("paint.transform_fill", json!({"scale_x": 1.1, "scale_y": 0.8, "rotate": -35}));
|
||||
self.tool = Tool::GradientTransform;
|
||||
if which == "gradient" {
|
||||
// The colour picker open on it, in gradient mode: the stop bar, overflow and
|
||||
// the picked stop's colour.
|
||||
self.open_fill_swatch = true;
|
||||
}
|
||||
if which == "gradientbucket" {
|
||||
// The Paint Bucket in hand, nothing selected: the swatch's gradient and Lock Fill.
|
||||
self.run("edit.deselect", json!({}));
|
||||
@@ -2898,6 +2931,8 @@ impl eframe::App for App {
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.frame(ui);
|
||||
// A few frames drawn: the window started (#207).
|
||||
crate::startup::frame();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -256,14 +256,14 @@ pub fn commit(app: &mut App, xf: Xf) {
|
||||
params["unit"] = json!(xf.unit());
|
||||
params["as_stroke"] = json!(as_stroke);
|
||||
if as_stroke {
|
||||
if let Some(v) = app.run("draw.brush", params)
|
||||
if let Some(v) = app.draw("draw.brush", params)
|
||||
&& v["width_points"].as_u64().is_some_and(|n| n > 1)
|
||||
{
|
||||
app.status_ok(tr!("A line whose width you can shape with the Width tool."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(v) = app.run("draw.brush", params)
|
||||
if let Some(v) = app.draw("draw.brush", params)
|
||||
&& v["elements"].as_array().is_some_and(Vec::is_empty)
|
||||
{
|
||||
app.status_ok(tr!("Nothing to paint behind there: Paint Behind only paints empty areas."));
|
||||
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
//! Colour swatches and the colour picker (#201, #246, #248), as Animate's swatch popup: a click
|
||||
//! on a swatch opens the web-safe palette with the colours used lately below it, a hex field,
|
||||
//! and the full mixer (hue, saturation and value, alpha) one click away.
|
||||
//!
|
||||
//! The 216 web-safe colours are the open standard cube (each channel 00, 33, 66, 99, CC or FF),
|
||||
//! laid out as the usual six-by-six blocks: red steps across the blocks, green down a block and
|
||||
//! blue across it. A column of greys and primaries sits on its left.
|
||||
//!
|
||||
//! View state only: what a colour is used for is the caller's (a tool's swatch, or a command).
|
||||
|
||||
use crate::a11y::Named;
|
||||
use crate::theme::{T, Type, text, to_color32, with_type};
|
||||
use anicraft_engine::doc::Rgba;
|
||||
use egui::{Color32, Id, Pos2, Rect, Response, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
|
||||
/// One palette cell, in points.
|
||||
const CELL: f32 = 14.0;
|
||||
/// Columns of the web-safe palette, and its rows.
|
||||
const COLS: usize = 18;
|
||||
const ROWS: usize = 12;
|
||||
/// Most colours kept in the recent row.
|
||||
const RECENT: usize = COLS + 1;
|
||||
|
||||
/// The channel steps of the web-safe cube.
|
||||
const STEPS: [u8; 6] = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff];
|
||||
|
||||
/// The web-safe colour at `row` (0..12), `col` (0..18): blocks of six by six, red by block,
|
||||
/// green down the block, blue across it.
|
||||
pub fn web_safe(row: usize, col: usize) -> Option<[u8; 3]> {
|
||||
if row >= ROWS || col >= COLS {
|
||||
return None;
|
||||
}
|
||||
let red = (row / 6) * 3 + col / 6;
|
||||
Some([*STEPS.get(red)?, *STEPS.get(row % 6)?, *STEPS.get(col % 6)?])
|
||||
}
|
||||
|
||||
/// The column left of the palette: greys from black to white, then the primaries and
|
||||
/// secondaries.
|
||||
const SIDE: [[u8; 3]; ROWS] = [
|
||||
[0x00, 0x00, 0x00],
|
||||
[0x33, 0x33, 0x33],
|
||||
[0x66, 0x66, 0x66],
|
||||
[0x99, 0x99, 0x99],
|
||||
[0xcc, 0xcc, 0xcc],
|
||||
[0xff, 0xff, 0xff],
|
||||
[0xff, 0x00, 0x00],
|
||||
[0x00, 0xff, 0x00],
|
||||
[0x00, 0x00, 0xff],
|
||||
[0xff, 0xff, 0x00],
|
||||
[0x00, 0xff, 0xff],
|
||||
[0xff, 0x00, 0xff],
|
||||
];
|
||||
|
||||
/// `#rrggbb`, or `#rrggbbaa` when `alpha` and it isn't opaque.
|
||||
pub fn to_hex(c: [u8; 4], alpha: bool) -> String {
|
||||
if alpha && c[3] != 255 {
|
||||
format!("#{:02x}{:02x}{:02x}{:02x}", c[0], c[1], c[2], c[3])
|
||||
} else {
|
||||
format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `rgb`, `rrggbb` or (with `alpha`) `rgba`, `rrggbbaa`, with or without one `#`, and
|
||||
/// spaces around it. The alpha is opaque unless given.
|
||||
pub fn parse_hex(s: &str, alpha: bool) -> Option<[u8; 4]> {
|
||||
let s = s.trim();
|
||||
let s = s.strip_prefix('#').unwrap_or(s);
|
||||
if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let digit = |i: usize| s.get(i..i + 1).and_then(|d| u8::from_str_radix(d, 16).ok());
|
||||
let pair = |i: usize| s.get(i..i + 2).and_then(|d| u8::from_str_radix(d, 16).ok());
|
||||
match (s.len(), alpha) {
|
||||
(3, _) => Some([digit(0)? * 17, digit(1)? * 17, digit(2)? * 17, 255]),
|
||||
(4, true) => Some([digit(0)? * 17, digit(1)? * 17, digit(2)? * 17, digit(3)? * 17]),
|
||||
(6, _) => Some([pair(0)?, pair(2)?, pair(4)?, 255]),
|
||||
(8, true) => Some([pair(0)?, pair(2)?, pair(4)?, pair(6)?]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn c32(c: [u8; 4]) -> Color32 {
|
||||
to_color32(Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0))
|
||||
}
|
||||
|
||||
/// What the picker shows first: the swatches (Animate's default) or the mixer.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default)]
|
||||
enum View {
|
||||
#[default]
|
||||
Swatches,
|
||||
Mixer,
|
||||
}
|
||||
|
||||
/// The colours used lately, newest first, and the popup that added the newest (a drag in the
|
||||
/// mixer or typing in the hex field changes that one entry instead of adding one per step).
|
||||
#[derive(Clone, Default)]
|
||||
struct Recent {
|
||||
colours: Vec<[u8; 3]>,
|
||||
from: Option<Id>,
|
||||
}
|
||||
|
||||
fn recent_id() -> Id {
|
||||
Id::new("anicraft.colour.recent")
|
||||
}
|
||||
|
||||
fn remember(ctx: &egui::Context, popup: Id, c: [u8; 3]) {
|
||||
ctx.data_mut(|d| {
|
||||
let r: &mut Recent = d.get_temp_mut_or_default(recent_id());
|
||||
if r.from == Some(popup) && !r.colours.is_empty() {
|
||||
r.colours.remove(0);
|
||||
}
|
||||
r.colours.retain(|q| *q != c);
|
||||
r.colours.insert(0, c);
|
||||
r.colours.truncate(RECENT);
|
||||
r.from = Some(popup);
|
||||
});
|
||||
}
|
||||
|
||||
/// A new popup opening adds its first change as a new recent colour.
|
||||
pub(crate) fn new_session(ctx: &egui::Context) {
|
||||
ctx.data_mut(|d| d.get_temp_mut_or_default::<Recent>(recent_id()).from = None);
|
||||
}
|
||||
|
||||
/// A swatch button for an opaque colour: a click opens the picker. `changed()` when the colour
|
||||
/// changed this frame. Name it with `Named::named`.
|
||||
pub fn button(ui: &mut egui::Ui, c: &mut [u8; 3]) -> Response {
|
||||
let mut full = [c[0], c[1], c[2], 255];
|
||||
let r = button_inner(ui, &mut full, false);
|
||||
*c = [full[0], full[1], full[2]];
|
||||
r
|
||||
}
|
||||
|
||||
/// A swatch button for a colour with alpha (unmultiplied).
|
||||
pub fn button_alpha(ui: &mut egui::Ui, c: &mut [u8; 4]) -> Response {
|
||||
button_inner(ui, c, true)
|
||||
}
|
||||
|
||||
fn button_inner(ui: &mut egui::Ui, c: &mut [u8; 4], alpha: bool) -> Response {
|
||||
let size = ui.spacing().interact_size;
|
||||
let (rect, mut resp) = ui.allocate_exact_size(size, Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::new(egui::WidgetType::ColorButton));
|
||||
let popup = resp.id.with("colour_popup");
|
||||
let open = egui::Popup::is_id_open(ui.ctx(), popup);
|
||||
if ui.is_rect_visible(rect) {
|
||||
let v = if open { &ui.visuals().widgets.open } else { ui.style().interact(&resp) };
|
||||
let rect = rect.expand(v.expansion);
|
||||
egui::color_picker::show_color_at(ui.painter(), c32(*c), rect.shrink(1.0));
|
||||
ui.painter().rect_stroke(rect, T.rc(), Stroke::new(1.0, if open || resp.hovered() { T.selection } else { T.border }), StrokeKind::Inside);
|
||||
}
|
||||
if popup_for(ui, &resp, popup, c, alpha, None) {
|
||||
resp.mark_changed();
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
/// Opens the picker under `anchor` when it is clicked, and shows it while open. True when the
|
||||
/// colour changed. `none`, when given, offers No Colour (true: none); picking a colour turns it
|
||||
/// off again.
|
||||
pub fn popup_for(ui: &egui::Ui, anchor: &Response, popup: Id, c: &mut [u8; 4], alpha: bool, none: Option<&mut bool>) -> bool {
|
||||
if anchor.clicked() {
|
||||
new_session(ui.ctx());
|
||||
}
|
||||
let mut changed = false;
|
||||
let shown = egui::Popup::menu(anchor).id(popup).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
|
||||
changed = picker(ui, popup, c, alpha, none);
|
||||
});
|
||||
if let Some(r) = shown {
|
||||
name_popup(&r.response, tr!("Colour picker"));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Names a picker popup for screen readers: a dialog holding the picker's controls.
|
||||
pub(crate) fn name_popup(r: &Response, name: &str) {
|
||||
r.ctx.accesskit_node_builder(r.id, |node| {
|
||||
node.set_role(egui::accesskit::Role::Dialog);
|
||||
node.set_label(name);
|
||||
});
|
||||
}
|
||||
|
||||
/// The picker itself: swatches or mixer, then the colour, its hex and its alpha.
|
||||
pub(crate) fn picker(ui: &mut egui::Ui, popup: Id, c: &mut [u8; 4], alpha: bool, none: Option<&mut bool>) -> bool {
|
||||
let view_id = Id::new("anicraft.colour.view");
|
||||
let mut view: View = ui.data(|d| d.get_temp(view_id)).unwrap_or_default();
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
let before = view;
|
||||
ui.selectable_value(&mut view, View::Swatches, tr!("Swatches")).on_hover_text(tr!("The web-safe palette and the colours used lately"));
|
||||
ui.selectable_value(&mut view, View::Mixer, tr!("Mixer")).on_hover_text(tr!("Any colour: hue, saturation and brightness"));
|
||||
if view != before {
|
||||
ui.data_mut(|d| d.insert_temp(view_id, view));
|
||||
}
|
||||
if let Some(none) = none {
|
||||
ui.separator();
|
||||
if ui.selectable_label(*none, tr!("No colour")).on_hover_text(tr!("Draw without this colour")).clicked() {
|
||||
*none = !*none;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
match view {
|
||||
View::Swatches => {
|
||||
if let Some(p) = swatches(ui, [c[0], c[1], c[2]]) {
|
||||
*c = [p[0], p[1], p[2], c[3]];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
View::Mixer => {
|
||||
let mut m = c32(*c);
|
||||
ui.spacing_mut().slider_width = (CELL * (COLS + 1) as f32).max(200.0);
|
||||
let a = if alpha { egui::color_picker::Alpha::OnlyBlend } else { egui::color_picker::Alpha::Opaque };
|
||||
if egui::color_picker::color_picker_color32(ui, &mut m, a) {
|
||||
let [r, g, b, al] = m.to_srgba_unmultiplied();
|
||||
*c = [r, g, b, if alpha { al } else { 255 }];
|
||||
remember(ui.ctx(), popup, [r, g, b]);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(CELL * 2.0, CELL * 1.5), Sense::hover());
|
||||
egui::color_picker::show_color_at(ui.painter(), c32(*c), r);
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, T.border), StrokeKind::Inside);
|
||||
if let Some(h) = hex_field(ui, popup, c, alpha) {
|
||||
*c = h;
|
||||
remember(ui.ctx(), popup, [h[0], h[1], h[2]]);
|
||||
changed = true;
|
||||
}
|
||||
if alpha {
|
||||
let mut pct = f32::from(c[3]) / 255.0 * 100.0;
|
||||
let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).suffix(" %").max_decimals(0))).named(tr!("Alpha"));
|
||||
if r.on_hover_text(tr!("Alpha: 0 % is clear, 100 % opaque")).changed() {
|
||||
c[3] = (pct.clamp(0.0, 100.0) / 100.0 * 255.0).round() as u8;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
|
||||
/// The hex field: shows the colour, and takes a typed one as soon as it reads as a colour.
|
||||
fn hex_field(ui: &mut egui::Ui, popup: Id, c: &[u8; 4], alpha: bool) -> Option<[u8; 4]> {
|
||||
let buf_id = popup.with("hex");
|
||||
let current = to_hex(*c, alpha);
|
||||
let mut s: String = ui.data(|d| d.get_temp(buf_id)).unwrap_or_else(|| current.clone());
|
||||
let r = with_type(ui, Type::Data, |ui| ui.add(egui::TextEdit::singleline(&mut s).desired_width(if alpha { 86.0 } else { 66.0 }).char_limit(10)));
|
||||
let r = r.named(tr!("Hex colour")).on_hover_text(if alpha { tr!("Hex colour: #rrggbb, or #rrggbbaa with alpha") } else { tr!("Hex colour: #rrggbb") });
|
||||
let mut out = None;
|
||||
if r.has_focus() || r.lost_focus() {
|
||||
if r.changed()
|
||||
&& let Some(p) = parse_hex(&s, alpha)
|
||||
&& p != *c
|
||||
{
|
||||
out = Some(p);
|
||||
}
|
||||
if r.lost_focus() {
|
||||
// Back to the colour it holds (an unreadable entry is dropped).
|
||||
ui.data_mut(|d| d.remove::<String>(buf_id));
|
||||
} else {
|
||||
ui.data_mut(|d| d.insert_temp(buf_id, s));
|
||||
}
|
||||
} else {
|
||||
ui.data_mut(|d| d.remove::<String>(buf_id));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The palette grid (side column, a gap, the web-safe cube) and the recent row under it.
|
||||
/// Returns the colour clicked.
|
||||
fn swatches(ui: &mut egui::Ui, current: [u8; 3]) -> Option<[u8; 3]> {
|
||||
let recent: Vec<[u8; 3]> = ui.data(|d| d.get_temp::<Recent>(recent_id())).map(|r| r.colours).unwrap_or_default();
|
||||
let gap = CELL * 0.5;
|
||||
let width = CELL * (COLS + 1) as f32 + gap;
|
||||
let height = CELL * (ROWS + 1) as f32 + gap;
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click());
|
||||
let painter = ui.painter_at(rect.expand(2.0));
|
||||
let o = rect.min;
|
||||
// Each cell: where it is, and its colour.
|
||||
let mut cells: Vec<(Rect, [u8; 3])> = Vec::with_capacity(ROWS * (COLS + 1) + RECENT);
|
||||
for (row, side) in SIDE.iter().enumerate() {
|
||||
let y = o.y + CELL * row as f32;
|
||||
cells.push((Rect::from_min_size(pos2(o.x, y), vec2(CELL, CELL)), *side));
|
||||
for col in 0..COLS {
|
||||
if let Some(c) = web_safe(row, col) {
|
||||
cells.push((Rect::from_min_size(pos2(o.x + CELL + gap + CELL * col as f32, y), vec2(CELL, CELL)), c));
|
||||
}
|
||||
}
|
||||
}
|
||||
let ry = o.y + CELL * ROWS as f32 + gap;
|
||||
for (i, c) in recent.iter().enumerate().take(RECENT) {
|
||||
cells.push((Rect::from_min_size(pos2(o.x + CELL * i as f32 + if i > 0 { gap } else { 0.0 }, ry), vec2(CELL, CELL)), *c));
|
||||
}
|
||||
// The palette's own grid lines are the gaps between cells, in the panel's border colour.
|
||||
let grid = Rect::from_min_size(o, vec2(width, CELL * ROWS as f32));
|
||||
painter.rect_filled(grid, 0.0, T.border);
|
||||
for (r, c) in &cells {
|
||||
painter.rect_filled(r.shrink(0.5), 0.0, c32([c[0], c[1], c[2], 255]));
|
||||
}
|
||||
if recent.is_empty() {
|
||||
painter.text(pos2(o.x, ry + CELL * 0.5), egui::Align2::LEFT_CENTER, tr!("Colours you mix or type show here"), crate::theme::font(Type::Caption), T.text_faint);
|
||||
}
|
||||
let hit = |p: Pos2| cells.iter().find(|(r, _)| r.contains(p)).copied();
|
||||
if let Some((r, _)) = cells.iter().find(|(_, c)| *c == current) {
|
||||
painter.rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, T.on_active), StrokeKind::Middle);
|
||||
}
|
||||
let hovered = resp.hover_pos().and_then(hit);
|
||||
if let Some((r, c)) = hovered {
|
||||
painter.rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, T.selection), StrokeKind::Middle);
|
||||
resp.clone().on_hover_text(text(Type::Data, to_hex([c[0], c[1], c[2], 255], false)));
|
||||
}
|
||||
// One control for the whole grid (a click picks the cell under the pointer).
|
||||
crate::a11y::control(ui, &resp, egui::WidgetType::Button, tr!("Colour swatches"), None);
|
||||
if resp.clicked() { resp.interact_pointer_pos().and_then(hit).map(|(_, c)| c) } else { None }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hex_reads_short_long_and_alpha_forms() {
|
||||
assert_eq!(parse_hex("#ff8000", false), Some([255, 128, 0, 255]));
|
||||
assert_eq!(parse_hex(" FF8000 ", false), Some([255, 128, 0, 255]));
|
||||
assert_eq!(parse_hex("#f80", false), Some([255, 136, 0, 255]));
|
||||
assert_eq!(parse_hex("#ff800080", true), Some([255, 128, 0, 128]));
|
||||
assert_eq!(parse_hex("#f808", true), Some([255, 136, 0, 136]));
|
||||
for bad in ["", "#", "#ff80", "#ff800080", "##ff8000", "#gg0000", "#+f0000", "#ff 800", "#ff8000ff00"] {
|
||||
assert_eq!(parse_hex(bad, false), None, "{bad:?}");
|
||||
}
|
||||
assert_eq!(parse_hex("#ff80008", true), None);
|
||||
// What the field shows reads back as the same colour.
|
||||
for c in [[0, 0, 0, 255], [18, 52, 86, 255], [255, 255, 255, 7]] {
|
||||
assert_eq!(parse_hex(&to_hex(c, true), true), Some(c));
|
||||
}
|
||||
assert_eq!(to_hex([1, 2, 3, 4], false), "#010203", "no alpha where the colour has none");
|
||||
}
|
||||
|
||||
/// #248: the 216 web-safe colours, each once, black at the top left and white where the
|
||||
/// last block ends (the open standard's cube).
|
||||
#[test]
|
||||
fn the_palette_is_the_web_safe_cube() {
|
||||
let mut all: Vec<[u8; 3]> = (0..ROWS).flat_map(|r| (0..COLS).filter_map(move |c| web_safe(r, c))).collect();
|
||||
assert_eq!(all.len(), 216);
|
||||
assert!(all.iter().all(|c| c.iter().all(|v| STEPS.contains(v))));
|
||||
assert_eq!(web_safe(0, 0), Some([0, 0, 0]));
|
||||
assert_eq!(web_safe(11, 17), Some([255, 255, 255]));
|
||||
assert_eq!(web_safe(0, 6), Some([0x33, 0, 0]), "red steps across the blocks");
|
||||
assert_eq!(web_safe(1, 0), Some([0, 0x33, 0]), "green down a block");
|
||||
assert_eq!(web_safe(0, 1), Some([0, 0, 0x33]), "blue across it");
|
||||
assert_eq!(web_safe(12, 0), None);
|
||||
assert_eq!(web_safe(0, 18), None);
|
||||
all.sort_unstable();
|
||||
all.dedup();
|
||||
assert_eq!(all.len(), 216, "no colour twice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_colours_keep_one_entry_per_popup_session() {
|
||||
let ctx = egui::Context::default();
|
||||
let (a, b) = (Id::new("a"), Id::new("b"));
|
||||
let list = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<Recent>(recent_id())).map(|r| r.colours).unwrap_or_default();
|
||||
// A drag in the mixer: one entry, the last colour.
|
||||
for v in [10, 20, 30] {
|
||||
remember(&ctx, a, [v, 0, 0]);
|
||||
}
|
||||
assert_eq!(list(&ctx), vec![[30, 0, 0]]);
|
||||
// Another popup adds one, newest first; the same colour again moves to the front.
|
||||
remember(&ctx, b, [0, 0, 9]);
|
||||
new_session(&ctx);
|
||||
remember(&ctx, b, [30, 0, 0]);
|
||||
assert_eq!(list(&ctx), vec![[30, 0, 0], [0, 0, 9]]);
|
||||
new_session(&ctx);
|
||||
for v in 0..40u8 {
|
||||
new_session(&ctx);
|
||||
remember(&ctx, a, [v, v, v]);
|
||||
}
|
||||
assert_eq!(list(&ctx).len(), RECENT, "bounded");
|
||||
}
|
||||
}
|
||||
+275
-148
@@ -1,31 +1,43 @@
|
||||
//! The Colour panel (ADR 0074): the fill's type (solid colour, linear or radial gradient,
|
||||
//! bitmap), a gradient's colour stops on a bar, its overflow (Extend, Reflect, Repeat), Linear
|
||||
//! RGB and focal point, and a bitmap fill's image.
|
||||
//! The fill side of the colour picker (ADR 0074): one picker, as Animate has one Color panel.
|
||||
//!
|
||||
//! It edits the selected shapes' fill when one is selected, else the fill swatch (what new
|
||||
//! shapes, the Paint Bucket and the Brush pour). Every change is `paint.set_fill`, which sets
|
||||
//! both, so agents and the CLI work the same way; drags are one undo step.
|
||||
//! The Tools panel's Fill square and every Fill swatch in Properties open the same popup. Its
|
||||
//! top row is the fill's type (None, Solid, Linear, Radial, Bitmap). A solid fill shows the
|
||||
//! colour picker (`crate::colour`: web-safe swatches, the mixer, hex). A gradient shows its stop
|
||||
//! bar, overflow, Linear RGB and focal point above that same picker, which then edits the picked
|
||||
//! stop's colour and opacity. A bitmap fill shows the Library image it uses. The Stroke square
|
||||
//! opens the colour picker alone (strokes are one colour).
|
||||
//!
|
||||
//! The popup says what was asked ([`FillEdit`]); its caller applies it: a solid colour or None
|
||||
//! the way that place always has, anything else as `paint.set_fill`, which sets the fill swatch
|
||||
//! and the selected fills in one step, so agents and the CLI work the same way.
|
||||
|
||||
use crate::a11y::{self, Named};
|
||||
use crate::app::App;
|
||||
use crate::theme::{T, Type, text, to_color32, with_type};
|
||||
use anicraft_engine::doc::{ElementKind, GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Spread, ramp_at};
|
||||
use egui::{Key, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
|
||||
use egui::{Id, Key, Rect, Response, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// How far (screen points) a stop dragged off the bar must go to be removed.
|
||||
const TEAR_OFF: f32 = 26.0;
|
||||
/// The stop bar's width: the colour picker's swatch grid under it.
|
||||
const BAR_WIDTH: f32 = 270.0;
|
||||
|
||||
fn row(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui)) {
|
||||
crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, label, |ui| with_type(ui, Type::Data, add));
|
||||
/// What the fill picker asks for.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum FillEdit {
|
||||
/// A solid colour (opaque).
|
||||
Solid([u8; 3]),
|
||||
/// No fill (true), or a fill again (false).
|
||||
None(bool),
|
||||
/// `paint.set_fill` params, with its undo label; `live` while a drag or typing goes on (one
|
||||
/// undo step for all of it).
|
||||
Set { label: &'static str, live: bool, params: Value },
|
||||
}
|
||||
|
||||
fn row_prose(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui)) {
|
||||
crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, label, add);
|
||||
}
|
||||
|
||||
/// The fill the panel shows: the first selected shape's on the active layer, else the swatch.
|
||||
fn current(app: &App) -> (Paint, bool) {
|
||||
/// The fill the pickers show: the first selected shape's on the active layer, else the swatch.
|
||||
/// True when it is the selection's.
|
||||
pub fn current(app: &App) -> (Paint, bool) {
|
||||
let selected = app.s.selected_elements().into_iter().filter(|(l, _)| *l == app.s.layer).find_map(|(_, e)| match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.fill.clone(),
|
||||
_ => None,
|
||||
@@ -36,6 +48,27 @@ fn current(app: &App) -> (Paint, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Library's bitmaps, for a bitmap fill: `(id, name)`.
|
||||
pub fn bitmaps(app: &App) -> Vec<(u64, String)> {
|
||||
app.s.doc.bitmaps.iter().map(|b| (b.id.0, b.name.clone())).collect()
|
||||
}
|
||||
|
||||
/// Applies `edit` as `paint.set_fill` (`selection`: also to the selected fills). Solid and None
|
||||
/// edits are the caller's (each place keeps its own rule for those).
|
||||
pub fn apply_set(app: &mut App, edit: &FillEdit, selection: bool) {
|
||||
if let FillEdit::Set { label, live, params } = edit {
|
||||
let mut p = params.clone();
|
||||
if !selection && let Some(o) = p.as_object_mut() {
|
||||
o.insert("selection".into(), json!(false));
|
||||
}
|
||||
if *live {
|
||||
crate::panels::live(app, label, "paint.set_fill", p);
|
||||
} else {
|
||||
app.run("paint.set_fill", p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
|
||||
fn hex(c: Rgba) -> String {
|
||||
let c = c.sanitized();
|
||||
@@ -46,121 +79,170 @@ fn stops_json(stops: &[GradientStop]) -> Value {
|
||||
json!(stops.iter().map(|s| json!({"offset": s.offset.clamp(0.0, 1.0), "color": hex(s.color)})).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Runs `paint.set_fill`: a drag or typing (`live`) coalesces into one undo step.
|
||||
fn set(app: &mut App, label: &str, live: bool, p: Value) {
|
||||
if live {
|
||||
crate::panels::live(app, label, "paint.set_fill", p);
|
||||
} else {
|
||||
app.run("paint.set_fill", p);
|
||||
fn bytes(c: Rgba) -> [u8; 4] {
|
||||
let c = c.sanitized();
|
||||
let b = |v: f32| (v * 255.0).round() as u8;
|
||||
[b(c.r), b(c.g), b(c.b), b(c.a)]
|
||||
}
|
||||
|
||||
fn from_bytes(c: [u8; 4]) -> Rgba {
|
||||
Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0)
|
||||
}
|
||||
|
||||
/// Paints `paint` into `r`: a colour, a gradient's ramp, a bitmap's mark, or the empty field
|
||||
/// with a slash for no fill.
|
||||
fn paint_preview(p: &egui::Painter, r: Rect, paint: Option<&Paint>) {
|
||||
match paint {
|
||||
None => {
|
||||
p.rect_filled(r, 0.0, T.field);
|
||||
p.line_segment([r.left_bottom(), r.right_top()], Stroke::new(1.5, T.danger));
|
||||
}
|
||||
Some(Paint::Solid(c)) => egui::color_picker::show_color_at(p, to_color32(*c), r),
|
||||
Some(Paint::Bitmap { .. }) => {
|
||||
p.rect_filled(r, 0.0, T.text_faint);
|
||||
crate::icons::paint(p, r.shrink(2.0), crate::icons::Icon::Image, T.panel);
|
||||
}
|
||||
Some(g) => {
|
||||
let stops = g.stops().unwrap_or(&[]);
|
||||
let mut mesh = egui::Mesh::default();
|
||||
let steps = 24u32;
|
||||
for i in 0..=steps {
|
||||
let t = i as f32 / steps as f32;
|
||||
let c = to_color32(ramp_at(stops, t));
|
||||
let x = r.left() + t * r.width();
|
||||
mesh.colored_vertex(pos2(x, r.top()), c);
|
||||
mesh.colored_vertex(pos2(x, r.bottom()), c);
|
||||
if i > 0 {
|
||||
let k = 2 * i;
|
||||
mesh.add_triangle(k - 2, k - 1, k);
|
||||
mesh.add_triangle(k - 1, k, k + 1);
|
||||
}
|
||||
}
|
||||
p.add(mesh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A colour swatch with opacity and its hex field. True when either changed `c`.
|
||||
fn colour_field(ui: &mut egui::Ui, c: &mut Rgba, name: &str) -> bool {
|
||||
let mut changed = crate::panels::alpha_swatch(ui, c, name);
|
||||
// The field keeps what is being typed while it has focus; it applies as soon as it parses.
|
||||
let id = ui.id().with(("hex", name));
|
||||
let mut s: String = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| hex(*c));
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(78.0).char_limit(9).font(egui::TextStyle::Monospace)).named(&tr!("{name} (hex)", name = name));
|
||||
if r.changed()
|
||||
&& let Some(v) = Rgba::parse_hex(&s)
|
||||
{
|
||||
*c = v;
|
||||
changed = true;
|
||||
/// A fill swatch for Properties: shows the fill (a gradient as its ramp) and opens the fill
|
||||
/// picker. Name it with `Named::named`.
|
||||
pub fn swatch(ui: &mut egui::Ui, paint: Option<&Paint>, bitmaps: &[(u64, String)]) -> (Response, Option<FillEdit>) {
|
||||
let size = ui.spacing().interact_size;
|
||||
let (rect, mut resp) = ui.allocate_exact_size(size, Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::new(WidgetType::ColorButton));
|
||||
let popup = resp.id.with("colour_popup");
|
||||
let open = egui::Popup::is_id_open(ui.ctx(), popup);
|
||||
if ui.is_rect_visible(rect) {
|
||||
paint_preview(ui.painter(), rect.shrink(1.0), paint);
|
||||
ui.painter().rect_stroke(rect, T.rc(), Stroke::new(1.0, if open || resp.hovered() { T.selection } else { T.border }), StrokeKind::Inside);
|
||||
}
|
||||
if r.has_focus() {
|
||||
ui.data_mut(|d| d.insert_temp(id, s));
|
||||
} else {
|
||||
ui.data_mut(|d| d.remove::<String>(id));
|
||||
let edit = popup_for(ui, &resp, popup, paint, bitmaps);
|
||||
if edit.is_some() {
|
||||
resp.mark_changed();
|
||||
}
|
||||
changed
|
||||
(resp, edit)
|
||||
}
|
||||
|
||||
pub fn panel(app: &mut App, ui: &mut egui::Ui) {
|
||||
let (paint, selected) = current(app);
|
||||
ui.label(text(Type::Caption, if selected { tr!("The selected fill") } else { tr!("The fill swatch: new shapes, the Paint Bucket and the Brush") }));
|
||||
ui.add_space(2.0);
|
||||
// The type, as Animate's Color Type menu.
|
||||
let kinds = [("solid", tr!("Solid colour")), ("linear", tr!("Linear gradient")), ("radial", tr!("Radial gradient")), ("bitmap", tr!("Bitmap fill"))];
|
||||
/// Opens the fill picker under `anchor` when it is clicked, and shows it while open. `paint`
|
||||
/// is the fill (`None`: no fill).
|
||||
pub fn popup_for(ui: &egui::Ui, anchor: &Response, popup: Id, paint: Option<&Paint>, bitmaps: &[(u64, String)]) -> Option<FillEdit> {
|
||||
if anchor.clicked() {
|
||||
crate::colour::new_session(ui.ctx());
|
||||
}
|
||||
let mut edit = None;
|
||||
let shown = egui::Popup::menu(anchor).id(popup).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
|
||||
edit = fill_picker(ui, popup, paint, bitmaps);
|
||||
});
|
||||
if let Some(r) = shown {
|
||||
crate::colour::name_popup(&r.response, tr!("Fill colour picker"));
|
||||
}
|
||||
edit
|
||||
}
|
||||
|
||||
/// The kinds of fill on the type row, as Animate's Color Type menu: key, label, what it is.
|
||||
fn kinds() -> [(&'static str, &'static str, &'static str); 5] {
|
||||
[
|
||||
("none", tr!("None"), tr!("No fill")),
|
||||
("solid", tr!("Solid"), tr!("Solid colour")),
|
||||
("linear", tr!("Linear"), tr!("Linear gradient: colours along a line")),
|
||||
("radial", tr!("Radial"), tr!("Radial gradient: colours out from a centre")),
|
||||
("bitmap", tr!("Bitmap"), tr!("Bitmap fill: a Library image, tiled")),
|
||||
]
|
||||
}
|
||||
|
||||
/// The picker's body: the type row, then what that type has.
|
||||
pub fn fill_picker(ui: &mut egui::Ui, popup: Id, paint: Option<&Paint>, bitmaps: &[(u64, String)]) -> Option<FillEdit> {
|
||||
let now = match paint {
|
||||
Paint::Solid(_) => "solid",
|
||||
Paint::Linear { .. } => "linear",
|
||||
Paint::Radial { .. } => "radial",
|
||||
Paint::Bitmap { .. } => "bitmap",
|
||||
None => "none",
|
||||
Some(Paint::Solid(_)) => "solid",
|
||||
Some(Paint::Linear { .. }) => "linear",
|
||||
Some(Paint::Radial { .. }) => "radial",
|
||||
Some(Paint::Bitmap { .. }) => "bitmap",
|
||||
};
|
||||
let mut pick = now;
|
||||
row_prose(ui, tr!("Type"), |ui| {
|
||||
egui::ComboBox::from_id_salt("fill_type")
|
||||
.width(150.0)
|
||||
.selected_text(kinds.iter().find(|k| k.0 == now).map_or("", |k| k.1))
|
||||
.show_ui(ui, |ui| {
|
||||
for (key, label) in &kinds {
|
||||
ui.selectable_value(&mut pick, *key, *label);
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Fill type"));
|
||||
ui.horizontal(|ui| {
|
||||
for (key, label, tip) in kinds() {
|
||||
let usable = key != "bitmap" || !bitmaps.is_empty();
|
||||
let r = ui.add_enabled(usable, egui::Button::selectable(pick == key, label)).named(&tr!("Fill type: {kind}", kind = tip));
|
||||
let r = if usable { r.on_hover_text(tip) } else { r.on_disabled_hover_text(tr!("Import an image into the Library first (File › Import › Import to Library), then fill with it.")) };
|
||||
if r.clicked() {
|
||||
pick = key;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
if pick != now {
|
||||
if pick == "bitmap" {
|
||||
match app.s.doc.bitmaps.first().map(|b| b.id) {
|
||||
Some(b) => set(app, tr_noop!("Fill"), false, json!({"type": "bitmap", "bitmap": b.0})),
|
||||
None => app.status_err(tr!("Import an image into the Library first (File › Import › Import to Library), then fill with it.")),
|
||||
}
|
||||
} else {
|
||||
set(app, tr_noop!("Fill"), false, json!({"type": pick}));
|
||||
}
|
||||
return;
|
||||
return Some(match pick {
|
||||
"none" => FillEdit::None(true),
|
||||
"solid" => match paint {
|
||||
// A fill again: the colour it shows.
|
||||
None => FillEdit::None(false),
|
||||
Some(p) => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "solid", "color": hex(p.primary_color().with_alpha(1.0))}) },
|
||||
},
|
||||
"bitmap" => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "bitmap", "bitmap": bitmaps.first().map_or(0, |b| b.0)}) },
|
||||
other => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": other}) },
|
||||
});
|
||||
}
|
||||
match &paint {
|
||||
Paint::Solid(c) => {
|
||||
let mut c = *c;
|
||||
row(ui, tr!("Colour"), |ui| {
|
||||
if colour_field(ui, &mut c, tr!("Fill colour")) {
|
||||
set(app, tr_noop!("Fill colour"), true, json!({"type": "solid", "color": hex(c)}));
|
||||
}
|
||||
});
|
||||
match paint {
|
||||
None => {
|
||||
ui.label(text(Type::Caption, tr!("No fill. Choose a type above to fill again.")));
|
||||
None
|
||||
}
|
||||
Paint::Linear { stops, spread, linear_rgb, .. } | Paint::Radial { stops, spread, linear_rgb, .. } => {
|
||||
gradient_rows(app, ui, stops, *spread, *linear_rgb);
|
||||
if let Paint::Radial { focal, .. } = &paint {
|
||||
let mut pct = focal * 100.0;
|
||||
row(ui, tr!("Focal point"), |ui| {
|
||||
let lim = MAX_FOCAL * 100.0;
|
||||
let r = ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(0.5).range(-lim..=lim).max_decimals(0)).named(tr!("Focal point")).on_hover_text(tr!("Where the ramp starts, from the centre along the gradient's axis (drag the triangle with the Gradient Transform tool)"));
|
||||
if r.changed() {
|
||||
set(app, tr_noop!("Focal point"), true, json!({"focal": (pct / 100.0).clamp(-MAX_FOCAL, MAX_FOCAL)}));
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(Paint::Solid(c)) => {
|
||||
let mut px = bytes(*c);
|
||||
crate::colour::picker(ui, popup, &mut px, false, None).then_some(FillEdit::Solid([px[0], px[1], px[2]]))
|
||||
}
|
||||
Paint::Bitmap { bitmap, .. } => {
|
||||
let current = *bitmap;
|
||||
let choices: Vec<(u64, String)> = app.s.doc.bitmaps.iter().map(|b| (b.id.0, b.name.clone())).collect();
|
||||
let mut want = current.0;
|
||||
row_prose(ui, tr!("Bitmap"), |ui| {
|
||||
egui::ComboBox::from_id_salt("fill_bitmap")
|
||||
.width(150.0)
|
||||
.selected_text(choices.iter().find(|c| c.0 == current.0).map_or_else(|| tr!("missing bitmap").to_string(), |c| c.1.clone()))
|
||||
Some(Paint::Linear { stops, spread, linear_rgb, .. }) => gradient(ui, popup, stops, *spread, *linear_rgb, None),
|
||||
Some(Paint::Radial { stops, spread, linear_rgb, focal, .. }) => gradient(ui, popup, stops, *spread, *linear_rgb, Some(*focal)),
|
||||
Some(Paint::Bitmap { bitmap, .. }) => {
|
||||
let current = bitmap.0;
|
||||
let mut want = current;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr!("Bitmap"));
|
||||
egui::ComboBox::from_id_salt(popup.with("fill_bitmap"))
|
||||
.width(180.0)
|
||||
.selected_text(bitmaps.iter().find(|c| c.0 == current).map_or_else(|| tr!("missing bitmap").to_string(), |c| c.1.clone()))
|
||||
.show_ui(ui, |ui| {
|
||||
for (id, name) in &choices {
|
||||
for (id, name) in bitmaps {
|
||||
ui.selectable_value(&mut want, *id, name.as_str());
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Fill bitmap"));
|
||||
});
|
||||
if want != current.0 {
|
||||
set(app, tr_noop!("Fill"), false, json!({"type": "bitmap", "bitmap": want}));
|
||||
}
|
||||
ui.label(text(Type::Caption, tr!("Scale, turn and skew it with the Gradient Transform tool (F).")));
|
||||
(want != current).then(|| FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "bitmap", "bitmap": want}) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Overflow, Linear RGB, the stop bar and the picked stop's colour and position.
|
||||
fn gradient_rows(app: &mut App, ui: &mut egui::Ui, stops: &[GradientStop], spread: Spread, linear_rgb: bool) {
|
||||
/// A gradient: overflow, Linear RGB and the focal point, the stop bar, the picked stop's
|
||||
/// position, and the colour picker for its colour.
|
||||
fn gradient(ui: &mut egui::Ui, popup: Id, stops: &[GradientStop], spread: Spread, linear_rgb: bool, focal: Option<f32>) -> Option<FillEdit> {
|
||||
let set = |label: &'static str, live: bool, params: Value| Some(FillEdit::Set { label, live, params });
|
||||
let mut out = None;
|
||||
let mut sp = spread;
|
||||
row_prose(ui, tr!("Overflow"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr!("Overflow"));
|
||||
for (s, label, tip) in [
|
||||
(Spread::Pad, tr!("Extend"), tr!("Past its ends the gradient keeps its end colours")),
|
||||
(Spread::Reflect, tr!("Reflect"), tr!("Past its ends the gradient mirrors back and forth")),
|
||||
@@ -170,18 +252,30 @@ fn gradient_rows(app: &mut App, ui: &mut egui::Ui, stops: &[GradientStop], sprea
|
||||
}
|
||||
});
|
||||
if sp != spread {
|
||||
set(app, tr_noop!("Overflow"), false, json!({"spread": sp.key()}));
|
||||
out = set(tr_noop!("Overflow"), false, json!({"spread": sp.key()}));
|
||||
}
|
||||
let mut lin = linear_rgb;
|
||||
row_prose(ui, tr!("Blending"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let mut lin = linear_rgb;
|
||||
if crate::theme::checkbox(ui, &mut lin, tr!("Linear RGB")).on_hover_text(tr!("Mix the colours in linear light: brighter, more even blends")).changed() {
|
||||
set(app, tr_noop!("Linear RGB"), false, json!({"linear_rgb": lin}));
|
||||
out = set(tr_noop!("Linear RGB"), false, json!({"linear_rgb": lin}));
|
||||
}
|
||||
if let Some(f) = focal {
|
||||
ui.add_space(8.0);
|
||||
ui.label(tr!("Focal point"));
|
||||
let mut pct = f * 100.0;
|
||||
let lim = MAX_FOCAL * 100.0;
|
||||
let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(0.5).range(-lim..=lim).max_decimals(0)));
|
||||
if r.named(tr!("Focal point")).on_hover_text(tr!("Where the ramp starts, from the centre along the gradient's axis (drag the triangle with the Gradient Transform tool)")).changed() {
|
||||
out = set(tr_noop!("Focal point"), true, json!({"focal": (pct / 100.0).clamp(-MAX_FOCAL, MAX_FOCAL)}));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let mut edited = stops.to_vec();
|
||||
if let Some(label) = stop_bar(ui, &mut edited) {
|
||||
set(app, label, true, json!({"stops": stops_json(&edited)}));
|
||||
if let Some((label, live)) = stop_bar(ui, popup, &mut edited) {
|
||||
out = set(label, live, json!({"stops": stops_json(&edited)}));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where stop `i` may move: between its neighbours, so the order (and the pick) stays.
|
||||
@@ -226,14 +320,15 @@ fn remove_stop(stops: &mut Vec<GradientStop>, i: usize) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// What the bar did.
|
||||
fn stop_bar(ui: &mut egui::Ui, stops: &mut Vec<GradientStop>) -> Option<&'static str> {
|
||||
let sel_id = ui.id().with("fill_stop");
|
||||
let tear_id = ui.id().with("fill_stop_tear");
|
||||
/// The bar of colour stops, the picked stop's position and its colour (the colour picker,
|
||||
/// with opacity). What changed (its undo label), and whether it is live (a drag or typing).
|
||||
fn stop_bar(ui: &mut egui::Ui, popup: Id, stops: &mut Vec<GradientStop>) -> Option<(&'static str, bool)> {
|
||||
let sel_id = popup.with("fill_stop");
|
||||
let tear_id = popup.with("fill_stop_tear");
|
||||
let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0).min(stops.len().saturating_sub(1));
|
||||
let mut changed = None;
|
||||
let can_remove = stops.len() > 2;
|
||||
let w = ui.available_width().clamp(120.0, 240.0);
|
||||
let w = BAR_WIDTH;
|
||||
let (strip, resp) = ui.allocate_exact_size(vec2(w, 18.0), Sense::click());
|
||||
a11y::control(ui, &resp, WidgetType::Button, tr!("Gradient: add a colour stop"), None);
|
||||
let resp = resp.on_hover_text(tr!("Click to add a colour stop. Drag a stop to move it, or off the bar to remove it. With a stop focused, the arrow keys move it and Delete removes it."));
|
||||
@@ -271,7 +366,7 @@ fn stop_bar(ui: &mut egui::Ui, stops: &mut Vec<GradientStop>) -> Option<&'static
|
||||
let Some(off) = stops.get(i).map(|s| s.offset) else { continue };
|
||||
let x = strip.left() + off.clamp(0.0, 1.0) * strip.width();
|
||||
let hit = Rect::from_center_size(pos2(x, track.center().y), vec2(12.0, 14.0));
|
||||
let r = ui.interact(hit, ui.id().with(("fill_stop_marker", i)), Sense::click_and_drag());
|
||||
let r = ui.interact(hit, popup.with(("fill_stop_marker", i)), Sense::click_and_drag());
|
||||
let at = format!("{:.0}", off * 100.0);
|
||||
a11y::control(ui, &r, WidgetType::Button, &tr!("Colour stop {stop} of {count} at {at}%", stop = i + 1, count = count, at = at), Some(i == sel));
|
||||
if r.clicked() || r.drag_started() || r.gained_focus() {
|
||||
@@ -286,7 +381,7 @@ fn stop_bar(ui: &mut egui::Ui, stops: &mut Vec<GradientStop>) -> Option<&'static
|
||||
tearing = off_bar.then_some(i);
|
||||
if !off_bar {
|
||||
move_stop(stops, i, (pt.x - strip.left()) / strip.width());
|
||||
changed = Some(tr_noop!("Move colour stop"));
|
||||
changed = Some((tr_noop!("Move colour stop"), true));
|
||||
}
|
||||
}
|
||||
if r.drag_stopped() && tearing == Some(i) {
|
||||
@@ -300,7 +395,7 @@ fn stop_bar(ui: &mut egui::Ui, stops: &mut Vec<GradientStop>) -> Option<&'static
|
||||
let d = if right { step } else if left { -step } else { 0.0 };
|
||||
if d != 0.0 {
|
||||
move_stop(stops, i, off + d);
|
||||
changed = Some(tr_noop!("Move colour stop"));
|
||||
changed = Some((tr_noop!("Move colour stop"), true));
|
||||
}
|
||||
if del && can_remove {
|
||||
remove = Some(i);
|
||||
@@ -328,41 +423,43 @@ fn stop_bar(ui: &mut egui::Ui, stops: &mut Vec<GradientStop>) -> Option<&'static
|
||||
let t = resp.interact_pointer_pos().map_or_else(|| widest_gap(stops), |at| (at.x - strip.left()) / strip.width());
|
||||
if let Some(i) = add_stop(stops, t) {
|
||||
sel = i;
|
||||
changed = Some(tr_noop!("Add colour stop"));
|
||||
changed = Some((tr_noop!("Add colour stop"), false));
|
||||
}
|
||||
}
|
||||
if let Some(i) = remove.take()
|
||||
&& remove_stop(stops, i)
|
||||
{
|
||||
sel = sel.min(stops.len().saturating_sub(1));
|
||||
changed = Some(tr_noop!("Remove colour stop"));
|
||||
changed = Some((tr_noop!("Remove colour stop"), false));
|
||||
}
|
||||
// The picked stop: its colour (with opacity), hex and position.
|
||||
// The picked stop: its position, then its colour in the colour picker.
|
||||
let n = stops.len();
|
||||
if let Some(st) = stops.get_mut(sel) {
|
||||
let mut c = st.color;
|
||||
row(ui, tr!("Stop colour"), |ui| {
|
||||
if colour_field(ui, &mut c, &tr!("Colour stop {stop}", stop = sel + 1)) {
|
||||
st.color = c;
|
||||
changed = Some(tr_noop!("Colour stop"));
|
||||
}
|
||||
});
|
||||
let mut pct = st.offset * 100.0;
|
||||
row(ui, tr!("Position"), |ui| {
|
||||
if ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)).named(tr!("Colour stop position")).changed() {
|
||||
ui.add_space(2.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr!("Stop {stop} at", stop = sel + 1));
|
||||
let mut pct = st.offset * 100.0;
|
||||
let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)));
|
||||
if r.named(tr!("Colour stop position")).changed() {
|
||||
st.offset = (pct / 100.0).clamp(0.0, 1.0);
|
||||
changed = Some(tr_noop!("Move colour stop"));
|
||||
changed = Some((tr_noop!("Move colour stop"), true));
|
||||
}
|
||||
if ui.add_enabled(n > 2, egui::Button::new(tr!("Remove")).small()).named(tr!("Remove colour stop")).on_hover_text(tr!("Remove this colour stop (or drag it off the bar)")).clicked() {
|
||||
remove = Some(sel);
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let mut px = bytes(st.color);
|
||||
if crate::colour::picker(ui, popup.with(("stop", sel)), &mut px, true, None) {
|
||||
st.color = from_bytes(px);
|
||||
changed = Some((tr_noop!("Colour stop"), true));
|
||||
}
|
||||
}
|
||||
if let Some(i) = remove
|
||||
&& remove_stop(stops, i)
|
||||
{
|
||||
sel = sel.min(stops.len().saturating_sub(1));
|
||||
changed = Some(tr_noop!("Remove colour stop"));
|
||||
changed = Some((tr_noop!("Remove colour stop"), false));
|
||||
}
|
||||
// Typed positions may pass a neighbour: keep the stops in order (the pick follows its stop).
|
||||
if let Some(picked) = stops.get(sel).copied() {
|
||||
@@ -377,6 +474,7 @@ fn stop_bar(ui: &mut egui::Ui, stops: &mut Vec<GradientStop>) -> Option<&'static
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::Tool;
|
||||
use anicraft_engine::geom::Vec2;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn stop(offset: f32, c: u32) -> GradientStop {
|
||||
@@ -416,37 +514,66 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill picker drawn alone for `paint`: what it asked for with no input.
|
||||
fn picker_once(paint: Option<&Paint>, bitmaps: &[(u64, String)]) -> Option<FillEdit> {
|
||||
let ctx = egui::Context::default();
|
||||
let mut edit = Some(FillEdit::None(false));
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| edit = fill_picker(ui, Id::new("test_fill"), paint, bitmaps));
|
||||
out.textures_delta.clear();
|
||||
edit
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_panel_shows_every_kind_of_fill_and_edits_through_the_command() {
|
||||
fn the_picker_shows_every_kind_of_fill_without_changing_it() {
|
||||
let two = vec![stop(0.0, 0x000000), stop(1.0, 0xffffff)];
|
||||
let bitmaps = vec![(7u64, "tile.png".to_string())];
|
||||
let mut radial = Paint::radial(Vec2::ZERO, 10.0, two.clone());
|
||||
if let Paint::Radial { focal, .. } = &mut radial {
|
||||
*focal = 0.4;
|
||||
}
|
||||
for p in [None, Some(Paint::Solid(Rgba::hex(0x3d8bfd))), Some(Paint::linear(Vec2::ZERO, Vec2::new(10.0, 0.0), two)), Some(radial), Some(Paint::Bitmap { bitmap: anicraft_engine::doc::BitmapId(7), repeat: true, matrix: anicraft_engine::geom::Affine::IDENTITY })] {
|
||||
assert_eq!(picker_once(p.as_ref(), &bitmaps), None, "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_from_the_picker_reach_the_swatch_and_the_selection() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = App::with_context(&ctx, anicraft_engine::Session::default(), Some(PathBuf::from("unused.png")));
|
||||
app.run("draw.rect", json!({"x": 10, "y": 10, "w": 100, "h": 80, "fill": "#ff0000", "stroke": null}));
|
||||
app.tool = Tool::Select;
|
||||
// Solid, linear, radial (with its focal point) and a bitmap, each drawn without fault.
|
||||
frames(&ctx, &mut app);
|
||||
assert!(matches!(current(&app), (Paint::Solid(_), true)));
|
||||
for kind in ["linear", "radial"] {
|
||||
set(&mut app, "Fill", false, json!({"type": kind, "spread": "repeat", "linear_rgb": true}));
|
||||
frames(&ctx, &mut app);
|
||||
}
|
||||
let png = anicraft_engine::render::encode_png(2, 2, &[200; 16]).unwrap_or_default();
|
||||
let id = app.s.doc.alloc_id();
|
||||
app.s.doc.bitmaps.push(std::sync::Arc::new(anicraft_engine::doc::Bitmap::from_png(anicraft_engine::doc::BitmapId(id), "tile.png", png).unwrap()));
|
||||
set(&mut app, "Fill", false, json!({"type": "bitmap", "bitmap": id}));
|
||||
frames(&ctx, &mut app);
|
||||
assert!(matches!(current(&app).0, Paint::Bitmap { .. }));
|
||||
// A live edit (a drag) is one undo step however many frames it takes.
|
||||
// A type change is one step on the selection and the swatch.
|
||||
let steps = app.s.history_len();
|
||||
apply_set(&mut app, &FillEdit::Set { label: "Fill", live: false, params: json!({"type": "radial"}) }, true);
|
||||
assert_eq!(app.s.history_len(), steps + 1);
|
||||
assert!(matches!(current(&app).0, Paint::Radial { .. }) && matches!(app.s.style.fill_paint, Some(Paint::Radial { .. })));
|
||||
// A drag of a stop's colour is one step however many frames it takes.
|
||||
let steps = app.s.history_len();
|
||||
for c in ["#112233", "#445566", "#778899"] {
|
||||
set(&mut app, "Fill colour", true, json!({"type": "solid", "color": c}));
|
||||
let stops = json!([{"offset": 0, "color": c}, {"offset": 1, "color": "#000000"}]);
|
||||
apply_set(&mut app, &FillEdit::Set { label: "Colour stop", live: true, params: json!({"stops": stops}) }, true);
|
||||
}
|
||||
app.s.end_gesture();
|
||||
assert_eq!(app.s.history_len(), steps + 1);
|
||||
// Nothing selected and a fill tool in hand: the swatch.
|
||||
// From the tool options: the swatch only.
|
||||
apply_set(&mut app, &FillEdit::Set { label: "Fill", live: false, params: json!({"type": "linear"}) }, false);
|
||||
assert!(matches!(current(&app).0, Paint::Radial { .. }), "the selection keeps its fill");
|
||||
assert!(matches!(app.s.style.fill_paint, Some(Paint::Linear { .. })));
|
||||
// Solid and None are the caller's: apply_set leaves them alone.
|
||||
let before = app.s.doc.clone();
|
||||
apply_set(&mut app, &FillEdit::Solid([1, 2, 3]), true);
|
||||
apply_set(&mut app, &FillEdit::None(true), true);
|
||||
assert!(app.s.doc == before);
|
||||
// The whole window draws with the Tools square's picker open on the selection's gradient,
|
||||
// and on the swatch with a fill tool in hand.
|
||||
app.open_fill_swatch = true;
|
||||
frames(&ctx, &mut app);
|
||||
app.run("edit.deselect", json!({}));
|
||||
app.tool = Tool::PaintBucket;
|
||||
frames(&ctx, &mut app);
|
||||
assert!(!current(&app).1);
|
||||
assert_eq!(stops_json(&[stop(0.0, 0xff0000)])[0]["color"], "#ff0000");
|
||||
assert_eq!(from_bytes(bytes(Rgba::new(1.0, 0.0, 0.0, 0.5))).a, 128.0 / 255.0);
|
||||
}
|
||||
}
|
||||
@@ -511,6 +511,26 @@ fn preferences(app: &mut App, ctx: &egui::Context) {
|
||||
form_note(ui, LW, text(Type::Caption, s));
|
||||
}
|
||||
}
|
||||
// How the window itself is drawn (#207, #255): read when AniCraft starts.
|
||||
let backends = crate::platform::window_backends(crate::platform::OS);
|
||||
if !backends.is_empty() {
|
||||
ui.add_space(4.0);
|
||||
form_row(ui, LW, tr!("Window graphics"), |ui| {
|
||||
ui.vertical(|ui| {
|
||||
for &choice in backends {
|
||||
let (name, tip) = choice.describe();
|
||||
crate::theme::radio_value(ui, &mut p.window_backend, choice, text(Type::Body, crate::i18n::t(name)));
|
||||
form_note(ui, toggle_indent, text(Type::Caption, crate::i18n::t(tip)));
|
||||
ui.add_space(2.0);
|
||||
}
|
||||
});
|
||||
});
|
||||
form_note(ui, LW, text(Type::Caption, tr!("A change takes effect the next time AniCraft starts. If a way doesn't work, AniCraft starts with the next one.")));
|
||||
if let Some(log) = crate::startup::log_path() {
|
||||
form_note(ui, LW, text(Type::Caption, tr!("If AniCraft has trouble starting, this start-up log says why (attach it to a bug report):")));
|
||||
form_note(ui, LW, text(Type::Path, log.display().to_string()));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
section(ui, "prefs_timeline", Section::Rule, tr!("Timeline"), None, |ui| {
|
||||
|
||||
+2
-2
@@ -285,11 +285,11 @@ fn query_rows(app: &mut App, ui: &mut egui::Ui) -> bool {
|
||||
}
|
||||
Kind::Color => {
|
||||
row(ui, tr!("Find"), &mut |ui| {
|
||||
ui.color_edit_button_srgb(&mut app.find.color).named(tr!("Colour to find"));
|
||||
crate::colour::button(ui, &mut app.find.color).named(tr!("Colour to find"));
|
||||
ui.label(text(Type::Data, format!("#{:02x}{:02x}{:02x}", app.find.color[0], app.find.color[1], app.find.color[2])));
|
||||
});
|
||||
row(ui, tr!("Replace with"), &mut |ui| {
|
||||
ui.color_edit_button_srgb(&mut app.find.with_color).named(tr!("Colour to replace with"));
|
||||
crate::colour::button(ui, &mut app.find.with_color).named(tr!("Colour to replace with"));
|
||||
ui.label(text(Type::Data, format!("#{:02x}{:02x}{:02x}", app.find.with_color[0], app.find.with_color[1], app.find.with_color[2])));
|
||||
});
|
||||
}
|
||||
|
||||
+9
-2
@@ -157,14 +157,21 @@ mod imp {
|
||||
{
|
||||
self.starting = None;
|
||||
match r {
|
||||
Ok(g) => self.renderer = Some(Arc::new(g)),
|
||||
Err(e) => self.state = State::Failed(e),
|
||||
Ok(g) => {
|
||||
crate::startup::line(&format!("stage on the GPU: {}", g.adapter));
|
||||
self.renderer = Some(Arc::new(g));
|
||||
}
|
||||
Err(e) => {
|
||||
crate::startup::line(&format!("the stage is drawn on the CPU: {e}"));
|
||||
self.state = State::Failed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(g) = &self.renderer
|
||||
&& let Some(e) = g.broken()
|
||||
{
|
||||
self.renderer = None;
|
||||
crate::startup::line(&format!("the GPU stage stopped, the CPU draws: {e}"));
|
||||
self.state = State::Failed(e);
|
||||
}
|
||||
if want && self.renderer.is_none() && self.starting.is_none() && !matches!(self.state, State::Failed(_)) {
|
||||
|
||||
@@ -133,7 +133,7 @@ pub fn pick(app: &mut App, at: Pos2, xf: Xf) {
|
||||
}
|
||||
app.run("element.pick", json!({"x": p.x, "y": p.y}));
|
||||
if target(app).is_none() && !app.s.selection.is_empty() {
|
||||
app.status_ok(tr!("That fill is a solid colour. Choose Linear, Radial or Bitmap in the Colour panel to give it a gradient."));
|
||||
app.status_ok(tr!("That fill is a solid colour. Click its Fill swatch and choose Linear, Radial or Bitmap to give it a gradient."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values.
|
||||
|
||||
const SOURCES: [(&str, &str); 27] = [
|
||||
const SOURCES: [(&str, &str); 28] = [
|
||||
("colour.rs", include_str!("colour.rs")),
|
||||
("drop.rs", include_str!("drop.rs")),
|
||||
("recent.rs", include_str!("recent.rs")),
|
||||
("start.rs", include_str!("start.rs")),
|
||||
|
||||
@@ -55,6 +55,8 @@ fn without_tests(src: &str) -> String {
|
||||
const NOT_UI: &[&str] = &[
|
||||
"eprintln!(", "println!(", "print!(", "panic!(", "assert", "unreachable!(", "Id::new(", "id_salt(", "persistent_id(", "json!(", "execute(", "perform(", "invoke(", ".run(", "find_command(", "#[", "env!(", "include_str!(", "include_bytes!(", "concat!(", "var(",
|
||||
"contains(", "starts_with(", "ends_with(", "strip_prefix(", "strip_suffix(", "matches!(", "== ", "!= ",
|
||||
// The start-up log (`startup::line`): English, like console messages, for bug reports.
|
||||
"line(&", "write(&format!(",
|
||||
];
|
||||
|
||||
/// Whether a prose literal outside the macros is allowed: not interface text by its context,
|
||||
|
||||
+1
-1
@@ -152,7 +152,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
});
|
||||
}
|
||||
form_row(ui, FORM_LABEL_DIALOG, tr!("Outline colour"), |ui| {
|
||||
ui.color_edit_button_srgb(&mut d.color).named(tr!("Outline colour")).on_hover_text(tr!("The colour of the layer's outlines and of its bar on the timeline"));
|
||||
crate::colour::button(ui, &mut d.color).named(tr!("Outline colour")).on_hover_text(tr!("The colour of the layer's outlines and of its bar on the timeline"));
|
||||
});
|
||||
if kind != LayerKind::Camera && kind != LayerKind::Folder {
|
||||
form_row(ui, FORM_LABEL_DIALOG, tr!("Outlines"), |ui| {
|
||||
|
||||
+71
-32
@@ -27,6 +27,7 @@ mod app;
|
||||
mod autosave;
|
||||
mod brush_panel;
|
||||
mod brushtool;
|
||||
mod colour;
|
||||
mod colour_panel;
|
||||
mod envelope;
|
||||
mod find_panel;
|
||||
@@ -64,6 +65,7 @@ mod shape_hints;
|
||||
mod stage;
|
||||
mod stage_a11y;
|
||||
mod start;
|
||||
mod startup;
|
||||
mod templates;
|
||||
mod test_movie;
|
||||
mod theme;
|
||||
@@ -77,24 +79,37 @@ use anicraft_engine::Session;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The session to start with: the file given on the command line (through `file.open`, so
|
||||
/// `.fla` / `.xfl` import works the same as from the menu), else the sample. Also the import
|
||||
/// report of an Animate document, for the status bar.
|
||||
/// What opening the command line's file said, for the status bar.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_session(file: Option<&Path>) -> (Session, Option<String>) {
|
||||
let Some(p) = file else { return (Session::new(anicraft_engine::doc::sample::demo()), None) };
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Opened {
|
||||
/// Nothing to report (no file, or an AniCraft document).
|
||||
Quiet,
|
||||
/// The import report of an Animate document.
|
||||
Imported(String),
|
||||
/// It didn't open (the sample is there instead): the file's name and why.
|
||||
Failed(String, String),
|
||||
}
|
||||
|
||||
/// The session to start with: the file given on the command line (through `file.open`, so
|
||||
/// `.fla` / `.xfl` import works the same as from the menu), else the sample. A file that can't
|
||||
/// be opened says why in the window (#226: a release build has no console, so the reason used
|
||||
/// to go nowhere and a double-clicked document seemed to open as the sample).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_session(file: Option<&Path>) -> (Session, Opened) {
|
||||
let Some(p) = file else { return (Session::new(anicraft_engine::doc::sample::demo()), Opened::Quiet) };
|
||||
let mut s = Session::default();
|
||||
match s.execute("file.open", &serde_json::json!({"path": p.display().to_string()})) {
|
||||
Ok(v) => {
|
||||
let report = v.get("report").and_then(|r| r.as_str()).map(str::to_string);
|
||||
if let Some(r) = &report {
|
||||
println!("{r}");
|
||||
Ok(v) => match v.get("report").and_then(|r| r.as_str()) {
|
||||
Some(r) => {
|
||||
startup::line(&format!("imported {}: {r}", p.display()));
|
||||
(s, Opened::Imported(r.to_string()))
|
||||
}
|
||||
(s, report)
|
||||
}
|
||||
None => (s, Opened::Quiet),
|
||||
},
|
||||
Err(e) => {
|
||||
eprintln!("could not open {}: {e}; starting with the sample", p.display());
|
||||
(Session::new(anicraft_engine::doc::sample::demo()), None)
|
||||
startup::line(&format!("could not open {}: {e}; starting with the sample", p.display()));
|
||||
(Session::new(anicraft_engine::doc::sample::demo()), Opened::Failed(crate::recent::display_name(p), e.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -114,12 +129,11 @@ struct Look {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option<PathBuf>, open: Option<String>, look: Look) -> eframe::Result {
|
||||
let options = eframe::NativeOptions {
|
||||
fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option<PathBuf>, open: Option<String>, look: Look) -> eframe::Result {
|
||||
let options = attempt.options(eframe::NativeOptions {
|
||||
viewport: platform::viewport(egui::ViewportBuilder::default().with_title("AniCraft").with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])),
|
||||
renderer,
|
||||
..Default::default()
|
||||
};
|
||||
});
|
||||
// The embedded interface font joins the text library before anything lays text out:
|
||||
// opening an Animate document from the command line lays its text out right here.
|
||||
anicraft_engine::text::Fonts::register(theme::embedded_fonts());
|
||||
@@ -133,6 +147,7 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option<PathBuf>, o
|
||||
Box::new(move |cc| {
|
||||
// A document the system hands over while AniCraft is idle wakes it (ADR 0062).
|
||||
platform::wake_on_requests(&cc.egui_ctx);
|
||||
startup::log_adapter(cc.wgpu_render_state.as_ref());
|
||||
let starting_fresh = file_given.is_none() && shot.is_none();
|
||||
let mut a = app::App::new(cc, session, shot);
|
||||
if let Some(s) = a.shot.as_mut() {
|
||||
@@ -147,9 +162,11 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option<PathBuf>, o
|
||||
}
|
||||
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.
|
||||
if let Some(r) = report {
|
||||
a.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r));
|
||||
match report {
|
||||
// An imported document says what came across, as opening it from the menu does.
|
||||
Opened::Imported(r) => a.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)),
|
||||
Opened::Failed(name, e) => a.status_err(tr!("Could not open {name}: {e}", name = name, e = e)),
|
||||
Opened::Quiet => {}
|
||||
}
|
||||
Ok(Box::new(a))
|
||||
}),
|
||||
@@ -229,8 +246,8 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
/// `--help` (the console's text, in English).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// i18n-exempt: the --help console text
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--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|brushlibrary|brushcurve|paintbrush|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|testmovieinside|testscript|textfields|testtext|softmask|pathtext|gradient|gradientbucket|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\
|
||||
--renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|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|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|gradient|gradientbucket]\n\
|
||||
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
--shot-width scales the screenshot down to this width (the user guide's pictures)\n\
|
||||
ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\
|
||||
@@ -271,17 +288,32 @@ fn main() -> eframe::Result {
|
||||
// from before the event loop starts until it ends (ADR 0062).
|
||||
let _documents = platform::listen_for_documents();
|
||||
|
||||
// wgpu first (Vulkan/Metal/DX12). If it cannot start (old GPU, VM, missing drivers, common
|
||||
// on some Linux setups) retry once with OpenGL, unless the user forced a backend.
|
||||
let forced = platform::forced_renderer(renderer.as_deref());
|
||||
let first = forced.unwrap_or(eframe::Renderer::Wgpu);
|
||||
match run(first, file.as_deref(), shot.clone(), open.clone(), look.clone()) {
|
||||
Err(e) if forced.is_none() && first == eframe::Renderer::Wgpu => {
|
||||
eprintln!("GPU backend (wgpu) failed to start: {e}. Retrying with OpenGL.");
|
||||
run(eframe::Renderer::Glow, file.as_deref(), shot, open, look)
|
||||
// The window: the graphics asked for, then this platform's order down to OpenGL. A way that
|
||||
// fails or panics before the window is up falls through to the next; a start that died
|
||||
// inside a driver last time tries that way last (#207, `startup`).
|
||||
let died_in = startup::begin(platform::log_dir());
|
||||
let attempts = startup::plan(platform::forced_backend(renderer.as_deref()), prefs::Prefs::load().window_backend, &platform::window_attempts(platform::OS), died_in.as_deref());
|
||||
let mut why = String::from("no attempt"); // i18n-exempt: log text
|
||||
for (n, attempt) in attempts.iter().enumerate() {
|
||||
startup::trying(attempt, n + 1, attempts.len());
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone())));
|
||||
why = match result {
|
||||
Ok(Ok(())) => {
|
||||
startup::line("closed");
|
||||
return Ok(());
|
||||
}
|
||||
Ok(Err(e)) => e.to_string(),
|
||||
Err(p) => format!("{} panicked: {}", attempt.label(), startup::panic_text(p.as_ref())), // i18n-exempt: a log line
|
||||
};
|
||||
startup::line(&format!("{} failed: {why}", attempt.label()));
|
||||
// It ran and then stopped: not a start-up problem, and opening a second window would
|
||||
// surprise (autosave offers the work back next time).
|
||||
if startup::started() {
|
||||
return Err(eframe::Error::AppCreation(why.into()));
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
startup::give_up(&why);
|
||||
Err(eframe::Error::AppCreation(why.into()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -319,8 +351,15 @@ mod args_tests {
|
||||
assert_eq!(opened.path.as_deref(), Some(path.as_path()));
|
||||
assert!(opened.doc == s.doc, "the document on the command line, not the sample");
|
||||
// A file that isn't there: the sample, never a crash.
|
||||
let (fallback, _) = open_session(Some(&dir.join("missing.anicraft")));
|
||||
let (fallback, said) = open_session(Some(&dir.join("missing.anicraft")));
|
||||
assert!(fallback.path.is_none());
|
||||
// #226: and the window says why (a release build has no console to print it on).
|
||||
assert!(matches!(&said, Opened::Failed(name, why) if name == "missing.anicraft" && !why.is_empty()), "{said:?}");
|
||||
// An Animate document double-clicked or opened with AniCraft imports, with its report.
|
||||
let xfl = Path::new(env!("CARGO_MANIFEST_DIR")).join("crates/xfl/tests/corpus/shapes/shapes.xfl");
|
||||
let (imported, said) = open_session(Some(&xfl));
|
||||
assert!(matches!(said, Opened::Imported(_)), "{said:?}");
|
||||
assert!(imported.path.is_none() && !imported.doc.timeline(0).layers.is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -169,10 +169,11 @@ pub fn menu(app: &mut App, ui: &mut egui::Ui) {
|
||||
for past in [true, false] {
|
||||
let name = if past { tr!("Before colour") } else { tr!("After colour") };
|
||||
ui.label(text(Type::Body, if past { tr!("Before") } else { tr!("After") }));
|
||||
let mut c = to_color32(if past { o.past } else { o.future });
|
||||
let r = ui.color_edit_button_srgba(&mut c).named(name).on_hover_text(if past { tr!("Colour of the frames before the playhead") } else { tr!("Colour of the frames after the playhead") });
|
||||
let [r0, g0, b0, _] = to_color32(if past { o.past } else { o.future }).to_srgba_unmultiplied();
|
||||
let mut px = [r0, g0, b0];
|
||||
let r = crate::colour::button(ui, &mut px).named(name).on_hover_text(if past { tr!("Colour of the frames before the playhead") } else { tr!("Colour of the frames after the playhead") });
|
||||
if r.changed() {
|
||||
let [cr, cg, cb, _] = c.to_srgba_unmultiplied();
|
||||
let [cr, cg, cb] = px;
|
||||
change(app, &ctx, |o, p| {
|
||||
let pick = [cr, cg, cb];
|
||||
if past {
|
||||
|
||||
+176
-50
@@ -108,19 +108,105 @@ fn tool_column(app: &mut App, ui: &mut egui::Ui, area: Rect) {
|
||||
app.run("draw.snap_to_objects", json!({}));
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
// fill / stroke swatches
|
||||
let st = &app.s.style;
|
||||
let (r, _) = ui.allocate_exact_size(vec2(TOOL_BUTTON, TOOL_BUTTON), Sense::hover());
|
||||
let back = Rect::from_min_size(r.left_top() + vec2(14.0, 14.0), vec2(24.0, 24.0));
|
||||
let front = Rect::from_min_size(r.left_top() + vec2(2.0, 2.0), vec2(24.0, 24.0));
|
||||
ui.painter().rect_filled(back, T.rc(), if st.use_fill { to_color32(st.fill) } else { T.field });
|
||||
ui.painter().rect_stroke(back, T.rc(), Stroke::new(1.0, T.border), StrokeKind::Inside);
|
||||
ui.painter().rect_filled(front, T.rc(), T.panel);
|
||||
ui.painter().rect_stroke(front.shrink(1.0), T.rc(), Stroke::new(5.0, if st.use_stroke { to_color32(st.stroke) } else { T.field }), StrokeKind::Inside);
|
||||
ui.painter().rect_stroke(front, T.rc(), Stroke::new(1.0, T.border), StrokeKind::Inside);
|
||||
tool_swatches(app, ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// The stroke and fill swatches under the tools, as in Animate: the stroke's frame at the top
|
||||
/// left, the fill behind it. A click on either opens the colour picker (#246); the colour is
|
||||
/// the tools' (what they draw next) and, with shapes selected, theirs too.
|
||||
fn tool_swatches(app: &mut App, ui: &mut egui::Ui) {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(TOOL_BUTTON, TOOL_BUTTON), Sense::hover());
|
||||
let back = Rect::from_min_size(r.left_top() + vec2(14.0, 14.0), vec2(24.0, 24.0));
|
||||
let front = Rect::from_min_size(r.left_top() + vec2(2.0, 2.0), vec2(24.0, 24.0));
|
||||
// The fill first, so the stroke's frame (on top) takes the clicks where they overlap.
|
||||
let fill_resp = ui.interact(back, ui.id().with("tool_fill"), Sense::click());
|
||||
let stroke_resp = ui.interact(front, ui.id().with("tool_stroke"), Sense::click());
|
||||
let st = &app.s.style;
|
||||
let hot = |r: &egui::Response| if r.hovered() { T.selection } else { T.border };
|
||||
ui.painter().rect_filled(back, T.rc(), if st.use_fill { to_color32(st.fill) } else { T.field });
|
||||
ui.painter().rect_stroke(back, T.rc(), Stroke::new(1.0, hot(&fill_resp)), StrokeKind::Inside);
|
||||
ui.painter().rect_filled(front, T.rc(), T.panel);
|
||||
ui.painter().rect_stroke(front.shrink(1.0), T.rc(), Stroke::new(5.0, if st.use_stroke { to_color32(st.stroke) } else { T.field }), StrokeKind::Inside);
|
||||
ui.painter().rect_stroke(front, T.rc(), Stroke::new(1.0, hot(&stroke_resp)), StrokeKind::Inside);
|
||||
for (fill, resp) in [(true, fill_resp), (false, stroke_resp)] {
|
||||
let name = if fill { tr!("Fill colour") } else { tr!("Stroke colour") };
|
||||
a11y::control(ui, &resp, WidgetType::ColorButton, name, None);
|
||||
let resp = resp.on_hover_text(if fill { tr!("Fill colour: click to pick the colour shapes are filled with") } else { tr!("Stroke colour: click to pick the colour of lines and outlines") });
|
||||
let st = &app.s.style;
|
||||
let (colour, mut none) = if fill { (st.fill, !st.use_fill) } else { (st.stroke, !st.use_stroke) };
|
||||
let mut c = rgba(colour);
|
||||
let was = none;
|
||||
if fill && std::mem::take(&mut app.open_fill_swatch) {
|
||||
egui::Popup::open_id(ui.ctx(), resp.id.with("colour_popup"));
|
||||
}
|
||||
// The fill opens the one colour picker with the fill's type on top (ADR 0074): what the
|
||||
// selection is filled with, else the swatch. Solid colours and None go on as below.
|
||||
let picked = if fill {
|
||||
let (paint, selected) = crate::colour_panel::current(app);
|
||||
let shown = (selected || st.use_fill).then_some(paint);
|
||||
match crate::colour_panel::popup_for(ui, &resp, resp.id.with("colour_popup"), shown.as_ref(), &crate::colour_panel::bitmaps(app)) {
|
||||
Some(crate::colour_panel::FillEdit::Solid(p)) => {
|
||||
c = [p[0], p[1], p[2], 255];
|
||||
none = false;
|
||||
true
|
||||
}
|
||||
Some(crate::colour_panel::FillEdit::None(n)) => {
|
||||
none = n;
|
||||
true
|
||||
}
|
||||
Some(edit) => {
|
||||
app.s.style.use_fill = true;
|
||||
crate::colour_panel::apply_set(app, &edit, true);
|
||||
false
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
} else {
|
||||
crate::colour::popup_for(ui, &resp, resp.id.with("colour_popup"), &mut c, false, Some(&mut none))
|
||||
};
|
||||
if picked {
|
||||
// No Colour toggled says which; a colour picked turns the colour back on.
|
||||
let none = none != was && none;
|
||||
let pick = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0);
|
||||
let style = &mut app.s.style;
|
||||
if fill {
|
||||
style.use_fill = !none;
|
||||
if !none {
|
||||
style.set_fill_color(pick);
|
||||
}
|
||||
} else {
|
||||
style.use_stroke = !none;
|
||||
if !none {
|
||||
style.stroke = pick;
|
||||
}
|
||||
}
|
||||
// Selected shapes take it too (one undo step for a drag in the mixer).
|
||||
let shapes = app.s.selected_elements().iter().any(|(_, e)| matches!(e.kind, ElementKind::Shape(_)));
|
||||
if shapes {
|
||||
let colour = if none { Value::Null } else { json!(hex([c[0], c[1], c[2]])) };
|
||||
let (label, id, p) = if fill { (tr_noop!("Fill colour"), "element.set_fill", json!({"color": colour})) } else { (tr_noop!("Stroke colour"), "element.set_stroke", json!({"color": colour})) };
|
||||
live(app, label, id, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a gradient or bitmap fill is, for the caption beside its swatch (nothing for a colour).
|
||||
fn fill_kind_label(p: Option<&Paint>) -> Option<&'static str> {
|
||||
match p? {
|
||||
Paint::Linear { .. } => Some(tr!("Linear gradient")),
|
||||
Paint::Radial { .. } => Some(tr!("Radial gradient")),
|
||||
Paint::Bitmap { .. } => Some(tr!("Bitmap fill")),
|
||||
Paint::Solid(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rgba(c: Rgba) -> [u8; 4] {
|
||||
let [r, g, b] = rgb(c);
|
||||
[r, g, b, 255]
|
||||
}
|
||||
|
||||
// ----- edit bar & status ------------------------------------------------------------------
|
||||
|
||||
pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) {
|
||||
@@ -451,12 +537,6 @@ fn properties(app: &mut App, ui: &mut egui::Ui) {
|
||||
let title = tr!("{tool} tool", tool = crate::i18n::t(app.tool.label()));
|
||||
section(ui, "prop_tool", Section::Rule, &title, None, |ui| tool_props(app, ui));
|
||||
}
|
||||
// ---- Colour (ADR 0074): the selected fill, else the swatch the fill tools pour ----
|
||||
let filled = app.s.selected_elements().iter().any(|(l, e)| *l == app.s.layer && matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some()));
|
||||
let fill_tool = matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Pen | Tool::Brush | Tool::PaintBucket);
|
||||
if fill_tool && !filled {
|
||||
section(ui, "prop_colour", Section::Rule, tr!("Colour"), None, |ui| crate::colour_panel::panel(app, ui));
|
||||
}
|
||||
// ---- Snap to Objects for the tools that drag points and selections (ADR 0042) ----
|
||||
if matches!(app.tool, Tool::Select | Tool::Subselect | Tool::Transform) {
|
||||
let title = tr!("{tool} tool", tool = crate::i18n::t(app.tool.label()));
|
||||
@@ -492,9 +572,6 @@ fn properties(app: &mut App, ui: &mut egui::Ui) {
|
||||
(n, l) => trn!("{n} element {on_layers}", "{n} elements {on_layers}", n, on_layers = trn!("on {n} layer", "on {n} layers", l)),
|
||||
};
|
||||
section(ui, "prop_selection", Section::Rule, &title, None, |ui| selection_props(app, ui, e, &sel));
|
||||
if filled {
|
||||
section(ui, "prop_colour", Section::Rule, tr!("Colour"), None, |ui| crate::colour_panel::panel(app, ui));
|
||||
}
|
||||
} else if let Some((id, name)) = app.s.editing_symbol().and_then(|id| app.s.doc.symbol(id).map(|x| (id, x.name.clone()))) {
|
||||
// Inside a symbol, nothing selected: the symbol's own settings (ADR 0055).
|
||||
section(ui, "prop_symbol", Section::Rule, &tr!("Symbol: {name}", name = name), None, |ui| scale_grid_props(app, ui, id, "open"));
|
||||
@@ -591,7 +668,7 @@ fn colour_effect_rows(app: &mut App, ui: &mut egui::Ui, fx: &ColorEffect, m: cra
|
||||
ColorEffect::Tint { color, amount } => {
|
||||
let mut c = rgb(color);
|
||||
row(ui, tr!("Tint"), |ui| {
|
||||
if ui.color_edit_button_srgb(&mut c).named(tr!("Tint colour")).changed() {
|
||||
if crate::colour::button(ui, &mut c).named(tr!("Tint colour")).changed() {
|
||||
set(app, json!({"tint": hex(c)}));
|
||||
}
|
||||
ui.label(text(Type::Data, hex(c)));
|
||||
@@ -816,18 +893,27 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
|
||||
if let ElementKind::Shape(sh) = &e.kind {
|
||||
ui.add_space(4.0);
|
||||
let fill = sh.fill.as_ref().map(Paint::primary_color);
|
||||
let bitmaps = crate::colour_panel::bitmaps(app);
|
||||
row(ui, tr!("Fill"), |ui| {
|
||||
let is_grad = matches!(sh.fill, Some(Paint::Linear { .. } | Paint::Radial { .. }));
|
||||
let mut c = rgb(fill.unwrap_or(Rgba::WHITE));
|
||||
if ui.color_edit_button_srgb(&mut c).named(tr!("Fill colour")).changed() {
|
||||
live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": hex(c)}));
|
||||
let c = rgb(fill.unwrap_or(Rgba::WHITE));
|
||||
// The one colour picker, with the fill's type (ADR 0074): a gradient shows as its
|
||||
// ramp here and is edited in the picker.
|
||||
let (r, edit) = crate::colour_panel::swatch(ui, sh.fill.as_ref(), &bitmaps);
|
||||
r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour, or a gradient or bitmap fill"));
|
||||
match edit {
|
||||
Some(crate::colour_panel::FillEdit::Solid(p)) => live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": hex(p)})),
|
||||
Some(crate::colour_panel::FillEdit::None(n)) => {
|
||||
app.run("element.set_fill", if n { json!({"color": null}) } else { json!({"color": hex(c)}) });
|
||||
}
|
||||
Some(edit) => crate::colour_panel::apply_set(app, &edit, true),
|
||||
None => {}
|
||||
}
|
||||
let mut on = fill.is_some();
|
||||
if crate::theme::checkbox(ui, &mut on, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off")).changed() {
|
||||
app.run("element.set_fill", if on { json!({"color": hex(c)}) } else { json!({"color": null}) });
|
||||
}
|
||||
if is_grad {
|
||||
ui.label(text(Type::Caption, tr!("gradient")));
|
||||
if let Some(what) = fill_kind_label(sh.fill.as_ref()) {
|
||||
ui.label(text(Type::Caption, what));
|
||||
}
|
||||
mixed(ui, m.fill);
|
||||
});
|
||||
@@ -837,7 +923,7 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
|
||||
let mut sc = rgb(sh.stroke.as_ref().map_or(app.s.style.stroke, |s| s.color));
|
||||
let mut sw = sh.stroke.as_ref().map_or(0.0, |s| s.width);
|
||||
row(ui, tr!("Stroke"), |ui| {
|
||||
if ui.color_edit_button_srgb(&mut sc).named(tr!("Stroke colour")).changed() {
|
||||
if crate::colour::button(ui, &mut sc).named(tr!("Stroke colour")).changed() {
|
||||
live(app, tr_noop!("Stroke colour"), "element.set_stroke", json!({"color": hex(sc)}));
|
||||
}
|
||||
if ui.add(egui::DragValue::new(&mut sw).suffix(" px").speed(0.1).range(0.0..=200.0).max_decimals(1)).named(tr!("Stroke width")).changed() {
|
||||
@@ -1193,7 +1279,7 @@ fn shadow_rows(ui: &mut egui::Ui, fname: &str, strength: &mut f32, color: &mut R
|
||||
*changed = Some(tr_noop!("Filter strength"));
|
||||
}
|
||||
let mut c = rgb(*color);
|
||||
if ui.color_edit_button_srgb(&mut c).named(&tr!("{filter} colour", filter = fname)).on_hover_text(tr!("Colour")).changed() {
|
||||
if crate::colour::button(ui, &mut c).named(&tr!("{filter} colour", filter = fname)).on_hover_text(tr!("Colour")).changed() {
|
||||
*color = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, color.a);
|
||||
*changed = Some(tr_noop!("Filter colour"));
|
||||
}
|
||||
@@ -1249,7 +1335,7 @@ pub(crate) fn alpha_swatch(ui: &mut egui::Ui, c: &mut Rgba, name: &str) -> bool
|
||||
let s = c.sanitized();
|
||||
let b = |v: f32| (v * 255.0).round() as u8;
|
||||
let mut px = [b(s.r), b(s.g), b(s.b), b(s.a)];
|
||||
let r = ui.color_edit_button_srgba_unmultiplied(&mut px).named(name).on_hover_text(name);
|
||||
let r = crate::colour::button_alpha(ui, &mut px).named(name).on_hover_text(name);
|
||||
if r.changed() {
|
||||
*c = Rgba::new(f32::from(px[0]) / 255.0, f32::from(px[1]) / 255.0, f32::from(px[2]) / 255.0, f32::from(px[3]) / 255.0);
|
||||
}
|
||||
@@ -1364,7 +1450,7 @@ fn ramp_editor(ui: &mut egui::Ui, fname: &str, stops: &mut Vec<anicraft_engine::
|
||||
if pinned {
|
||||
// Colour only: this stop stays transparent.
|
||||
let mut c = rgb(st.color);
|
||||
if ui.color_edit_button_srgb(&mut c).named(&tr!("{filter} stop colour", filter = fname)).on_hover_text(tr!("Stop colour (this stop stays transparent)")).changed() {
|
||||
if crate::colour::button(ui, &mut c).named(&tr!("{filter} stop colour", filter = fname)).on_hover_text(tr!("Stop colour (this stop stays transparent)")).changed() {
|
||||
st.color = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 0.0);
|
||||
*changed = Some(tr_noop!("Colour stop"));
|
||||
}
|
||||
@@ -1418,7 +1504,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin
|
||||
out = Some((tr_noop!("Font size"), json!({"size": st.size})));
|
||||
}
|
||||
let mut c = rgb(st.color);
|
||||
if ui.color_edit_button_srgb(&mut c).named(tr!("Text colour")).on_hover_text(tr!("Text colour")).changed() {
|
||||
if crate::colour::button(ui, &mut c).named(tr!("Text colour")).on_hover_text(tr!("Text colour")).changed() {
|
||||
st.color = Rgba::hex(u32::from(c[0]) << 16 | u32::from(c[1]) << 8 | u32::from(c[2]));
|
||||
out = Some((tr_noop!("Text colour"), json!({"color": hex(c)})));
|
||||
}
|
||||
@@ -1495,7 +1581,7 @@ fn camera_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
let mut tint = rgb(cam.tint);
|
||||
let mut amount = cam.tint_amount * 100.0;
|
||||
row(ui, tr!("Tint"), |ui| {
|
||||
let a = ui.color_edit_button_srgb(&mut tint).named(tr!("Camera tint colour"));
|
||||
let a = crate::colour::button(ui, &mut tint).named(tr!("Camera tint colour"));
|
||||
let b = ui.add(egui::DragValue::new(&mut amount).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)).named(tr!("Camera tint amount"));
|
||||
if a.changed() || b.changed() {
|
||||
live(app, tr_noop!("Camera Tint"), "camera.set", json!({"tint": hex(tint), "tint_amount": amount}));
|
||||
@@ -1588,7 +1674,7 @@ fn document_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
});
|
||||
let mut bg = rgb(st.background);
|
||||
row(ui, tr!("Stage"), |ui| {
|
||||
if ui.color_edit_button_srgb(&mut bg).named(tr!("Stage colour")).changed() {
|
||||
if crate::colour::button(ui, &mut bg).named(tr!("Stage colour")).changed() {
|
||||
live(app, tr_noop!("Stage colour"), "doc.set_stage", json!({"background": hex(bg)}));
|
||||
}
|
||||
ui.label(text(Type::Data, trn!("{n} frame", "{n} frames", app.s.frame_count())).color(T.text_faint));
|
||||
@@ -1894,6 +1980,12 @@ fn sound_rows(app: &mut App, ui: &mut egui::Ui, current: Option<anicraft_engine:
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools that only ever draw or paint a line, in the stroke colour: Properties shows no fill
|
||||
/// for them, nor a stroke on/off (#252).
|
||||
pub(crate) fn stroke_only(tool: Tool) -> bool {
|
||||
matches!(tool, Tool::InkBottle | Tool::PaintBrush | Tool::Pencil | Tool::Line)
|
||||
}
|
||||
|
||||
fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
if app.tool == Tool::Eraser {
|
||||
eraser_props(app, ui);
|
||||
@@ -1908,37 +2000,47 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
return;
|
||||
}
|
||||
let mut st = app.s.style.clone();
|
||||
// Each tool shows only what it uses: the bucket and the brush always fill, the ink bottle
|
||||
// always strokes.
|
||||
// Each tool shows only what it uses: the bucket and the brush always fill; the ink bottle,
|
||||
// the Pencil and the Line tool always stroke and never fill (#252).
|
||||
// The Paint Brush (ADR 0068) draws in the stroke colour at its own size and profile.
|
||||
let (fills, ink) = (matches!(app.tool, Tool::PaintBucket | Tool::Brush), matches!(app.tool, Tool::InkBottle | Tool::PaintBrush));
|
||||
let (fills, ink) = (matches!(app.tool, Tool::PaintBucket | Tool::Brush), stroke_only(app.tool));
|
||||
let brush_line = app.tool == Tool::PaintBrush;
|
||||
if !ink {
|
||||
let bitmaps = crate::colour_panel::bitmaps(app);
|
||||
let mut set = None;
|
||||
row(ui, tr!("Fill"), |ui| {
|
||||
let mut c = rgb(st.fill);
|
||||
if ui.color_edit_button_srgb(&mut c).named(tr!("Fill colour")).changed() {
|
||||
st.set_fill_color(Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0));
|
||||
// The fill swatch: what new shapes, the Paint Bucket and the Brush pour, in the one
|
||||
// colour picker with the fill's type (ADR 0074).
|
||||
let paint = st.fill_paint();
|
||||
let (r, edit) = crate::colour_panel::swatch(ui, (st.use_fill || fills).then_some(&paint), &bitmaps);
|
||||
r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour, or a gradient or bitmap fill"));
|
||||
match edit {
|
||||
Some(crate::colour_panel::FillEdit::Solid(p)) => {
|
||||
st.set_fill_color(Rgba::new(f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0, 1.0));
|
||||
st.use_fill = true;
|
||||
}
|
||||
Some(crate::colour_panel::FillEdit::None(n)) => st.use_fill = !n || fills,
|
||||
other => set = other,
|
||||
}
|
||||
// A gradient or bitmap picked with the Eyedropper (ADR 0034): the swatch shows its
|
||||
// first colour, and says what it holds.
|
||||
if let Some(p) = &st.fill_paint {
|
||||
let what = match p {
|
||||
Paint::Linear { .. } => tr!("Linear gradient"),
|
||||
Paint::Radial { .. } => tr!("Radial gradient"),
|
||||
Paint::Bitmap { .. } => tr!("Bitmap fill"),
|
||||
Paint::Solid(_) => tr!("Solid"),
|
||||
};
|
||||
ui.label(text(Type::Caption, what)).on_hover_text(tr!("Set in the Colour panel or picked with the Eyedropper. Pick a colour here to fill with a solid colour again."));
|
||||
if let Some(what) = fill_kind_label(st.fill_paint.as_ref()) {
|
||||
ui.label(text(Type::Caption, what)).on_hover_text(tr!("Set in the colour picker or picked with the Eyedropper. Choose Solid in the picker to fill with a colour again."));
|
||||
}
|
||||
if !fills {
|
||||
crate::theme::checkbox(ui, &mut st.use_fill, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off"));
|
||||
}
|
||||
});
|
||||
// A type, stops or bitmap: the swatch through the command (the rest of the options go
|
||||
// on from what it set).
|
||||
if let Some(edit) = set {
|
||||
app.s.style = st;
|
||||
crate::colour_panel::apply_set(app, &edit, false);
|
||||
st = app.s.style.clone();
|
||||
}
|
||||
}
|
||||
if !fills {
|
||||
row(ui, tr!("Stroke"), |ui| {
|
||||
let mut c = rgb(st.stroke);
|
||||
if ui.color_edit_button_srgb(&mut c).named(tr!("Stroke colour")).changed() {
|
||||
if crate::colour::button(ui, &mut c).named(tr!("Stroke colour")).changed() {
|
||||
st.stroke = Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0);
|
||||
}
|
||||
if !ink {
|
||||
@@ -2308,3 +2410,27 @@ fn library(app: &mut App, ui: &mut egui::Ui) {
|
||||
let r = ui.scope(|ui| crate::library::panel(app, ui)).response.rect;
|
||||
app.library.drop_zone.panel = Some(r);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #252: the Pencil and the Line tool never fill, whatever the fill swatch says, so their
|
||||
/// Properties show no Fill row; the Pen and the shape tools still fill.
|
||||
#[test]
|
||||
fn stroke_only_tools_never_fill() {
|
||||
let mut s = anicraft_engine::Session::default();
|
||||
s.style.use_fill = true;
|
||||
let pts: Vec<[f32; 2]> = (0..20).map(|i| [i as f32 * 5.0, (i % 4) as f32 * 6.0]).collect();
|
||||
// A loop back to where it began, too.
|
||||
let loop_pts: Vec<[f32; 2]> = (0..=24).map(|i| { let a = i as f32 / 24.0 * std::f32::consts::TAU; [200.0 + 40.0 * a.cos(), 200.0 + 40.0 * a.sin()] }).collect();
|
||||
for (id, p) in [("draw.freehand", json!({"points": pts})), ("draw.freehand", json!({"points": loop_pts})), ("draw.line", json!({"x0": 0, "y0": 0, "x1": 90, "y1": 40}))] {
|
||||
s.execute(id, &p).expect("drawn");
|
||||
}
|
||||
assert!(s.visible_elements().iter().all(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_none() && sh.stroke.is_some())));
|
||||
assert!(stroke_only(Tool::Pencil) && stroke_only(Tool::Line) && stroke_only(Tool::InkBottle) && stroke_only(Tool::PaintBrush));
|
||||
for t in [Tool::Pen, Tool::Rect, Tool::Oval, Tool::Star, Tool::Brush, Tool::PaintBucket] {
|
||||
assert!(!stroke_only(t), "{t:?} fills");
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -141,7 +141,7 @@ pub fn commit_pen(app: &mut App, closed: bool) {
|
||||
if pen.knots.len() < 2 {
|
||||
return;
|
||||
}
|
||||
app.run("draw.path", json!({"d": pen.to_svg(closed)}));
|
||||
app.draw("draw.path", json!({"d": pen.to_svg(closed)}));
|
||||
}
|
||||
|
||||
// ----- Pencil ------------------------------------------------------------------------------
|
||||
@@ -195,7 +195,7 @@ pub fn commit_pencil(app: &mut App, xf: Xf) {
|
||||
return;
|
||||
}
|
||||
let points: Vec<[f32; 2]> = pts.iter().map(|p| [p.x, p.y]).collect();
|
||||
app.run("draw.freehand", json!({"points": points, "mode": app.pencil_mode.id(), "tolerance": 1.5 * xf.unit()}));
|
||||
app.draw("draw.freehand", json!({"points": points, "mode": app.pencil_mode.id(), "tolerance": 1.5 * xf.unit()}));
|
||||
}
|
||||
|
||||
// ----- Subselection --------------------------------------------------------------------------
|
||||
|
||||
+58
-7
@@ -5,6 +5,7 @@
|
||||
//! The web build (ADR 0036) is one more platform: the browser's file picker and downloads take
|
||||
//! the dialogs' place, its storage the settings folder's, and the glue lives in `web.rs`.
|
||||
|
||||
use crate::prefs::WindowBackend;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
@@ -546,17 +547,52 @@ pub fn is_system_argument(arg: &str) -> bool {
|
||||
arg.starts_with("-psn_")
|
||||
}
|
||||
|
||||
/// Renderer requested by `--renderer` / `ANICRAFT_RENDERER` (`wgpu` or `gl`), if any.
|
||||
/// The window's graphics asked for by `--renderer` / `ANICRAFT_RENDERER`, if any: `gl`,
|
||||
/// `wgpu` (automatic), `vulkan`, `dx12` or `metal`. Before #207 the last three all meant `wgpu`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn forced_renderer(arg: Option<&str>) -> Option<eframe::Renderer> {
|
||||
pub fn forced_backend(arg: Option<&str>) -> Option<WindowBackend> {
|
||||
let v = arg.map(str::to_owned).or_else(|| std::env::var("ANICRAFT_RENDERER").ok())?;
|
||||
match v.to_ascii_lowercase().as_str() {
|
||||
"gl" | "glow" | "opengl" => Some(eframe::Renderer::Glow),
|
||||
"wgpu" | "vulkan" | "metal" | "dx12" => Some(eframe::Renderer::Wgpu),
|
||||
match v.trim().to_ascii_lowercase().as_str() {
|
||||
"gl" | "glow" | "opengl" => Some(WindowBackend::OpenGl),
|
||||
"wgpu" | "auto" => Some(WindowBackend::Auto),
|
||||
"vulkan" => Some(WindowBackend::Vulkan),
|
||||
"dx12" | "d3d12" | "directx" => Some(WindowBackend::Dx12),
|
||||
"metal" => Some(WindowBackend::Metal),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ways to open the window on `os`, in the order Automatic tries them (`startup`, #207):
|
||||
/// each a graphics interface and whether to ask for the low-power GPU. On a laptop with two
|
||||
/// GPUs (a Surface Book, most gaming laptops) the integrated one drives the display, so the
|
||||
/// second try is the system's own interface on it; OpenGL is the last resort everywhere.
|
||||
pub fn window_attempts(os: Os) -> Vec<(WindowBackend, bool)> {
|
||||
match os {
|
||||
Os::Windows => vec![(WindowBackend::Auto, false), (WindowBackend::Dx12, true), (WindowBackend::OpenGl, false)],
|
||||
Os::Mac => vec![(WindowBackend::Auto, false), (WindowBackend::Metal, true), (WindowBackend::OpenGl, false)],
|
||||
_ => vec![(WindowBackend::Auto, false), (WindowBackend::Vulkan, true), (WindowBackend::OpenGl, false)],
|
||||
}
|
||||
}
|
||||
|
||||
/// The window graphics Preferences offers on `os`.
|
||||
pub fn window_backends(os: Os) -> &'static [WindowBackend] {
|
||||
match os {
|
||||
Os::Windows => &[WindowBackend::Auto, WindowBackend::Dx12, WindowBackend::Vulkan, WindowBackend::OpenGl],
|
||||
Os::Mac => &[WindowBackend::Auto, WindowBackend::Metal, WindowBackend::OpenGl],
|
||||
Os::Web => &[],
|
||||
_ => &[WindowBackend::Auto, WindowBackend::Vulkan, WindowBackend::OpenGl],
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the start-up log goes (#207): `Logs` in the settings folder. `ANICRAFT_LOG_DIR`
|
||||
/// points it elsewhere (tests, portable installs).
|
||||
pub fn log_dir() -> Option<PathBuf> {
|
||||
match std::env::var_os("ANICRAFT_LOG_DIR").filter(|v| !v.is_empty()) {
|
||||
Some(d) => Some(PathBuf::from(d)),
|
||||
None => config_dir().map(|d| d.join("Logs")), // i18n-exempt: a folder name
|
||||
}
|
||||
}
|
||||
|
||||
// ----- native file dialogs ----------------------------------------------------------------------
|
||||
|
||||
/// File type filters per command: the filter's name (English, translated where it is shown)
|
||||
@@ -752,7 +788,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn renderer_override() {
|
||||
assert_eq!(forced_renderer(Some("gl")), Some(eframe::Renderer::Glow));
|
||||
assert_eq!(forced_renderer(Some("WGPU")), Some(eframe::Renderer::Wgpu));
|
||||
assert_eq!(forced_backend(Some("gl")), Some(WindowBackend::OpenGl));
|
||||
assert_eq!(forced_backend(Some("WGPU")), Some(WindowBackend::Auto));
|
||||
// #207: each interface is its own choice now, not just "wgpu".
|
||||
assert_eq!(forced_backend(Some("dx12")), Some(WindowBackend::Dx12));
|
||||
assert_eq!(forced_backend(Some("vulkan")), Some(WindowBackend::Vulkan));
|
||||
assert_eq!(forced_backend(Some("metal")), Some(WindowBackend::Metal));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_platform_falls_back_to_opengl_and_offers_what_it_tries() {
|
||||
for os in [Os::Windows, Os::Mac, Os::Linux, Os::Other] {
|
||||
let tries = window_attempts(os);
|
||||
assert_eq!(tries.first(), Some(&(WindowBackend::Auto, false)), "{os:?}");
|
||||
assert_eq!(tries.last(), Some(&(WindowBackend::OpenGl, false)), "{os:?}: OpenGL is the last resort");
|
||||
assert!(tries.iter().all(|(b, _)| window_backends(os).contains(b)), "{os:?}: Preferences offers each");
|
||||
}
|
||||
assert!(window_attempts(Os::Windows).contains(&(WindowBackend::Dx12, true)), "DirectX 12 on the integrated GPU");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -183,7 +183,7 @@ fn control(ui: &mut egui::Ui, name: &str, kind: &ParamKind, v: &mut Value) -> bo
|
||||
}
|
||||
ParamKind::Color { .. } => {
|
||||
let mut c = hex_rgb(v.as_str().unwrap_or("#000000"));
|
||||
let changed = ui.color_edit_button_srgb(&mut c).named(name).changed();
|
||||
let changed = crate::colour::button(ui, &mut c).named(name).changed();
|
||||
let h = format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]);
|
||||
ui.label(text(Type::Data, h.clone()));
|
||||
*v = json!(h);
|
||||
|
||||
@@ -47,6 +47,39 @@ pub enum StageRenderer {
|
||||
Cpu,
|
||||
}
|
||||
|
||||
/// How the window itself is drawn (#207, #255): AniCraft picks, or one graphics interface the user
|
||||
/// chose for this computer. Takes effect the next time AniCraft starts; whichever is chosen, a
|
||||
/// failure falls back to the next way that works (`startup`). Read leniently, so a value a
|
||||
/// newer build wrote never resets the other preferences.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum WindowBackend {
|
||||
/// The platform's order (`platform::window_attempts`).
|
||||
#[default]
|
||||
Auto,
|
||||
Vulkan,
|
||||
/// Windows' own (Direct3D 12).
|
||||
Dx12,
|
||||
Metal,
|
||||
OpenGl,
|
||||
}
|
||||
|
||||
impl WindowBackend {
|
||||
/// The choice's name and what it is for, as Preferences lists it (English keys).
|
||||
pub fn describe(self) -> (&'static str, &'static str) {
|
||||
match self {
|
||||
WindowBackend::Auto => (tr_noop!("Automatic"), tr_noop!("AniCraft tries the best way for this computer first, and the next one if a way doesn't work.")),
|
||||
WindowBackend::Vulkan => (tr_noop!("Vulkan"), tr_noop!("Try this if the window flickers or goes black with another choice.")),
|
||||
WindowBackend::Dx12 => (tr_noop!("DirectX 12"), tr_noop!("Windows' own graphics: try this if the window flickers or goes black with another choice.")),
|
||||
WindowBackend::Metal => (tr_noop!("Metal"), tr_noop!("The Mac's own graphics.")),
|
||||
WindowBackend::OpenGl => (tr_noop!("OpenGL"), tr_noop!("Older and slower, but works with most graphics drivers. The stage is drawn on the CPU or on a graphics device of its own.")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lenient_backend<'de, D: serde::Deserializer<'de>>(d: D) -> Result<WindowBackend, D::Error> {
|
||||
Ok(serde_json::from_value(serde_json::Value::deserialize(d)?).unwrap_or_default())
|
||||
}
|
||||
|
||||
impl StageRenderer {
|
||||
pub const ALL: [(StageRenderer, &'static str, &'static str); 2] = [
|
||||
(StageRenderer::Gpu, tr_noop!("Graphics card (GPU)"), tr_noop!("Draws the stage on the graphics card, and on the CPU when there is no card that can. The picture is the same either way.")),
|
||||
@@ -78,6 +111,9 @@ pub struct Prefs {
|
||||
/// the choice), so that key is not read.
|
||||
#[serde(rename = "stage")]
|
||||
pub stage_renderer: StageRenderer,
|
||||
/// How the window is drawn, from the next start (#207, #255).
|
||||
#[serde(deserialize_with = "lenient_backend")]
|
||||
pub window_backend: WindowBackend,
|
||||
/// Native open/save dialogs; off = a built-in path field (for Linux setups without an XDG
|
||||
/// desktop portal).
|
||||
pub native_dialogs: bool,
|
||||
@@ -162,6 +198,7 @@ impl Default for Prefs {
|
||||
ui_scale: 1.0,
|
||||
render_mode: RenderMode::Auto,
|
||||
stage_renderer: StageRenderer::Gpu,
|
||||
window_backend: WindowBackend::Auto,
|
||||
native_dialogs: true,
|
||||
timeline_start_gap: 0.0,
|
||||
timeline_short_rows: false,
|
||||
@@ -387,6 +424,12 @@ mod tests {
|
||||
assert_eq!(p.stage_renderer, StageRenderer::Gpu, "the GPU draws the stage unless the CPU is chosen");
|
||||
assert_eq!(Prefs::from_json(r#"{"stage_renderer": "Cpu"}"#).stage_renderer, StageRenderer::Gpu, "the old default, written by every earlier build, is not a choice");
|
||||
assert_eq!(Prefs::from_json(r#"{"stage": "Cpu"}"#).stage_renderer, StageRenderer::Cpu);
|
||||
// The window's graphics: automatic unless chosen, and a value this build doesn't know
|
||||
// (a newer build's) leaves it automatic without resetting anything else.
|
||||
assert_eq!(p.window_backend, WindowBackend::Auto);
|
||||
assert_eq!(Prefs::from_json(r#"{"window_backend": "Dx12"}"#).window_backend, WindowBackend::Dx12);
|
||||
let newer = Prefs::from_json(r#"{"window_backend": "Hologram", "stage": "Cpu"}"#);
|
||||
assert_eq!((newer.window_backend, newer.stage_renderer), (WindowBackend::Auto, StageRenderer::Cpu));
|
||||
let chosen = Prefs { stage_renderer: StageRenderer::Cpu, ..Prefs::default() };
|
||||
assert_eq!(Prefs::from_json(&serde_json::to_string(&chosen).unwrap()).stage_renderer, StageRenderer::Cpu, "a choice survives saving");
|
||||
let p = Prefs::from_json(r#"{"shortcuts": {"tool.pen": ["F10", "Ctrl+K"], "nope": ["F2"]}}"#);
|
||||
|
||||
+463
-114
@@ -67,11 +67,13 @@ pub struct Cache {
|
||||
pub gpu: crate::gpu_stage::GpuStage,
|
||||
/// Who drew the newest visible tiles: the GPU, or the CPU and why (status bar).
|
||||
pub drawn_by: Option<(bool, Option<String>)>,
|
||||
/// The selection pattern's texture and the colour it was made in (`selection_pattern`).
|
||||
pattern: Option<(Color32, egui::TextureHandle)>,
|
||||
}
|
||||
|
||||
impl Default for Cache {
|
||||
fn default() -> Self {
|
||||
Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), service: None, shown_state: None, gpu: Default::default(), drawn_by: None }
|
||||
Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), service: None, shown_state: None, gpu: Default::default(), drawn_by: None, pattern: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,34 +426,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Tool::Select | Tool::Transform if multi => crate::onion::drag_start(app, sp, shift, zoom),
|
||||
// On an armature, a drag poses it (ADR 0043).
|
||||
Tool::Select if let Some(d) = crate::bone_tool::select_drag_start(app, xf, press) => d,
|
||||
// Raw shapes (ADR 0041): an unselected corner or end moves, an unselected segment
|
||||
// or fill edge bends; anything else is picked (unless it already is) and moved.
|
||||
Tool::Select => match app.s.raw_grab(to_v(sp), GRAB_EDGE / zoom, GRAB_POINT / zoom) {
|
||||
Some((_, Grab::Point { at })) => {
|
||||
app.s.begin_gesture(tr_noop!("Move Point"));
|
||||
app.raw_points = serde_json::Value::Null;
|
||||
app.raw_with.clear();
|
||||
app.raw_touched.clear();
|
||||
Drag::RawPoint { at: pos2(at.x, at.y), off: pos2(at.x, at.y) - sp }
|
||||
}
|
||||
Some((layer, Grab::Segment { id, cmd, t, .. })) => {
|
||||
if layer != app.s.layer {
|
||||
app.s.layer = layer;
|
||||
app.s.selection.clear();
|
||||
}
|
||||
app.s.begin_gesture(tr_noop!("Bend"));
|
||||
app.raw_touched.clear();
|
||||
Drag::Bend { id, cmd, t, last: sp }
|
||||
}
|
||||
Some((layer, Grab::Fill { id } | Grab::Object { id })) => {
|
||||
if !app.s.selection.contains(layer, id) {
|
||||
app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift}));
|
||||
}
|
||||
app.s.begin_gesture(tr_noop!("Move"));
|
||||
Drag::SnapMove { start: sp, applied: egui::Vec2::ZERO }
|
||||
}
|
||||
None => Drag::Marquee { start: sp, cur: sp },
|
||||
},
|
||||
Tool::Select => select_press(app, sp, shift, command, zoom),
|
||||
Tool::Transform => {
|
||||
let zone = sel_rect.and_then(|r| xf_zone(r, press));
|
||||
match (zone, sel_bounds) {
|
||||
@@ -640,15 +615,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
app.drop_raw();
|
||||
app.s.end_gesture();
|
||||
}
|
||||
Drag::Bend { .. } | Drag::RawPoint { .. } | Drag::RawHandle { .. } => {
|
||||
// What the drag changed merges again with what it touches, in the same step.
|
||||
if !app.raw_touched.is_empty() {
|
||||
let ids = std::mem::take(&mut app.raw_touched);
|
||||
app.run("raw.merge", json!({"ids": ids}));
|
||||
}
|
||||
app.raw_points = serde_json::Value::Null;
|
||||
app.s.end_gesture();
|
||||
}
|
||||
Drag::Bend { .. } | Drag::RawPoint { .. } | Drag::RawHandle { .. } => end_raw_drag(app),
|
||||
Drag::Transform { .. } | Drag::SliceGuide { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::MotionMove { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } | Drag::BonePose { .. } | Drag::ArmatureMove { .. } => app.s.end_gesture(),
|
||||
Drag::Bone { from, head, cur } => crate::bone_tool::drag_end(app, xf, from, head, cur),
|
||||
Drag::Width { .. } => crate::widthtool::drag_end(app),
|
||||
@@ -1042,12 +1009,17 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
// Selected raw shapes (ADR 0031) show Animate's dot pattern over themselves, with no box.
|
||||
if app.tool == Tool::Select {
|
||||
let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom));
|
||||
let mut mesh = egui::Mesh::default();
|
||||
let (mut spans, mut dots) = (Vec::new(), egui::Mesh::default());
|
||||
let mut budget = MAX_DOTS;
|
||||
for item in app.s.display_list().items.iter().filter(|i| app.s.selection.contains(i.layer, i.element) && raw.contains(&(i.layer, i.element))) {
|
||||
selection_dots(&mut mesh, item, &to_px.mul(&item.transform), canvas, &mut budget);
|
||||
selection_pattern(&mut spans, &mut dots, item, &to_px.mul(&item.transform), canvas, &mut budget);
|
||||
}
|
||||
painter.add(egui::Shape::mesh(mesh));
|
||||
if !spans.is_empty() {
|
||||
let mut mesh = egui::Mesh::with_texture(pattern_texture(&mut app.stage_cache.pattern, ui.ctx()));
|
||||
pattern_mesh(&mut mesh, &spans);
|
||||
painter.add(egui::Shape::mesh(mesh));
|
||||
}
|
||||
painter.add(egui::Shape::mesh(dots));
|
||||
}
|
||||
if multi {
|
||||
let hover = pointer.filter(|p| canvas.contains(*p) && !panning && !app.modal_open() && app.palette.is_none() && matches!(app.tool, Tool::Select | Tool::Transform)).map(to_stage);
|
||||
@@ -1075,6 +1047,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.45)), StrokeKind::Middle);
|
||||
continue;
|
||||
}
|
||||
// A plain box, as Animate's Selection tool shows: handles are Free Transform's (Q),
|
||||
// where they work. Handles drawn here could not be dragged (#205).
|
||||
painter.rect_stroke(r, 0.0, sel_stroke, StrokeKind::Middle);
|
||||
// Text on a path shows the path it follows (ADR 0070).
|
||||
if let anicraft_engine::doc::ElementKind::Text(t) = &e.kind
|
||||
@@ -1087,11 +1061,6 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
painter.add(if pl.closed { egui::Shape::closed_line(pts, sel_stroke) } else { egui::Shape::line(pts, sel_stroke) });
|
||||
}
|
||||
}
|
||||
for c in [r.left_top(), r.right_top(), r.left_bottom(), r.right_bottom(), r.center_top(), r.center_bottom(), r.left_center(), r.right_center()] {
|
||||
let h = Rect::from_center_size(c, vec2(6.0, 6.0));
|
||||
painter.rect_filled(h, 0.0, Color32::WHITE);
|
||||
painter.rect_stroke(h, 0.0, sel_stroke, StrokeKind::Middle);
|
||||
}
|
||||
// registration point
|
||||
let o = to_screen(e.transform.translation());
|
||||
painter.circle(o, 3.5, Color32::WHITE, Stroke::new(1.0, Color32::BLACK));
|
||||
@@ -1166,6 +1135,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
&& let Some(p) = pointer.filter(|p| canvas.contains(*p))
|
||||
&& let Some((_, grab)) = app.s.raw_grab(to_v(to_stage(p)), GRAB_EDGE / zoom, GRAB_POINT / zoom)
|
||||
{
|
||||
// With Ctrl (⌘) an edge takes a new corner point there: the corner mark (#200).
|
||||
let grab = match grab {
|
||||
Grab::Segment { at, .. } if command => Grab::Point { at },
|
||||
g => g,
|
||||
};
|
||||
grab_mark(&painter, p, grab);
|
||||
}
|
||||
|
||||
@@ -1283,6 +1257,70 @@ fn move_raw_point(app: &mut App, c: Pos2, zoom: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Selection-tool press at `sp` (stage) on raw shapes (ADR 0041): an unselected corner or end
|
||||
/// moves, an unselected segment or fill edge bends; anything else is picked (unless it already
|
||||
/// is) and moved. With `corner` (Ctrl, ⌘ on macOS), as in Animate, an edge gets a corner point
|
||||
/// where it was pressed and the drag pulls that point, so the edge peaks there (#200).
|
||||
fn select_press(app: &mut App, sp: Pos2, shift: bool, corner: bool, zoom: f32) -> Drag {
|
||||
let point_drag = |app: &mut App, at: Vec2| {
|
||||
app.raw_points = serde_json::Value::Null;
|
||||
app.raw_with.clear();
|
||||
app.raw_touched.clear();
|
||||
Drag::RawPoint { at: pos2(at.x, at.y), off: pos2(at.x, at.y) - sp }
|
||||
};
|
||||
match app.s.raw_grab(to_v(sp), GRAB_EDGE / zoom, GRAB_POINT / zoom) {
|
||||
Some((_, Grab::Point { at })) => {
|
||||
app.s.begin_gesture(tr_noop!("Move Point"));
|
||||
point_drag(app, at)
|
||||
}
|
||||
Some((layer, Grab::Segment { id, cmd, t, at })) => {
|
||||
if layer != app.s.layer {
|
||||
app.s.layer = layer;
|
||||
app.s.selection.clear();
|
||||
}
|
||||
if corner {
|
||||
// The new point, its corner and its move are one undo step. Where no point can
|
||||
// go (one is there already), the press bends the edge as without Ctrl.
|
||||
app.s.begin_gesture(tr_noop!("Add Corner Point"));
|
||||
if let Ok(v) = app.s.execute("raw.add_point", &json!({"x": at.x, "y": at.y, "slop": GRAB_EDGE / zoom.max(1e-3)})) {
|
||||
let f = |k: &str| v.get(k).and_then(serde_json::Value::as_f64).map(|x| x as f32);
|
||||
if let (Some(x), Some(y)) = (f("x"), f("y")) {
|
||||
// A curved edge splits into two curves meeting smoothly: drawing the new
|
||||
// point's handles in makes it a corner, so the sides meet in a peak.
|
||||
let _ = app.s.execute("raw.convert_points", &json!({"points": [[x, y]], "smooth": false}));
|
||||
let drag = point_drag(app, Vec2::new(x, y));
|
||||
touched(app, &v["changed"]);
|
||||
return drag;
|
||||
}
|
||||
}
|
||||
app.s.end_gesture();
|
||||
}
|
||||
app.s.begin_gesture(tr_noop!("Bend"));
|
||||
app.raw_touched.clear();
|
||||
Drag::Bend { id, cmd, t, last: sp }
|
||||
}
|
||||
Some((layer, Grab::Fill { id } | Grab::Object { id })) => {
|
||||
if !app.s.selection.contains(layer, id) {
|
||||
app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift}));
|
||||
}
|
||||
app.s.begin_gesture(tr_noop!("Move"));
|
||||
Drag::SnapMove { start: sp, applied: egui::Vec2::ZERO }
|
||||
}
|
||||
None => Drag::Marquee { start: sp, cur: sp },
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a drag that bent an edge or moved raw points or handles: what it changed merges
|
||||
/// again with what it touches, in the same step.
|
||||
fn end_raw_drag(app: &mut App) {
|
||||
if !app.raw_touched.is_empty() {
|
||||
let ids = std::mem::take(&mut app.raw_touched);
|
||||
app.run("raw.merge", json!({"ids": ids}));
|
||||
}
|
||||
app.raw_points = serde_json::Value::Null;
|
||||
app.s.end_gesture();
|
||||
}
|
||||
|
||||
/// Where a command's result says the drag snapped.
|
||||
fn snapped_at(v: &serde_json::Value) -> Option<Vec2> {
|
||||
let s = v.get("snapped")?;
|
||||
@@ -1322,14 +1360,80 @@ fn raw_ids(app: &App) -> std::collections::HashSet<(anicraft_engine::doc::LayerI
|
||||
layers.into_iter().flat_map(|l| app.s.elements_on(l).into_iter().filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).map(move |e| (l, e.id))).collect()
|
||||
}
|
||||
|
||||
/// Most selection dots drawn in a frame.
|
||||
/// Spacing of the selection pattern's dots (points).
|
||||
const GAP: f32 = 3.0;
|
||||
/// Most single dots drawn in a frame along hairline strokes (wider strokes and fills are spans).
|
||||
const MAX_DOTS: usize = 60_000;
|
||||
/// Most pattern spans in a frame: far more than a full-screen drawing needs (a 4K view is ~720
|
||||
/// rows), so the pattern never stops part way down a shape; it only bounds a pathological one.
|
||||
const MAX_SPANS: usize = 400_000;
|
||||
|
||||
/// The selection pattern's tile: two by two dot cells, dark and light in a checker, at four
|
||||
/// texels a point so the 1.5-point dots stay crisp. Drawn repeating, on the screen grid.
|
||||
fn pattern_image(dark: Color32) -> egui::ColorImage {
|
||||
const PER_PT: usize = 4;
|
||||
let cell = (GAP as usize) * PER_PT;
|
||||
let size = 2 * cell;
|
||||
let (lo, hi) = (cell / 4, cell - cell / 4);
|
||||
let pixels = (0..size * size)
|
||||
.map(|i| {
|
||||
let (x, y) = (i % size, i / size);
|
||||
let inside = (lo..hi).contains(&(x % cell)) && (lo..hi).contains(&(y % cell));
|
||||
match inside {
|
||||
false => Color32::TRANSPARENT,
|
||||
true if (x / cell + y / cell).is_multiple_of(2) => dark,
|
||||
true => Color32::WHITE,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
egui::ColorImage::new([size, size], pixels)
|
||||
}
|
||||
|
||||
/// The pattern texture for the theme's selection colour (made again when the theme changes).
|
||||
fn pattern_texture(cache: &mut Option<(Color32, egui::TextureHandle)>, ctx: &egui::Context) -> egui::TextureId {
|
||||
let dark = T.selection;
|
||||
if let Some((c, t)) = cache.as_ref()
|
||||
&& *c == dark
|
||||
{
|
||||
return t.id();
|
||||
}
|
||||
let t = ctx.load_texture("selection-pattern", pattern_image(dark), egui::TextureOptions::NEAREST_REPEAT);
|
||||
let id = t.id();
|
||||
*cache = Some((dark, t));
|
||||
id
|
||||
}
|
||||
|
||||
/// Adds the pattern over `spans` to `mesh` (textured with [`pattern_texture`]). The texture
|
||||
/// coordinates come from screen positions, so the dots sit on a fixed screen grid and don't
|
||||
/// crawl when the view pans; a dot's centre is on a multiple of [`GAP`].
|
||||
fn pattern_mesh(mesh: &mut egui::Mesh, spans: &[Rect]) {
|
||||
let tile = 2.0 * GAP;
|
||||
let uv = |p: Pos2| pos2((p.x + GAP * 0.5) / tile, (p.y + GAP * 0.5) / tile);
|
||||
for r in spans {
|
||||
mesh.add_rect_with_uv(*r, Rect::from_min_max(uv(r.min), uv(r.max)), Color32::WHITE);
|
||||
}
|
||||
}
|
||||
|
||||
/// Animate's selection look for raw shapes: fine dots over the selected fill or stroke, light and
|
||||
/// dark in a checker so they show on any colour. They sit on a fixed screen grid, so they don't
|
||||
/// crawl when the view pans; `m` maps the item's path to the screen.
|
||||
fn selection_dots(mesh: &mut egui::Mesh, item: &anicraft_engine::doc::DisplayItem, m: &Affine, clip: Rect, budget: &mut usize) {
|
||||
const GAP: f32 = 3.0;
|
||||
/// dark in a checker so they show on any colour. `m` maps the item's path to the screen. Fills
|
||||
/// and strokes wider than the dot spacing become `spans` (one rectangle per row of dots per run
|
||||
/// inside them, for the pattern texture), so a shape filling the view costs a few hundred
|
||||
/// rectangles however far it is zoomed in (#204: single dots under one budget ran out part way
|
||||
/// down a big or zoomed-in shape, and the shading stopped there). Hairline strokes get one row of
|
||||
/// dots along them in `mesh`.
|
||||
fn selection_pattern(spans: &mut Vec<Rect>, mesh: &mut egui::Mesh, item: &anicraft_engine::doc::DisplayItem, m: &Affine, clip: Rect, budget: &mut usize) {
|
||||
use anicraft_engine::geom::FillRule;
|
||||
if item.fill.is_some() {
|
||||
pattern_spans(&item.path.flatten(m, 0.5), item.fill_rule, clip, spans);
|
||||
}
|
||||
let Some(st) = &item.stroke else { return };
|
||||
let half = (st.reach() * m.mean_scale()).max(0.5);
|
||||
if half >= GAP {
|
||||
// The stroke's own outline (caps, joins and dashes as drawn), filled non-zero.
|
||||
let outline = anicraft_engine::render::stroke::stroke_outline(&item.path, m, st, 0.5);
|
||||
pattern_spans(&outline.flatten(&Affine::IDENTITY, 0.5), FillRule::NonZero, clip, spans);
|
||||
return;
|
||||
}
|
||||
let mut dot = |p: Pos2| {
|
||||
if clip.contains(p) && *budget > 0 {
|
||||
*budget -= 1;
|
||||
@@ -1338,73 +1442,228 @@ fn selection_dots(mesh: &mut egui::Mesh, item: &anicraft_engine::doc::DisplayIte
|
||||
}
|
||||
*budget > 0
|
||||
};
|
||||
let lines = item.path.flatten(m, 0.5);
|
||||
if item.fill.is_some() {
|
||||
let b = item.path.bounds().transformed(m);
|
||||
let mut y = (b.min.y.max(clip.top()) / GAP).ceil() * GAP;
|
||||
let bottom = b.max.y.min(clip.bottom());
|
||||
let mut xs: Vec<f32> = Vec::new();
|
||||
while y <= bottom {
|
||||
// Where this row crosses the outline; pairs of crossings are inside (even-odd: raw
|
||||
// fills never overlap themselves).
|
||||
xs.clear();
|
||||
for pl in &lines {
|
||||
let n = pl.points.len();
|
||||
for i in 0..n {
|
||||
let (a, c) = (pl.points[i], pl.points[(i + 1) % n]);
|
||||
if (a.y > y) != (c.y > y) {
|
||||
xs.push(a.x + (y - a.y) * (c.x - a.x) / (c.y - a.y));
|
||||
}
|
||||
}
|
||||
// Along the stroke; segments off the screen are skipped.
|
||||
let near = clip.expand(half + GAP);
|
||||
for pl in &item.path.flatten(m, 0.5) {
|
||||
let n = pl.points.len();
|
||||
let segs = if pl.closed { n } else { n.saturating_sub(1) };
|
||||
let mut carry = 0.0;
|
||||
for i in 0..segs {
|
||||
let (Some(&a), Some(&c)) = (pl.points.get(i), pl.points.get((i + 1) % n)) else { continue };
|
||||
let d = c - a;
|
||||
let len = d.length();
|
||||
if len <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
xs.sort_by(f32::total_cmp);
|
||||
for [x0, x1] in xs.as_chunks::<2>().0 {
|
||||
let mut x = (x0.max(clip.left()) / GAP).ceil() * GAP;
|
||||
while x <= x1.min(clip.right()) {
|
||||
if !dot(pos2(x, y)) {
|
||||
return;
|
||||
}
|
||||
x += GAP;
|
||||
}
|
||||
if !near.intersects(Rect::from_two_pos(pos2(a.x, a.y), pos2(c.x, c.y))) {
|
||||
carry = (carry - len).rem_euclid(GAP);
|
||||
continue;
|
||||
}
|
||||
y += GAP;
|
||||
let dir = d * (1.0 / len);
|
||||
let mut t = carry;
|
||||
while t < len {
|
||||
let p = a + dir * t;
|
||||
if !dot(pos2(p.x, p.y)) {
|
||||
return;
|
||||
}
|
||||
t += GAP;
|
||||
}
|
||||
carry = t - len;
|
||||
}
|
||||
}
|
||||
if let Some(st) = &item.stroke {
|
||||
// Along the stroke, in rows across its width; segments off the screen are skipped.
|
||||
let half = (st.reach() * m.mean_scale()).max(0.5);
|
||||
let rows = (half / GAP).floor() as i32;
|
||||
let near = clip.expand(half + GAP);
|
||||
for pl in &lines {
|
||||
let n = pl.points.len();
|
||||
let segs = if pl.closed { n } else { n.saturating_sub(1) };
|
||||
let mut carry = 0.0;
|
||||
for i in 0..segs {
|
||||
let (a, c) = (pl.points[i], pl.points[(i + 1) % n]);
|
||||
let d = c - a;
|
||||
let len = d.length();
|
||||
if len <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
if !near.intersects(Rect::from_two_pos(pos2(a.x, a.y), pos2(c.x, c.y))) {
|
||||
carry = (carry - len).rem_euclid(GAP);
|
||||
continue;
|
||||
}
|
||||
let (dir, normal) = (d * (1.0 / len), d.perp() * (1.0 / len));
|
||||
let mut t = carry;
|
||||
while t < len {
|
||||
let p = a + dir * t;
|
||||
for k in -rows..=rows {
|
||||
let q = p + normal * (k as f32 * GAP);
|
||||
if !dot(pos2(q.x, q.y)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// The runs inside the closed outlines `lines` (screen space, filled by `rule`) along each row
|
||||
/// of dots, as rectangles one row of dots tall, clipped to `clip`. Rows are scanned with an
|
||||
/// active edge list, so the cost follows the outline's edges and the rows on screen, not the
|
||||
/// area covered.
|
||||
pub(crate) fn pattern_spans(lines: &[anicraft_engine::geom::Polyline], rule: anicraft_engine::geom::FillRule, clip: Rect, out: &mut Vec<Rect>) {
|
||||
use anicraft_engine::geom::FillRule;
|
||||
// Every non-horizontal edge near the view, as (top, bottom, x at top, dx/dy, winding).
|
||||
let mut edges: Vec<(f32, f32, f32, f32, i32)> = Vec::new();
|
||||
for pl in lines {
|
||||
let n = pl.points.len();
|
||||
if n < 2 {
|
||||
continue;
|
||||
}
|
||||
for i in 0..n {
|
||||
let (Some(&a), Some(&c)) = (pl.points.get(i), pl.points.get((i + 1) % n)) else { continue };
|
||||
if a.y == c.y || !(a.is_finite() && c.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let (top, bottom, w) = if a.y < c.y { (a, c, 1) } else { (c, a, -1) };
|
||||
if bottom.y < clip.top() - GAP || top.y > clip.bottom() + GAP {
|
||||
continue;
|
||||
}
|
||||
edges.push((top.y, bottom.y, top.x, (bottom.x - top.x) / (bottom.y - top.y), w));
|
||||
}
|
||||
}
|
||||
if edges.is_empty() {
|
||||
return;
|
||||
}
|
||||
edges.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let last = edges.iter().fold(f32::NEG_INFINITY, |m, e| m.max(e.1)).min(clip.bottom() + GAP * 0.5);
|
||||
let mut y = (edges.first().map_or(0.0, |e| e.0).max(clip.top() - GAP * 0.5) / GAP).ceil() * GAP;
|
||||
let inside = |w: i32| match rule {
|
||||
FillRule::NonZero => w != 0,
|
||||
FillRule::EvenOdd => w % 2 != 0,
|
||||
};
|
||||
let (mut next, mut active, mut xs): (usize, Vec<usize>, Vec<(f32, i32)>) = (0, Vec::new(), Vec::new());
|
||||
while y <= last && out.len() < MAX_SPANS {
|
||||
while edges.get(next).is_some_and(|e| e.0 <= y) {
|
||||
active.push(next);
|
||||
next += 1;
|
||||
}
|
||||
// Half-open in y, so a vertex shared by two edges counts once.
|
||||
active.retain(|&i| edges.get(i).is_some_and(|e| e.1 > y));
|
||||
xs.clear();
|
||||
xs.extend(active.iter().filter_map(|&i| edges.get(i)).map(|e| (e.2 + (y - e.0) * e.3, e.4)));
|
||||
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let (top, bottom) = ((y - GAP * 0.5).max(clip.top()), (y + GAP * 0.5).min(clip.bottom()));
|
||||
let (mut w, mut from) = (0, 0.0);
|
||||
for &(x, d) in &xs {
|
||||
let was = inside(w);
|
||||
w += d;
|
||||
match (was, inside(w)) {
|
||||
(false, true) => from = x,
|
||||
(true, false) => {
|
||||
let (x0, x1) = (from.max(clip.left()), x.min(clip.right()));
|
||||
if x1 > x0 && bottom > top {
|
||||
out.push(Rect::from_min_max(pos2(x0, top), pos2(x1, bottom)));
|
||||
}
|
||||
t += GAP;
|
||||
}
|
||||
carry = t - len;
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
y += GAP;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pattern_tests {
|
||||
use super::*;
|
||||
use anicraft_engine::geom::{FillRule, Path};
|
||||
|
||||
fn area(spans: &[Rect]) -> f32 {
|
||||
spans.iter().map(|r| r.area()).sum()
|
||||
}
|
||||
|
||||
/// #204: a shape far bigger than the view (zoomed in) is shaded all the way down, not just its
|
||||
/// top rows, and costs one span per row rather than one quad per dot.
|
||||
#[test]
|
||||
fn a_zoomed_in_shape_is_shaded_to_the_bottom_of_the_view() {
|
||||
let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(3840.0, 2160.0));
|
||||
let mut spans = Vec::new();
|
||||
let big = Path::rect(-5000.0, -4000.0, 20000.0, 15000.0);
|
||||
pattern_spans(&big.flatten(&Affine::IDENTITY, 0.5), FillRule::NonZero, clip, &mut spans);
|
||||
let bottom = spans.iter().fold(0.0f32, |m, r| m.max(r.max.y));
|
||||
assert_eq!(bottom, clip.bottom(), "the pattern reaches the bottom of the view");
|
||||
assert!((area(&spans) - clip.area()).abs() < 1.0, "the whole view is covered: {} of {}", area(&spans), clip.area());
|
||||
assert_eq!(spans.len(), 721, "one span per row of dots");
|
||||
// The single-dot overlay this replaced stopped after 60 000 dots: 46 rows of 1 280.
|
||||
assert!(clip.area() / (GAP * GAP) > 60_000.0 * 10.0);
|
||||
}
|
||||
|
||||
/// Holes stay unshaded (even-odd and non-zero), and the spans follow the outline.
|
||||
#[test]
|
||||
fn spans_follow_the_fill_rule_and_the_outline() {
|
||||
let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 400.0));
|
||||
let mut ring = Path::rect(0.0, 0.0, 300.0, 300.0);
|
||||
ring.cmds.extend(Path::rect(100.0, 100.0, 100.0, 100.0).cmds);
|
||||
for rule in [FillRule::EvenOdd, FillRule::NonZero] {
|
||||
let mut spans = Vec::new();
|
||||
pattern_spans(&ring.flatten(&Affine::IDENTITY, 0.5), rule, clip, &mut spans);
|
||||
let in_hole = spans.iter().any(|r| r.contains(pos2(150.0, 150.0)));
|
||||
assert_eq!(in_hole, rule == FillRule::NonZero, "{rule:?}: both squares wind the same way");
|
||||
assert!(spans.iter().all(|r| r.min.x >= 0.0 && r.max.x <= 300.0 && r.max.y <= 301.5));
|
||||
assert!(spans.iter().any(|r| r.contains(pos2(50.0, 150.0))));
|
||||
}
|
||||
}
|
||||
|
||||
fn item(path: Path, fill: bool, stroke: Option<f32>) -> anicraft_engine::doc::DisplayItem {
|
||||
use anicraft_engine::doc::{ColorTransform, DisplayItem, ElementId, LayerId, Paint, Rgba, Stroke};
|
||||
DisplayItem {
|
||||
path: std::sync::Arc::new(path),
|
||||
transform: Affine::IDENTITY,
|
||||
fill: fill.then_some(Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0))),
|
||||
stroke: stroke.map(|w| Stroke::new(Rgba::new(0.0, 0.0, 0.0, 1.0), w)),
|
||||
fill_rule: FillRule::NonZero,
|
||||
color: ColorTransform::IDENTITY,
|
||||
layer: LayerId(0),
|
||||
element: ElementId(0),
|
||||
outline: None,
|
||||
clip: None,
|
||||
masks: None,
|
||||
guide: false,
|
||||
group: None,
|
||||
image: None,
|
||||
smooth: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A wide stroke is shaded over its whole outline (beyond the fill), a hairline gets dots
|
||||
/// along it, and nothing off the view is drawn.
|
||||
#[test]
|
||||
fn strokes_are_shaded_wide_as_spans_and_hairlines_as_dots() {
|
||||
let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 400.0));
|
||||
let square = || Path::rect(100.0, 100.0, 200.0, 200.0);
|
||||
let (mut spans, mut dots, mut budget) = (Vec::new(), egui::Mesh::default(), MAX_DOTS);
|
||||
selection_pattern(&mut spans, &mut dots, &item(square(), false, Some(20.0)), &Affine::IDENTITY, clip, &mut budget);
|
||||
assert!(spans.iter().any(|r| r.min.x < 100.0) && !spans.iter().any(|r| r.contains(pos2(200.0, 200.0))), "the outline only, its outer half included");
|
||||
assert!(dots.vertices.is_empty());
|
||||
let mut spans = Vec::new();
|
||||
selection_pattern(&mut spans, &mut dots, &item(square(), true, Some(0.5)), &Affine::IDENTITY, clip, &mut budget);
|
||||
assert!(spans.iter().any(|r| r.contains(pos2(200.0, 200.0))), "the fill");
|
||||
let n = dots.vertices.len() / 4;
|
||||
assert!((250..=290).contains(&n), "a dot every {GAP} along the 800-long hairline: {n}");
|
||||
// Wholly off the view: nothing.
|
||||
let (mut spans, mut dots) = (Vec::new(), egui::Mesh::default());
|
||||
selection_pattern(&mut spans, &mut dots, &item(Path::rect(900.0, 900.0, 50.0, 50.0), true, Some(0.5)), &Affine::IDENTITY, clip, &mut budget);
|
||||
assert!(spans.is_empty() && dots.vertices.is_empty());
|
||||
// The pattern mesh maps each span to the repeating tile.
|
||||
let mut mesh = egui::Mesh::default();
|
||||
pattern_mesh(&mut mesh, &[Rect::from_min_max(pos2(-1.5, -1.5), pos2(4.5, 1.5))]);
|
||||
assert_eq!(mesh.vertices.first().map(|v| v.uv), Some(pos2(0.0, 0.0)));
|
||||
assert_eq!(mesh.vertices.last().map(|v| v.uv), Some(pos2(1.0, 0.5)));
|
||||
}
|
||||
|
||||
/// The whole window, headless, with a big selected raw shape zoomed in (`--open selectzoom`):
|
||||
/// the pattern is drawn with its texture, made once for the theme's colour.
|
||||
#[test]
|
||||
fn a_selected_raw_shape_draws_its_pattern_in_the_window() {
|
||||
let ctx = egui::Context::default();
|
||||
let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo());
|
||||
let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png")));
|
||||
app.open_panel(Some("selectzoom"));
|
||||
assert!(!app.s.selection.is_empty() && app.view.zoom == 4.0);
|
||||
let input = || egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() };
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(input(), |ui| app.frame(ui));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
let first = app.stage_cache.pattern.as_ref().map(|(c, t)| (*c, t.id()));
|
||||
assert_eq!(first.map(|f| f.0), Some(T.selection));
|
||||
let mut out = ctx.run_ui(input(), |ui| app.frame(ui));
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(app.stage_cache.pattern.as_ref().map(|(c, t)| (*c, t.id())), first, "made once");
|
||||
}
|
||||
|
||||
/// The tile's dots sit on the screen grid in the old checker: dark where the row and column
|
||||
/// numbers add up to an even number.
|
||||
#[test]
|
||||
fn the_pattern_tile_is_a_checker_of_dots() {
|
||||
let img = pattern_image(Color32::BLUE);
|
||||
let size = img.size[0];
|
||||
let at = |pt: (f32, f32)| {
|
||||
// Screen point → texel, as `pattern_mesh` maps it.
|
||||
let u = ((pt.0 + GAP * 0.5) / (2.0 * GAP)).rem_euclid(1.0);
|
||||
let v = ((pt.1 + GAP * 0.5) / (2.0 * GAP)).rem_euclid(1.0);
|
||||
img.pixels[(v * size as f32) as usize * size + (u * size as f32) as usize]
|
||||
};
|
||||
assert_eq!(at((0.0, 0.0)), Color32::BLUE);
|
||||
assert_eq!(at((3.0, 0.0)), Color32::WHITE);
|
||||
assert_eq!(at((3.0, 3.0)), Color32::BLUE);
|
||||
assert_eq!(at((1.4, 0.0)), Color32::TRANSPARENT, "space between dots");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1576,17 +1835,17 @@ fn create_shape(app: &mut App, start: Pos2, cur: Pos2) {
|
||||
}
|
||||
match app.tool {
|
||||
Tool::Rect => {
|
||||
app.run("draw.rect", json!({"x": start.x, "y": start.y, "w": d.x, "h": d.y, "radius": app.rect_radius}));
|
||||
app.draw("draw.rect", json!({"x": start.x, "y": start.y, "w": d.x, "h": d.y, "radius": app.rect_radius}));
|
||||
}
|
||||
Tool::Oval => {
|
||||
app.run("draw.ellipse", json!({"x": start.x, "y": start.y, "w": d.x, "h": d.y}));
|
||||
app.draw("draw.ellipse", json!({"x": start.x, "y": start.y, "w": d.x, "h": d.y}));
|
||||
}
|
||||
Tool::Star => {
|
||||
let r = d.length();
|
||||
app.run("draw.star", json!({"cx": start.x, "cy": start.y, "outer": r, "inner": r * 0.45, "points": app.star_points}));
|
||||
app.draw("draw.star", json!({"cx": start.x, "cy": start.y, "outer": r, "inner": r * 0.45, "points": app.star_points}));
|
||||
}
|
||||
Tool::Line => {
|
||||
app.run("draw.line", json!({"x0": start.x, "y0": start.y, "x1": cur.x, "y1": cur.y}));
|
||||
app.draw("draw.line", json!({"x0": start.x, "y0": start.y, "x1": cur.x, "y1": cur.y}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -1632,6 +1891,96 @@ fn draw_preview(app: &App, painter: &egui::Painter, a: Pos2, b: Pos2, zoom: f32)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod draw_tests {
|
||||
use super::*;
|
||||
|
||||
fn app() -> App {
|
||||
let ctx = egui::Context::default();
|
||||
App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::Document::default()), Some(std::path::PathBuf::from("unused.png")))
|
||||
}
|
||||
|
||||
/// #205, #243: a shape or a line drawn with a tool leaves nothing selected (no box around
|
||||
/// the last stroke), in merge drawing and in Object Drawing, and the previous selection
|
||||
/// goes too, as in Animate. Undo still takes the shape away in one step.
|
||||
#[test]
|
||||
fn drawing_tools_leave_nothing_selected() {
|
||||
for object in [false, true] {
|
||||
let mut app = app();
|
||||
app.s.style.object_drawing = object;
|
||||
for tool in [Tool::Line, Tool::Rect, Tool::Oval, Tool::Star] {
|
||||
app.tool = tool;
|
||||
let before = app.s.history_len();
|
||||
create_shape(&mut app, pos2(10.0, 10.0), pos2(80.0, 60.0));
|
||||
assert_eq!(app.s.history_len(), before + 1, "{tool:?} drew");
|
||||
assert!(app.s.selection.is_empty(), "{tool:?}, object {object}: nothing selected");
|
||||
}
|
||||
app.pencil = (0..20).map(|i| Vec2::new(100.0 + i as f32 * 4.0, 100.0 + (i % 3) as f32)).collect();
|
||||
crate::pathtools::commit_pencil(&mut app, crate::pathtools::Xf { origin: Pos2::ZERO, zoom: 1.0 });
|
||||
assert!(app.s.selection.is_empty(), "Pencil, object {object}");
|
||||
let n = app.s.visible_elements().len();
|
||||
app.s.undo().expect("undo");
|
||||
assert!(app.s.visible_elements().len() < n, "one undo takes the stroke away");
|
||||
}
|
||||
}
|
||||
|
||||
/// The area of the raw fill (one on the stage).
|
||||
fn fill_area(app: &App) -> f32 {
|
||||
let fills: Vec<_> = app.s.visible_elements().into_iter().filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge && sh.fill.is_some())).collect();
|
||||
assert_eq!(fills.len(), 1, "one raw fill");
|
||||
let anicraft_engine::doc::ElementKind::Shape(sh) = &fills[0].kind else { return 0.0 };
|
||||
sh.path
|
||||
.flatten(&fills[0].transform, 0.01)
|
||||
.iter()
|
||||
.map(|pl| {
|
||||
let n = pl.points.len();
|
||||
(0..n).filter_map(|i| Some(pl.points.get(i)?.cross(*pl.points.get((i + 1) % n)?))).sum::<f32>() * 0.5
|
||||
})
|
||||
.sum::<f32>()
|
||||
.abs()
|
||||
}
|
||||
|
||||
/// Presses the top edge of a raw 100 × 80 rectangle in its middle, drags it 30 up and lets
|
||||
/// go, as the stage does.
|
||||
fn drag_top_edge(ctrl: bool) -> App {
|
||||
let mut app = app();
|
||||
app.tool = Tool::Select;
|
||||
app.s.style.object_drawing = false;
|
||||
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
app.run("edit.deselect", json!({}));
|
||||
app.drag = select_press(&mut app, pos2(50.0, 0.0), false, ctrl, 1.0);
|
||||
let to = pos2(50.0, -30.0);
|
||||
match app.drag {
|
||||
Drag::RawPoint { .. } => move_raw_point(&mut app, to, 1.0),
|
||||
Drag::Bend { id, cmd, t, last } => {
|
||||
let d = to - last;
|
||||
let v = app.run("path.bend_segment", json!({"id": id.0, "cmd": cmd, "t": t, "x": last.x, "y": last.y, "dx": d.x, "dy": d.y, "merge": false})).expect("bent");
|
||||
touched(&mut app, &v["changed"]);
|
||||
}
|
||||
d => panic!("a press on the edge starts {d:?}"),
|
||||
}
|
||||
end_raw_drag(&mut app);
|
||||
app.drag = Drag::None;
|
||||
app
|
||||
}
|
||||
|
||||
/// #200: Ctrl-drag on an edge makes a corner point with straight sides (Animate); a plain
|
||||
/// drag still bends the edge into a curve. One undo takes either back.
|
||||
#[test]
|
||||
fn ctrl_drag_on_an_edge_makes_a_corner() {
|
||||
let mut app = drag_top_edge(true);
|
||||
// The rectangle and the triangle (0, 0), (50, -30), (100, 0).
|
||||
assert!((fill_area(&app) - 9500.0).abs() < 1.0, "straight sides up to the peak: {}", fill_area(&app));
|
||||
let pts = app.s.execute("raw.points", &json!({"ids": app.s.visible_elements().iter().map(|e| e.id.0).collect::<Vec<_>>()})).expect("points");
|
||||
assert!(pts.to_string().contains("-30"), "a point at the peak: {pts}");
|
||||
app.s.undo().expect("undo");
|
||||
assert!((fill_area(&app) - 8000.0).abs() < 1.0, "one undo: the rectangle again");
|
||||
let bent = drag_top_edge(false);
|
||||
let a = fill_area(&bent);
|
||||
assert!(a > 8000.0 + 100.0 && (a - 9500.0).abs() > 50.0, "a plain drag bends it into a curve: {a}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod xf_tests {
|
||||
use super::*;
|
||||
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
//! Starting the window whatever the graphics driver does (#207, ADR 0006), and the start-up log
|
||||
//! users can attach to a bug report.
|
||||
//!
|
||||
//! The window is opened by a list of attempts ([`plan`]): the interface asked for (`--renderer`,
|
||||
//! `ANICRAFT_RENDERER`, or Preferences › Stage › Window graphics), then the platform's order
|
||||
//! ([`crate::platform::window_attempts`]), ending with OpenGL. An attempt that returns an error
|
||||
//! or panics before the window has drawn falls through to the next one; when none works, a
|
||||
//! system message box says so and where the log is, so AniCraft never just disappears.
|
||||
//!
|
||||
//! A driver can also crash the process or hang, which nothing inside it can catch. Each attempt
|
||||
//! leaves a marker in the log folder until the window has drawn a few frames; if the next start
|
||||
//! finds one, the previous start died in that attempt, so it goes last this time. The log (the
|
||||
//! previous run's is kept beside it) records each attempt, the graphics adapter and driver,
|
||||
//! panics, and a note when the window is still not up after a while.
|
||||
|
||||
use crate::prefs::WindowBackend;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
/// One way to open the window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Attempt {
|
||||
pub backend: WindowBackend,
|
||||
/// Ask for the low-power (integrated) GPU rather than the fastest one.
|
||||
pub low_power: bool,
|
||||
}
|
||||
|
||||
impl Attempt {
|
||||
/// A stable name for the log and the crash marker (English: it is a log).
|
||||
pub fn label(&self) -> String {
|
||||
let name = match self.backend {
|
||||
WindowBackend::Auto => "wgpu (automatic)", // i18n-exempt: log text
|
||||
WindowBackend::Vulkan => "wgpu Vulkan", // i18n-exempt: log text
|
||||
WindowBackend::Dx12 => "wgpu DirectX 12", // i18n-exempt: log text
|
||||
WindowBackend::Metal => "wgpu Metal", // i18n-exempt: log text
|
||||
WindowBackend::OpenGl => "OpenGL", // i18n-exempt: log text
|
||||
};
|
||||
if self.low_power && self.backend != WindowBackend::OpenGl { format!("{name}, low-power GPU") } else { name.to_string() }
|
||||
}
|
||||
|
||||
/// `base` set up for this attempt.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn options(&self, mut base: eframe::NativeOptions) -> eframe::NativeOptions {
|
||||
use eframe::egui_wgpu::{WgpuSetup, WgpuSetupCreateNew, wgpu};
|
||||
if self.backend == WindowBackend::OpenGl {
|
||||
base.renderer = eframe::Renderer::Glow;
|
||||
return base;
|
||||
}
|
||||
base.renderer = eframe::Renderer::Wgpu;
|
||||
let mut setup = WgpuSetupCreateNew::without_display_handle();
|
||||
match self.backend {
|
||||
WindowBackend::Vulkan => setup.instance_descriptor.backends = wgpu::Backends::VULKAN,
|
||||
WindowBackend::Dx12 => setup.instance_descriptor.backends = wgpu::Backends::DX12,
|
||||
WindowBackend::Metal => setup.instance_descriptor.backends = wgpu::Backends::METAL,
|
||||
WindowBackend::Auto | WindowBackend::OpenGl => {}
|
||||
}
|
||||
if self.low_power {
|
||||
setup.power_preference = wgpu::PowerPreference::LowPower;
|
||||
}
|
||||
base.wgpu_options.wgpu_setup = WgpuSetup::CreateNew(setup);
|
||||
base
|
||||
}
|
||||
}
|
||||
|
||||
/// The attempts in order: `forced` (the command line) or else `chosen` (Preferences) first, then
|
||||
/// the platform's order `platform`, each once. The attempt named `died_in` (the previous start
|
||||
/// crashed or hung in it) goes last.
|
||||
pub fn plan(forced: Option<WindowBackend>, chosen: WindowBackend, platform: &[(WindowBackend, bool)], died_in: Option<&str>) -> Vec<Attempt> {
|
||||
let mut out: Vec<Attempt> = Vec::new();
|
||||
let first = forced.unwrap_or(chosen);
|
||||
if first != WindowBackend::Auto {
|
||||
out.push(Attempt { backend: first, low_power: false });
|
||||
}
|
||||
for &(backend, low_power) in platform {
|
||||
let a = Attempt { backend, low_power };
|
||||
if !out.iter().any(|o| o.label() == a.label()) {
|
||||
out.push(a);
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push(Attempt { backend: WindowBackend::Auto, low_power: false });
|
||||
}
|
||||
if let Some(dead) = died_in
|
||||
&& let Some(i) = out.iter().position(|a| a.label() == dead)
|
||||
&& out.len() > 1
|
||||
{
|
||||
let a = out.remove(i);
|
||||
out.push(a);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Longest log written in one run: enough for any start-up, bounded however long AniCraft runs.
|
||||
const MAX_LOG_BYTES: u64 = 1024 * 1024;
|
||||
/// Frames the window draws before the start counts as working.
|
||||
const STARTED_AFTER: u32 = 3;
|
||||
/// A note goes in the log when the window still isn't up after this long.
|
||||
const SLOW_START_SECS: u64 = 20;
|
||||
|
||||
const LOG_NAME: &str = "anicraft.log";
|
||||
const PREVIOUS_LOG_NAME: &str = "anicraft.previous.log";
|
||||
const MARKER_NAME: &str = "starting";
|
||||
|
||||
struct Log {
|
||||
dir: PathBuf,
|
||||
file: Option<std::fs::File>,
|
||||
since: std::time::Instant,
|
||||
written: u64,
|
||||
}
|
||||
|
||||
static LOG: Mutex<Option<Log>> = Mutex::new(None);
|
||||
static FRAMES: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Opens the log in `dir` for this run (the previous run's becomes `anicraft.previous.log`) and
|
||||
/// returns the attempt the previous start died in, if its marker is still there. Panics are
|
||||
/// written to the log from now on.
|
||||
pub fn begin(dir: Option<PathBuf>) -> Option<String> {
|
||||
let dir = dir?;
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let died_in = std::fs::read_to_string(dir.join(MARKER_NAME)).ok().map(|s| s.trim().chars().take(200).collect::<String>()).filter(|s| !s.is_empty());
|
||||
let _ = std::fs::rename(dir.join(LOG_NAME), dir.join(PREVIOUS_LOG_NAME));
|
||||
let file = std::fs::File::create(dir.join(LOG_NAME)).ok();
|
||||
if let Ok(mut g) = LOG.lock() {
|
||||
*g = Some(Log { dir, file, since: std::time::Instant::now(), written: 0 });
|
||||
}
|
||||
FRAMES.store(0, Ordering::Relaxed);
|
||||
let previous = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
// Never waits: the panic may have happened while the log was being written.
|
||||
write(&format!("panic: {info}"), false);
|
||||
previous(info);
|
||||
}));
|
||||
let unix = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
|
||||
line(&format!("AniCraft {} ({}), {} {}, started at {unix} (Unix time)", env!("CARGO_PKG_VERSION"), crate::app::RELEASE_STAGE, std::env::consts::OS, std::env::consts::ARCH));
|
||||
if let Some(d) = &died_in {
|
||||
line(&format!("the previous start stopped while opening the window with {d}: trying it last"));
|
||||
}
|
||||
died_in
|
||||
}
|
||||
|
||||
/// Adds a line to the log (and the console in debug builds), with the seconds since it began.
|
||||
pub fn line(text: &str) {
|
||||
write(text, true);
|
||||
}
|
||||
|
||||
fn write(text: &str, wait: bool) {
|
||||
#[cfg(debug_assertions)]
|
||||
eprintln!("{text}");
|
||||
let Ok(mut g) = (if wait { LOG.lock().map_err(|_| ()) } else { LOG.try_lock().map_err(|_| ()) }) else { return };
|
||||
let Some(log) = g.as_mut() else { return };
|
||||
let Some(f) = log.file.as_mut() else { return };
|
||||
if log.written > MAX_LOG_BYTES {
|
||||
return;
|
||||
}
|
||||
let entry = format!("[{:8.3} s] {}\n", log.since.elapsed().as_secs_f64(), text.chars().take(4000).collect::<String>());
|
||||
log.written += entry.len() as u64;
|
||||
// Flushed at once: the next thing may be the driver taking the process down.
|
||||
let _ = f.write_all(entry.as_bytes()).and_then(|()| f.flush());
|
||||
}
|
||||
|
||||
/// Where the log is, when there is one.
|
||||
pub fn log_path() -> Option<PathBuf> {
|
||||
LOG.lock().ok()?.as_ref().map(|l| l.dir.join(LOG_NAME))
|
||||
}
|
||||
|
||||
/// About to try `a`: logged, and the marker says so until the window has drawn. A watchdog
|
||||
/// notes in the log if the window is still not up after a while (a driver that hangs).
|
||||
pub fn trying(a: &Attempt, n: usize, of: usize) {
|
||||
line(&format!("opening the window with {} (attempt {n} of {of})", a.label()));
|
||||
let marker = LOG.lock().ok().and_then(|g| g.as_ref().map(|l| l.dir.join(MARKER_NAME)));
|
||||
if let Some(m) = marker {
|
||||
let _ = std::fs::write(m, a.label());
|
||||
}
|
||||
FRAMES.store(0, Ordering::Relaxed);
|
||||
let label = a.label();
|
||||
let _ = std::thread::Builder::new().name("anicraft-start-watch".into()).spawn(move || {
|
||||
std::thread::sleep(std::time::Duration::from_secs(SLOW_START_SECS));
|
||||
if FRAMES.load(Ordering::Relaxed) == 0 {
|
||||
line(&format!("the window has not drawn after {SLOW_START_SECS} s with {label} (a graphics driver that hangs?)"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Called once a frame by the window: after a few frames the start counts as working and the
|
||||
/// marker goes.
|
||||
pub fn frame() {
|
||||
if FRAMES.fetch_add(1, Ordering::Relaxed) + 1 == STARTED_AFTER {
|
||||
line(&format!("the window is up ({STARTED_AFTER} frames drawn)"));
|
||||
let marker = LOG.lock().ok().and_then(|g| g.as_ref().map(|l| l.dir.join(MARKER_NAME)));
|
||||
if let Some(m) = marker {
|
||||
let _ = std::fs::remove_file(m);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the window of the current attempt has drawn (then a failure is not retried: it ran).
|
||||
pub fn started() -> bool {
|
||||
FRAMES.load(Ordering::Relaxed) >= STARTED_AFTER
|
||||
}
|
||||
|
||||
/// The adapter and driver the window got (wgpu), for the log.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn log_adapter(rs: Option<&eframe::egui_wgpu::RenderState>) {
|
||||
match rs {
|
||||
Some(rs) => {
|
||||
let i = rs.adapter.get_info();
|
||||
line(&format!("window graphics: {} ({:?}, {:?}), driver {} {}", i.name, i.backend, i.device_type, i.driver, i.driver_info));
|
||||
}
|
||||
None => line("window graphics: OpenGL"), // i18n-exempt: log text
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a panic's payload.
|
||||
pub fn panic_text(p: &(dyn std::any::Any + Send)) -> String {
|
||||
p.downcast_ref::<&str>().map(|s| (*s).to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "a panic".into()) // i18n-exempt: log text
|
||||
}
|
||||
|
||||
/// Every attempt failed: the log says why, and a system message box says so (the window
|
||||
/// can't), with where the log is.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn give_up(why: &str) {
|
||||
line(&format!("no way to open the window worked; last: {why}"));
|
||||
let log = log_path().map_or_else(String::new, |p| p.display().to_string());
|
||||
let text = if log.is_empty() {
|
||||
tr!("AniCraft couldn't open its window with this computer's graphics driver ({why}). Updating the graphics driver usually helps.", why = why).to_string()
|
||||
} else {
|
||||
tr!("AniCraft couldn't open its window with this computer's graphics driver ({why}). Updating the graphics driver usually helps. If it doesn't, please attach this file to a bug report: {log}", why = why, log = log).to_string()
|
||||
};
|
||||
let _ = rfd::MessageDialog::new().set_level(rfd::MessageLevel::Error).set_title(tr!("AniCraft couldn't start")).set_description(text).set_buttons(rfd::MessageButtons::Ok).show();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use WindowBackend::*;
|
||||
|
||||
const WINDOWS: &[(WindowBackend, bool)] = &[(Auto, false), (Dx12, true), (OpenGl, false)];
|
||||
|
||||
fn labels(v: &[Attempt]) -> Vec<String> {
|
||||
v.iter().map(Attempt::label).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_tries_the_platform_order_ending_with_opengl() {
|
||||
assert_eq!(labels(&plan(None, Auto, WINDOWS, None)), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_or_forced_interface_goes_first_and_still_falls_back() {
|
||||
assert_eq!(labels(&plan(None, Vulkan, WINDOWS, None)), ["wgpu Vulkan", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]);
|
||||
// The command line wins over Preferences; OpenGL isn't tried twice.
|
||||
assert_eq!(labels(&plan(Some(OpenGl), Dx12, WINDOWS, None)), ["OpenGL", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU"]);
|
||||
assert_eq!(labels(&plan(Some(Auto), Dx12, WINDOWS, None)), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"], "--renderer wgpu is automatic");
|
||||
}
|
||||
|
||||
/// Each attempt sets the window up as it says: OpenGL through glow, the others through
|
||||
/// wgpu on their interface and GPU.
|
||||
#[test]
|
||||
fn each_attempt_sets_up_the_window_as_it_says() {
|
||||
use eframe::egui_wgpu::{WgpuSetup, wgpu};
|
||||
let setup = |a: Attempt| {
|
||||
let o = a.options(eframe::NativeOptions::default());
|
||||
let wgpu = match o.wgpu_options.wgpu_setup {
|
||||
WgpuSetup::CreateNew(c) => Some((c.instance_descriptor.backends, c.power_preference)),
|
||||
_ => None,
|
||||
};
|
||||
(o.renderer, wgpu)
|
||||
};
|
||||
assert_eq!(setup(Attempt { backend: OpenGl, low_power: false }).0, eframe::Renderer::Glow);
|
||||
assert_eq!(setup(Attempt { backend: Dx12, low_power: true }), (eframe::Renderer::Wgpu, Some((wgpu::Backends::DX12, wgpu::PowerPreference::LowPower))));
|
||||
assert_eq!(setup(Attempt { backend: Vulkan, low_power: false }).1.map(|w| w.0), Some(wgpu::Backends::VULKAN));
|
||||
assert_eq!(setup(Attempt { backend: Metal, low_power: false }).1.map(|w| w.0), Some(wgpu::Backends::METAL));
|
||||
assert_eq!(setup(Attempt { backend: Auto, low_power: false }).0, eframe::Renderer::Wgpu);
|
||||
assert_eq!(Attempt { backend: OpenGl, low_power: true }.label(), "OpenGL", "OpenGL has no GPU choice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panics_read_as_text() {
|
||||
assert_eq!(panic_text(&"static"), "static");
|
||||
assert_eq!(panic_text(&String::from("owned")), "owned");
|
||||
assert_eq!(panic_text(&42), "a panic");
|
||||
// No window: logged as OpenGL, never a panic (nothing is logged without `begin`).
|
||||
log_adapter(None);
|
||||
}
|
||||
|
||||
/// #207: when the last start died inside a driver (nothing to catch), that way goes last.
|
||||
#[test]
|
||||
fn the_way_the_last_start_died_in_goes_last() {
|
||||
assert_eq!(labels(&plan(None, Auto, WINDOWS, Some("wgpu (automatic)"))), ["wgpu DirectX 12, low-power GPU", "OpenGL", "wgpu (automatic)"]);
|
||||
assert_eq!(labels(&plan(None, Auto, WINDOWS, Some("something else"))), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]);
|
||||
assert_eq!(labels(&plan(None, Auto, &[], None)), ["wgpu (automatic)"], "never nothing to try");
|
||||
}
|
||||
|
||||
/// The log, the crash marker and the previous run's log, in a folder of their own.
|
||||
#[test]
|
||||
fn the_log_keeps_the_previous_run_and_finds_a_crashed_start() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-startup-log-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(begin(Some(dir.clone())), None, "a first start");
|
||||
trying(&Attempt { backend: Dx12, low_power: true }, 1, 3);
|
||||
line("hello");
|
||||
// Killed here (a driver crash): the marker stays, and the next start finds it.
|
||||
assert_eq!(begin(Some(dir.clone())).as_deref(), Some("wgpu DirectX 12, low-power GPU"));
|
||||
let previous = std::fs::read_to_string(dir.join(PREVIOUS_LOG_NAME)).unwrap();
|
||||
assert!(previous.contains("opening the window with wgpu DirectX 12, low-power GPU (attempt 1 of 3)") && previous.contains("hello"), "{previous}");
|
||||
let now = std::fs::read_to_string(dir.join(LOG_NAME)).unwrap();
|
||||
assert!(now.contains("the previous start stopped while opening the window with wgpu DirectX 12"), "{now}");
|
||||
// This time the window comes up: the marker goes.
|
||||
trying(&Attempt { backend: OpenGl, low_power: false }, 1, 1);
|
||||
for _ in 0..STARTED_AFTER {
|
||||
frame();
|
||||
}
|
||||
assert!(started());
|
||||
assert!(!dir.join(MARKER_NAME).exists());
|
||||
assert_eq!(log_path(), Some(dir.join(LOG_NAME)));
|
||||
// A panic is written down.
|
||||
let _ = std::panic::catch_unwind(|| panic!("the driver said no"));
|
||||
assert!(std::fs::read_to_string(dir.join(LOG_NAME)).unwrap().contains("the driver said no"));
|
||||
// Closed, so the folder can go (Windows keeps open files).
|
||||
if let Ok(mut g) = LOG.lock() {
|
||||
*g = None;
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
+114
-39
@@ -136,50 +136,56 @@ pub fn drag_start(app: &mut App, press: Pos2, xf: Xf) -> Drag {
|
||||
}
|
||||
// Undo labels stay English in the history and are translated where they show.
|
||||
app.s.begin_gesture(tr_noop!("Width"));
|
||||
// A press on the stroke itself makes a point there once the drag sizes it. It is not
|
||||
// added yet: at the width the stroke already has, a first point leaves it uniform, so the
|
||||
// engine keeps no point for it (#250).
|
||||
let (index, grip) = match h.point {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
let Some(v) = app.run("stroke.set_width_point", json!({"id": h.id.0, "t": h.t})) else {
|
||||
app.s.end_gesture();
|
||||
return Drag::None;
|
||||
};
|
||||
let Some(i) = v["index"].as_u64() else {
|
||||
app.s.end_gesture();
|
||||
return Drag::None;
|
||||
};
|
||||
(i as usize, Grip::Side(h.side))
|
||||
}
|
||||
Some((i, g)) => (Some(i), g),
|
||||
None => (None, Grip::Side(h.side)),
|
||||
};
|
||||
app.width_sel = Some((h.id, index));
|
||||
let (l, r) = current_point(app, h.id, index).unwrap_or((1.0, 1.0));
|
||||
Drag::Width { id: h.id, sub: h.sub, index, grip, start: (l, r) }
|
||||
app.width_sel = index.map(|i| (h.id, i));
|
||||
let (l, r) = index.and_then(|i| current_point(app, h.id, i)).map_or_else(|| factors_at(app, h.id, h.t), |(l, r, _)| (l, r));
|
||||
Drag::Width { id: h.id, sub: h.sub, index, t: h.t, grip, start: (l, r) }
|
||||
}
|
||||
|
||||
/// The left and right factors of width point `index` on shape `id`.
|
||||
fn current_point(app: &App, id: ElementId, index: usize) -> Option<(f32, f32)> {
|
||||
/// The left and right factors of shape `id`'s stroke at `t` (1, 1 when uniform).
|
||||
fn factors_at(app: &App, id: ElementId, t: f32) -> (f32, f32) {
|
||||
let el = app.s.visible_elements().into_iter().find(|e| e.id == id);
|
||||
let profile = el.as_ref().and_then(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.stroke.as_ref().and_then(|st| st.profile.clone()),
|
||||
_ => None,
|
||||
});
|
||||
profile.map_or((1.0, 1.0), |p| p.at(t))
|
||||
}
|
||||
|
||||
/// The left and right factors and the position of width point `index` on shape `id`.
|
||||
fn current_point(app: &App, id: ElementId, index: usize) -> Option<(f32, f32, f32)> {
|
||||
let el = app.s.visible_elements().into_iter().find(|e| e.id == id)?;
|
||||
let ElementKind::Shape(sh) = &el.kind else { return None };
|
||||
let p = *sh.stroke.as_ref()?.profile.as_ref()?.points().get(index)?;
|
||||
Some((p.left, p.right))
|
||||
Some((p.left, p.right, p.t))
|
||||
}
|
||||
|
||||
/// Pointer at stage point `at` while dragging: resize or slide the grabbed point.
|
||||
pub fn drag_to(app: &mut App, d: Drag, at: Vec2, alt: bool, zoom: f32) {
|
||||
let Drag::Width { id, sub, index, grip, start } = d else { return };
|
||||
let Drag::Width { id, sub, index, t: pt_t, grip, start } = d else { return };
|
||||
let Some(t) = targets(app, zoom).into_iter().find(|t| t.id == id) else { return };
|
||||
let Some(inv) = t.m.inverse() else { return };
|
||||
let local = inv.apply(at);
|
||||
let p = match grip {
|
||||
Grip::Along => {
|
||||
let p = match (grip, index) {
|
||||
(Grip::Along, Some(index)) => {
|
||||
let Some(w) = t.walks.get(sub) else { return };
|
||||
let len = w.length();
|
||||
let tt = if len > 0.0 { w.project(local) / len } else { 0.0 };
|
||||
json!({"id": id.0, "index": index, "t": tt})
|
||||
}
|
||||
Grip::Side(side) => {
|
||||
let pt = t.stroke.profile.as_ref().and_then(|p| p.points().get(index).copied());
|
||||
let Some(pt) = pt else { return };
|
||||
let Some((c, n, _, _)) = t.section(sub, pt.t, (pt.left, pt.right)) else { return };
|
||||
(Grip::Along, None) => return,
|
||||
(Grip::Side(side), _) => {
|
||||
// The point is addressed by where it is, not by its index: sized back to the
|
||||
// stroke's own width it leaves the stroke uniform (no points), and dragging on
|
||||
// brings it back at the same place.
|
||||
let (cl, cr) = t.factors(pt_t);
|
||||
let Some((c, n, _, _)) = t.section(sub, pt_t, (cl, cr)) else { return };
|
||||
let hw = t.hw();
|
||||
if hw <= 0.0 {
|
||||
return;
|
||||
@@ -188,16 +194,18 @@ pub fn drag_to(app: &mut App, d: Drag, at: Vec2, alt: bool, zoom: f32) {
|
||||
let (l0, r0) = start;
|
||||
// Both sides move together (keeping their difference); Alt moves just this one.
|
||||
let (l, r) = match (side > 0, alt) {
|
||||
(true, true) => (f, pt.right),
|
||||
(false, true) => (pt.left, f),
|
||||
(true, true) => (f, r0),
|
||||
(false, true) => (l0, f),
|
||||
(true, false) => (f, (r0 + f - l0).max(0.0)),
|
||||
(false, false) => ((l0 + f - r0).max(0.0), f),
|
||||
};
|
||||
json!({"id": id.0, "index": index, "left": l, "right": r})
|
||||
json!({"id": id.0, "t": pt_t, "left": l, "right": r})
|
||||
}
|
||||
};
|
||||
// Inside the gesture: one undo step for the whole drag.
|
||||
let _ = app.s.execute("stroke.set_width_point", &p);
|
||||
if let Ok(v) = app.s.execute("stroke.set_width_point", &p) {
|
||||
app.width_sel = v["index"].as_u64().map(|i| (id, i as usize));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn drag_end(app: &mut App) {
|
||||
@@ -249,15 +257,17 @@ pub fn upkeep(app: &mut App) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor while hovering: a grab hand over a point, a crosshair on a stroke.
|
||||
/// The cursor while hovering: a grab hand over a point, the add cursor on a stroke (a drag
|
||||
/// there adds a point, as the Pen's add cursor), and a crosshair elsewhere, so the tool in
|
||||
/// hand shows on the stage (#250).
|
||||
pub fn cursor(app: &App, at: Option<Pos2>, xf: Xf) -> egui::CursorIcon {
|
||||
if matches!(app.drag, Drag::Width { .. }) {
|
||||
return egui::CursorIcon::Grabbing;
|
||||
}
|
||||
match at.and_then(|p| hit(app, p, xf)) {
|
||||
Some(Hit { point: Some(_), .. }) => egui::CursorIcon::Grab,
|
||||
Some(_) => egui::CursorIcon::Crosshair,
|
||||
None => egui::CursorIcon::Default,
|
||||
Some(_) => egui::CursorIcon::Copy,
|
||||
None => egui::CursorIcon::Crosshair,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +297,7 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
|
||||
painter.add(egui::Shape::line(pts, Line::new(1.0, T.selection.gamma_multiply(0.7))));
|
||||
}
|
||||
let grabbed = match app.drag {
|
||||
Drag::Width { index, .. } => Some(index),
|
||||
Drag::Width { index, .. } => index,
|
||||
_ => None,
|
||||
};
|
||||
if let Some(pr) = &t.stroke.profile {
|
||||
@@ -304,12 +314,77 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
|
||||
}
|
||||
}
|
||||
}
|
||||
// Where a drag would add a point: a faint cross-section at the pointer.
|
||||
if let Some(h) = h.filter(|h| h.point.is_none() && h.id == t.id)
|
||||
&& let Some((c, _, lh, rh)) = t.section(h.sub, h.t, t.factors(h.t))
|
||||
// Where a drag adds a point: a cross-section at the pointer with a white box on the line
|
||||
// and handles at the stroke's edges (#250: easy to see on any artwork), and the same while
|
||||
// a drag on the stroke is still at its own width (no point kept yet).
|
||||
let pending = match app.drag {
|
||||
Drag::Width { id, sub, index: None, t: at, .. } if id == t.id && app.width_sel.is_none() => Some((sub, at)),
|
||||
_ => h.filter(|h| h.point.is_none() && h.id == t.id).map(|h| (h.sub, h.t)),
|
||||
};
|
||||
if let Some((sub, at)) = pending
|
||||
&& let Some((c, _, lh, rh)) = t.section(sub, at, t.factors(at))
|
||||
{
|
||||
let faint = Line::new(1.0, T.selection.gamma_multiply(0.6));
|
||||
painter.add(egui::Shape::dashed_line(&[to_px(lh), to_px(rh)], faint, 3.0, 2.0));
|
||||
painter.rect_stroke(Rect::from_center_size(to_px(c), vec2(5.0, 5.0)), 0.0, faint, StrokeKind::Middle);
|
||||
let (c, lh, rh) = (to_px(c), to_px(lh), to_px(rh));
|
||||
painter.add(egui::Shape::dashed_line(&[lh, rh], line, 3.0, 2.0));
|
||||
diamond(painter, lh, 4.0, Color32::WHITE);
|
||||
diamond(painter, rh, 4.0, Color32::WHITE);
|
||||
let r = Rect::from_center_size(c, vec2(8.0, 8.0));
|
||||
painter.rect_filled(r, 0.0, Color32::WHITE);
|
||||
painter.rect_stroke(r, 0.0, Line::new(1.5, T.selection), StrokeKind::Middle);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::pos2;
|
||||
|
||||
const XF: Xf = Xf { origin: Pos2::ZERO, zoom: 1.0 };
|
||||
|
||||
fn widths(app: &App) -> Vec<f32> {
|
||||
app.s.visible_elements().iter().filter_map(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.stroke.as_ref().map(|st| st.profile.as_ref().map_or(1.0, |p| p.at(0.5).0)),
|
||||
_ => None,
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// #250: a Pencil squiggle in merge drawing, then a drag on it with the Width tool widens it.
|
||||
#[test]
|
||||
fn a_drag_on_a_pencil_stroke_widens_it() {
|
||||
let ctx = egui::Context::default();
|
||||
let session = anicraft_engine::Session::new(anicraft_engine::doc::Document::default());
|
||||
let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png")));
|
||||
app.view.zoom = 1.0;
|
||||
app.s.style.object_drawing = false;
|
||||
app.s.style.stroke_width = 4.0;
|
||||
let points: Vec<[f32; 2]> = (0..=40).map(|i| [100.0 + i as f32 * 5.0, 100.0 + (i as f32 * 0.3).sin() * 10.0]).collect();
|
||||
app.run("draw.freehand", json!({"points": points, "mode": "ink", "tolerance": 1.5})).expect("drawn");
|
||||
app.tool = Tool::Width;
|
||||
let mid = app.s.visible_elements().first().map(|e| e.id).expect("a stroke");
|
||||
let at = app.s.execute("stroke.width_at", &json!({"x": 200, "y": 100.0 + (20.0f32 * 0.3).sin() * 10.0, "slop": 4})).expect("width_at");
|
||||
assert_eq!(at["element"], mid.0, "{at}");
|
||||
let press = pos2(200.0, 100.0 + (20.0f32 * 0.3).sin() * 10.0 - 1.0);
|
||||
let steps = app.s.history_len();
|
||||
let d = drag_start(&mut app, press, XF);
|
||||
assert!(matches!(d, Drag::Width { index: None, .. }), "the press takes the stroke: {d:?}");
|
||||
drag_to(&mut app, d, Vec2::new(press.x, press.y - 8.0), false, 1.0);
|
||||
drag_end(&mut app);
|
||||
assert!(widths(&app).iter().any(|w| *w > 2.0), "the stroke is wider there: {:?}", widths(&app));
|
||||
assert_eq!(app.s.history_len(), steps + 1, "one undo step");
|
||||
assert!(app.width_sel.is_some(), "the new point is selected");
|
||||
// The same point dragged back to the stroke's own width (no point left) and out again,
|
||||
// in one drag: it keeps following the pointer.
|
||||
let y = press.y + 1.0;
|
||||
let w = widths(&app)[0] * 2.0;
|
||||
let d = drag_start(&mut app, pos2(press.x, y - w), XF);
|
||||
assert!(matches!(d, Drag::Width { index: Some(0), grip: Grip::Side(_), .. }), "the handle: {d:?}");
|
||||
let Drag::Width { id, sub, t: at, .. } = d else { unreachable!() };
|
||||
let tg = targets(&app, 1.0).into_iter().find(|t| t.id == id).expect("target");
|
||||
let (_, _, edge, _) = tg.section(sub, at, (1.0, 1.0)).expect("section");
|
||||
drag_to(&mut app, d, tg.m.apply(edge), false, 1.0);
|
||||
assert!(widths(&app).iter().all(|w| (*w - 1.0).abs() < 1e-3), "back to uniform: {:?}", widths(&app));
|
||||
drag_to(&mut app, d, Vec2::new(press.x, y - 12.0), false, 1.0);
|
||||
drag_end(&mut app);
|
||||
assert!(widths(&app).iter().any(|w| *w > 3.0), "wider again: {:?}", widths(&app));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user