mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 20:18:38 -05:00
Merge main into chore/never-run-test-allows
This commit is contained in:
commit
0f95fb0880
30 files changed
+745
-140
No files matched your search
@@ -47,6 +47,9 @@ jobs:
|
||||
test-shards: 6
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
|
||||
# its shard builds), and `cache warm` puts their files into the one entry it saves.
|
||||
warm-split: true
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
@@ -65,14 +68,17 @@ jobs:
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
|
||||
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
|
||||
# script reports a leg that starts late with its own error before the job times out.
|
||||
# free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its
|
||||
# start deadline while any split leg is queued or running, then allows 180 minutes from the last
|
||||
# split completion for the saving leg to start. Without split legs, it allows 180 minutes from
|
||||
# the script's start. A failed split leg fails this job too. The script then waits up to 160
|
||||
# minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the
|
||||
# script's deadlines expire when split builds or runner waits take too long.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 290
|
||||
timeout-minutes: 360
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the
|
||||
//! log (`logs/vectorcraft.log`) and to `logs/hang-report-<process id>.txt`: the stage, a clipboard
|
||||
//! call in progress, the last commands, the last frames' times, the platform, the window system, the
|
||||
//! graphics processor and the present mode the app asked for, and how long the session has run with
|
||||
//! how many documents open. The process holds a lock on the file until the interface thread answers
|
||||
//! graphics processor, its driver when known, and the present mode the app asked for, and how long
|
||||
//! the session has run with how many documents open. The process holds a lock on the file until the interface thread answers
|
||||
//! again; then the log says after how long and the file is removed. A file nobody holds at a later
|
||||
//! launch was left by a session that was closed while it did not answer, and a locked one belongs to
|
||||
//! another instance that is stalled now and is left alone. That launch writes the report to the log,
|
||||
@@ -113,6 +113,8 @@ pub struct Facts {
|
||||
pub flatpak: bool,
|
||||
/// The graphics processor the window draws with.
|
||||
pub graphics: Option<String>,
|
||||
/// The active graphics driver's identity, when the backend reports it.
|
||||
graphics_driver: Option<String>,
|
||||
/// The present mode and frame queue the app asked the window surface for.
|
||||
pub surface: String,
|
||||
}
|
||||
@@ -128,14 +130,29 @@ impl Facts {
|
||||
session_type: value("XDG_SESSION_TYPE"),
|
||||
flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()),
|
||||
graphics,
|
||||
graphics_driver: None,
|
||||
surface,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "wgpu", test))]
|
||||
pub fn with_graphics_driver(mut self, driver: &str, info: &str) -> Facts {
|
||||
// D3D12 reports 0.0.0.0 when the driver version could not be read.
|
||||
let mut fields = [driver, info].map(clean).into_iter().filter(|value| !value.is_empty() && value != "0.0.0.0");
|
||||
self.graphics_driver = fields.next().map(|mut detail| {
|
||||
if let Some(info) = fields.next().filter(|info| info != &detail) {
|
||||
detail.push_str(" / ");
|
||||
detail.push_str(&info);
|
||||
}
|
||||
detail
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// The facts as report lines.
|
||||
pub fn lines(&self) -> String {
|
||||
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
|
||||
format!(
|
||||
let mut lines = format!(
|
||||
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
|
||||
vectorcraft_ui_egui::os_window::version(),
|
||||
std::env::consts::OS,
|
||||
@@ -146,7 +163,13 @@ impl Facts {
|
||||
if self.flatpak { "yes" } else { "no" },
|
||||
or_unknown(&self.graphics),
|
||||
self.surface,
|
||||
)
|
||||
);
|
||||
if let Some(driver) = &self.graphics_driver {
|
||||
lines.push_str("Graphics driver: ");
|
||||
lines.push_str(driver);
|
||||
lines.push('\n');
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -279,3 +279,22 @@ fn troubleshooting_info_holds_both_sessions_reports() {
|
||||
assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n"));
|
||||
assert!(text.contains("Recent commands, oldest first: none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn troubleshooting_info_distinguishes_drivers_on_the_same_adapter() {
|
||||
let mut shared = shared(None);
|
||||
let beacon = Beacon::new();
|
||||
for (driver, info, expected) in [
|
||||
(" 32.0.16.1088 ", "", Some("32.0.16.1088")),
|
||||
("32.0.16.2124", "", Some("32.0.16.2124")),
|
||||
("Mesa\nRADV", "Mesa 25.2", Some("MesaRADV / Mesa 25.2")),
|
||||
("Mesa", "Mesa", Some("Mesa")),
|
||||
("0.0.0.0", "", None),
|
||||
("", "", None),
|
||||
] {
|
||||
shared.facts = facts().with_graphics_driver(driver, info);
|
||||
let text = troubleshooting(&shared, &beacon, UNIX_EPOCH);
|
||||
assert!(text.contains("Graphics: Test GPU"), "the adapter description is still in the report");
|
||||
assert_eq!(text.lines().find_map(|line| line.strip_prefix("Graphics driver: ")), expected);
|
||||
}
|
||||
}
|
||||
@@ -981,14 +981,22 @@ fn main() -> std::process::ExitCode {
|
||||
.map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency));
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let surface = None;
|
||||
let facts = hang_watch::Facts::new(
|
||||
|name| std::env::var(name).ok(),
|
||||
std::path::Path::new("/.flatpak-info").exists(),
|
||||
hang_watch::window_system(winit_window.as_deref()),
|
||||
app.graphics_adapter.clone(),
|
||||
hang_watch::surface(surface),
|
||||
);
|
||||
#[cfg(feature = "wgpu")]
|
||||
let facts = if let Some(rs) = &cc.wgpu_render_state {
|
||||
let info = rs.adapter.get_info();
|
||||
facts.with_graphics_driver(&info.driver, &info.driver_info)
|
||||
} else {
|
||||
facts
|
||||
};
|
||||
let hang = std::sync::Arc::new(hang_watch::Shared {
|
||||
facts: hang_watch::Facts::new(
|
||||
|name| std::env::var(name).ok(),
|
||||
std::path::Path::new("/.flatpak-info").exists(),
|
||||
hang_watch::window_system(winit_window.as_deref()),
|
||||
app.graphics_adapter.clone(),
|
||||
hang_watch::surface(surface),
|
||||
),
|
||||
facts,
|
||||
started: std::time::Instant::now(),
|
||||
last: std::sync::Mutex::new(None),
|
||||
previous: previous_hang.clone(),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 4.8L18.7 1.4L22.6 21.6L4.8 18.2Z"/>
|
||||
<rect x="0.8" y="3.6" width="2.4" height="2.4" fill="currentColor"/>
|
||||
<rect x="17.5" y="0.2" width="2.4" height="2.4" fill="currentColor"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 525 B After Width: | Height: | Size: 527 B |
@@ -744,20 +744,41 @@ fn objects_beyond_the_document_range_are_left_out() {
|
||||
assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings);
|
||||
}
|
||||
|
||||
/// A magenta rectangle with a Recolor adjustment (`RcRA`) attached, at `lightness`.
|
||||
fn recolored(visible: bool, lightness: f64) -> F {
|
||||
let mut node = rectangle(10, (0.0, 0.0), (50.0, 50.0));
|
||||
let recolor = F::Def(
|
||||
20,
|
||||
vec![tag(b"RcRA")],
|
||||
vec![
|
||||
(tag(b"Visi"), F::Bool(visible)),
|
||||
(tag(b"AdjP"), F::Obj(tag(b"RecP"), vec![(tag(b"RecH"), F::F64(0.0)), (tag(b"RecS"), F::F64(1.0)), (tag(b"RecL"), F::F64(lightness))])),
|
||||
],
|
||||
);
|
||||
if let F::Def(_, _, fields) = &mut node {
|
||||
fields.push((tag(b"AdCh"), F::Shared(vec![recolor])));
|
||||
}
|
||||
node
|
||||
}
|
||||
|
||||
fn first_fill(n: &Node) -> Paint {
|
||||
let Some(AppearanceItem::Fill(fill)) = n.appearance.items.first() else { panic!("no fill: {:?}", n.appearance) };
|
||||
fill.paint.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_af_g_symbol_fill_is_white() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af");
|
||||
let Ok(bytes) = std::fs::read(&path) else {
|
||||
return;
|
||||
};
|
||||
let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap();
|
||||
assert!(!loaded.preview_only, "{:?}", loaded.warnings);
|
||||
let d = &loaded.doc;
|
||||
// The visible "g41" group holds the "g" symbol (path43).
|
||||
let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present");
|
||||
let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present");
|
||||
let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else {
|
||||
panic!("path43 has no fill: {:?}", path43.appearance);
|
||||
};
|
||||
assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint);
|
||||
fn attached_recolor_adjustments_recolor_the_shape() {
|
||||
// Lightness 1 recolors to white.
|
||||
let loaded = open("recolor.af", &canvas_with(vec![recolored(true, 1.0)], None));
|
||||
assert!(!loaded.warnings.iter().any(|w| w.contains("attached to other layers")), "{:?}", loaded.warnings);
|
||||
let rect = named(&loaded.doc, "Magenta box");
|
||||
assert!(rect.appearance.effects.is_empty());
|
||||
assert_eq!(first_fill(rect), Paint::solid(Color::rgb(1.0, 1.0, 1.0)));
|
||||
// Lightness 0.5 at hue 0 and full saturation is pure red.
|
||||
let d = open("red.af", &canvas_with(vec![recolored(true, 0.5)], None)).doc;
|
||||
let [r, g, b, a] = pixel(&d, 25, 25);
|
||||
assert!(r > 250 && g < 5 && b < 5 && a == 255, "{:?}", [r, g, b, a]);
|
||||
// A hidden adjustment leaves the shape as it is.
|
||||
let d = open("hidden.af", &canvas_with(vec![recolored(false, 1.0)], None)).doc;
|
||||
assert_eq!(first_fill(named(&d, "Magenta box")), Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)));
|
||||
}
|
||||
+60
-11
@@ -19,7 +19,7 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) ->
|
||||
}
|
||||
// Closed endpoint rounding must not consume a substantial part of a subpixel band.
|
||||
let fine = (tol / 8.0).min(width / 32.0).max(1e-4);
|
||||
if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) {
|
||||
if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, &corners(line), st, width, fine)) {
|
||||
return band;
|
||||
}
|
||||
let outline = effects::stroke::line_outline(line, st, width, fine);
|
||||
@@ -49,21 +49,65 @@ fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option<BezPath> {
|
||||
lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines)
|
||||
}
|
||||
|
||||
/// The points where `line` has a corner: where two of its segments meet with tangents that are not
|
||||
/// in line ([`SMOOTH`]), or where a segment has no direction there. One list for each subpath, in
|
||||
/// order, each sorted by [`point_order`]. [`draw_sub`] leaves these points where they are, so the
|
||||
/// lines a curve is drawn with have each corner at the same point, and draws one subpath for each.
|
||||
fn corners(line: &BezPath) -> Vec<Vec<Point>> {
|
||||
let tangents = |seg: PathSeg| {
|
||||
let c = match seg {
|
||||
PathSeg::Line(l) => CubicBez::new(l.p0, l.p0, l.p1, l.p1),
|
||||
other => cubic(other)?,
|
||||
};
|
||||
Some((start_tangent(&c)?, end_tangent(&c)?))
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
// A span of `f64::INFINITY` gives every segment no steps: only the segments are wanted.
|
||||
for sub in subpaths(line.elements(), f64::INFINITY, 1.0).unwrap_or_default() {
|
||||
let mut here = Vec::new();
|
||||
let n = sub.segs.len();
|
||||
let first = if sub.closed { 0 } else { 1 };
|
||||
for i in first..n {
|
||||
let before = if i == 0 { n - 1 } else { i - 1 };
|
||||
let (Some((a, _)), Some((b, _))) = (sub.segs.get(before), sub.segs.get(i)) else { continue };
|
||||
let smooth = match (tangents(*a).map(|t| t.1), tangents(*b).map(|t| t.0)) {
|
||||
(Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(),
|
||||
_ => false,
|
||||
};
|
||||
if !smooth {
|
||||
here.push(b.start());
|
||||
}
|
||||
}
|
||||
here.sort_by(point_order);
|
||||
out.push(here);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Points in order of `x`, then `y` ([`corners`]).
|
||||
fn point_order(a: &Point, b: &Point) -> std::cmp::Ordering {
|
||||
a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))
|
||||
}
|
||||
|
||||
/// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill
|
||||
/// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet
|
||||
/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the
|
||||
/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as
|
||||
/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross. Elsewhere the
|
||||
/// stroke's join is drawn at the corners of the same subpath of the path (`corners`, one list for
|
||||
/// each subpath of `lines`, [`corners`]) and a round join where the lines a
|
||||
/// curve is drawn with meet. An open subpath ends in the stroke's caps, with round parts drawn as
|
||||
/// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a
|
||||
/// point that isn't finite, or is closed and no wider or taller than the stroke: those take
|
||||
/// [`effects::stroke::line_outline`].
|
||||
fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option<BezPath> {
|
||||
fn thin_band(lines: &BezPath, corners: &[Vec<Point>], st: &StrokeLayer, width: f64, fine: f64) -> Option<BezPath> {
|
||||
let h = width / 2.0;
|
||||
// The angle between two points of an arc of radius `h` drawn as lines within `fine` of it.
|
||||
let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3);
|
||||
let mut out = BezPath::new();
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
let mut closed = false;
|
||||
let flush = |pts: &mut Vec<Point>, closed: bool, out: &mut BezPath| -> Option<()> {
|
||||
// The subpath being read; `None` before the first move.
|
||||
let mut sub: Option<usize> = None;
|
||||
let flush = |pts: &mut Vec<Point>, closed: bool, sub: Option<usize>, out: &mut BezPath| -> Option<()> {
|
||||
if pts.is_empty() {
|
||||
return Some(());
|
||||
}
|
||||
@@ -80,14 +124,15 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
return None;
|
||||
}
|
||||
}
|
||||
band_sub(out, pts, closed, st, h, step);
|
||||
band_sub(out, pts, corners.get(sub?)?, closed, st, h, step);
|
||||
pts.clear();
|
||||
Some(())
|
||||
};
|
||||
for el in lines.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut pts, closed, &mut out)?;
|
||||
flush(&mut pts, closed, sub, &mut out)?;
|
||||
sub = Some(sub.map_or(0, |s| s + 1));
|
||||
closed = false;
|
||||
pts.push(p);
|
||||
}
|
||||
@@ -100,7 +145,7 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None,
|
||||
}
|
||||
}
|
||||
flush(&mut pts, closed, &mut out)?;
|
||||
flush(&mut pts, closed, sub, &mut out)?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -108,8 +153,9 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
/// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side,
|
||||
/// the end cap, its right side backward and the start cap; for a closed one its left side and its
|
||||
/// right side backward, as two contours. `h` is half the width and `step` the angle between the
|
||||
/// points of a round join or cap.
|
||||
fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) {
|
||||
/// points of a round join or cap. A sharp turn takes the stroke's join at one of this subpath's
|
||||
/// `corners` (sorted by [`point_order`]) and a round join elsewhere.
|
||||
fn band_sub(out: &mut BezPath, pts: &[Point], corners: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) {
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
let n = pts.len();
|
||||
let chords = if closed { n } else { n - 1 };
|
||||
@@ -143,7 +189,10 @@ fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h:
|
||||
inner.push(p);
|
||||
inner.push(p - nb * sign);
|
||||
outer.push(p + na * sign);
|
||||
match st.join {
|
||||
// Only the path's corners take the stroke's join; where the lines of a curve turn sharply
|
||||
// the stroke along the curve is round.
|
||||
let kind = if corners.binary_search_by(|c| point_order(c, &p)).is_ok() { st.join } else { LineJoin::Round };
|
||||
match kind {
|
||||
LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign),
|
||||
LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)),
|
||||
LineJoin::Miter | LineJoin::Bevel => {}
|
||||
|
||||
@@ -133,6 +133,148 @@ fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() {
|
||||
assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}");
|
||||
}
|
||||
|
||||
/// A path with a bend at (10, 0) and then six smooth anchors `gap` apart, each with handles
|
||||
/// `handle` and 1.7 times `handle` long, scaled by `zoom`, and its points flattened within 0.001.
|
||||
fn close_smooth_anchors(gap: f64, handle: f64, zoom: f64) -> (BezPath, Vec<kurbo::Point>) {
|
||||
let path = close_smooth_path(gap, handle, zoom);
|
||||
let mut line = Vec::new();
|
||||
vectorcraft_geom::flatten(path.iter(), 1e-3, |el| {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el {
|
||||
line.push(p);
|
||||
}
|
||||
});
|
||||
(path, line)
|
||||
}
|
||||
|
||||
/// How far `q` is from the nearest point of `path`.
|
||||
fn from_curve(path: &BezPath, q: kurbo::Point) -> f64 {
|
||||
use kurbo::ParamCurveNearest;
|
||||
path.segments().map(|s| s.nearest(q, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// The path of [`close_smooth_anchors`].
|
||||
fn close_smooth_path(gap: f64, handle: f64, zoom: f64) -> BezPath {
|
||||
use vectorcraft_geom::path::{Anchor, AnchorKind, PathData, SubPath};
|
||||
let dir = kurbo::Vec2::new(0.8, 0.6);
|
||||
let mut anchors = vec![
|
||||
Anchor::corner(kurbo::Point::new(0.0, 0.0)),
|
||||
Anchor::with_handles(kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 5.0)),
|
||||
];
|
||||
let mut x = 10.0;
|
||||
for i in 0..6 {
|
||||
x += gap;
|
||||
let p = kurbo::Point::new(x, 1.0 + if i % 2 == 0 { 0.3 } else { -0.2 } * gap);
|
||||
anchors.push(Anchor { p, h_in: p - dir * handle, h_out: p + dir * handle * 1.7, kind: AnchorKind::Smooth });
|
||||
}
|
||||
anchors.push(Anchor::smooth(kurbo::Point::new(x + 20.0, 0.0), kurbo::Point::new(x + 25.0, -4.0)));
|
||||
kurbo::Affine::scale(zoom) * PathData::single(SubPath::new(anchors, false)).to_bezpath()
|
||||
}
|
||||
|
||||
/// A thin stroke along smooth anchors that sit close together after a bend follows the curve: its
|
||||
/// outline has no point farther than a stroke's width from the curve, and covers the curve. The
|
||||
/// lines such a curve is drawn with are short beside the stroke and turn sharply, so offsetting
|
||||
/// them drew the stroke's miter joins as spikes.
|
||||
#[test]
|
||||
fn thin_strokes_follow_smooth_anchors_close_together() {
|
||||
for gap in [0.1, 1.0] {
|
||||
let (path, line) = close_smooth_anchors(gap, 1.0, 1.0);
|
||||
for w in [0.6, 0.9] {
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&path, &st, w, 0.25);
|
||||
for el in o.elements() {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el {
|
||||
let d = from_curve(&path, p);
|
||||
assert!(d <= w, "gap {gap}, width {w}: outline point {p:?} is {d} from the curve");
|
||||
}
|
||||
}
|
||||
for p in line.iter().step_by(7) {
|
||||
assert!(o.winding(*p) != 0, "gap {gap}, width {w}: the curve at {p:?} is not covered");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin stroke's outline stays within the stroke's width of its curve where the lines the curve is
|
||||
/// drawn with turn sharply, as near a cusp: they meet with a round join, not the stroke's miter.
|
||||
/// 200 cubic curves, each about 100 device pixels across.
|
||||
#[test]
|
||||
fn thin_strokes_meet_round_where_a_curves_lines_turn_sharply() {
|
||||
let mut seed: u64 = 7;
|
||||
let mut r = |lo: f64, hi: f64| {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64)
|
||||
};
|
||||
let w = 0.5;
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
st.join = LineJoin::Miter;
|
||||
st.miter_limit = 10.0;
|
||||
for _ in 0..200 {
|
||||
let (x, y) = (r(20.0, 980.0), r(20.0, 980.0));
|
||||
let mut q = [kurbo::Point::ZERO; 3];
|
||||
for p in &mut q {
|
||||
*p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71);
|
||||
}
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((x * 1.71, y * 1.71));
|
||||
path.curve_to(q[0], q[1], q[2]);
|
||||
let o = raster_stroke_outline(&path, &st, w, 0.25);
|
||||
for el in o.elements() {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el {
|
||||
let d = from_curve(&path, p);
|
||||
assert!(d <= w, "outline point {p:?} is {d} from the curve {path:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin stroke along smooth anchors close together, with handles long beside the gaps between
|
||||
/// them, covers what the curve's own outline covers: at every point of a grid more than 0.25 pixels
|
||||
/// nearer or farther than half the stroke's width from the curve, both outlines agree. The miter
|
||||
/// joins drawn where the curve's lines turned sharply covered points well outside the stroke.
|
||||
#[test]
|
||||
fn thin_strokes_along_long_handles_cover_the_curve_outline() {
|
||||
let tol = 0.25;
|
||||
for (gap, w) in [(1.0, 0.6), (1.0, 0.9), (0.1, 0.6)] {
|
||||
let path = close_smooth_path(gap, 10.0, 4.0);
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&path, &st, w, tol);
|
||||
let fine = (tol / 8.0).min(w / 32.0);
|
||||
let mut want = BezPath::new();
|
||||
vectorcraft_geom::flatten(crate::effects::stroke::line_outline(&path, &st, w, fine).iter(), fine, |el| want.push(el));
|
||||
let bb = want.bounding_box().inflate(w, w);
|
||||
for i in 0..90 {
|
||||
for j in 0..90 {
|
||||
let q = kurbo::Point::new(bb.x0 + bb.width() * f64::from(i) / 90.0, bb.y0 + bb.height() * f64::from(j) / 90.0);
|
||||
let d = from_curve(&path, q);
|
||||
if (d - w / 2.0).abs() > 0.25 {
|
||||
assert_eq!(o.winding(q) != 0, want.winding(q) != 0, "gap {gap}, width {w}: at {q:?}, {d} from the curve");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A corner of one subpath does not change the join where the lines of another subpath's curve
|
||||
/// meet at the same point: the first subpath's outline is the same with or without the second.
|
||||
#[test]
|
||||
fn thin_strokes_take_corners_from_their_own_subpath() {
|
||||
let w = 0.5;
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
st.join = LineJoin::Miter;
|
||||
st.miter_limit = 10.0;
|
||||
let mut alone = BezPath::new();
|
||||
alone.move_to((-1.0, 0.0));
|
||||
alone.line_to((0.0, 0.0));
|
||||
alone.curve_to((0.000001, 0.0), (-1.0, 0.5), (-2.0, 1.0));
|
||||
let mut both = alone.clone();
|
||||
both.move_to((-10.0, -10.0));
|
||||
both.line_to((0.0, 0.0));
|
||||
both.line_to((-10.0, 10.0));
|
||||
let one = raster_stroke_outline(&alone, &st, w, 0.25);
|
||||
let two = raster_stroke_outline(&both, &st, w, 0.25);
|
||||
assert_eq!(two.elements().get(..one.elements().len()), Some(one.elements()), "the second subpath changed the first one's outline");
|
||||
}
|
||||
|
||||
/// Independently integrate coverage in radial/angle bins of an original notched ring. Checking
|
||||
/// only the outline geometry misses raster flattening that cancels its two nearby contours.
|
||||
#[test]
|
||||
|
||||
@@ -709,7 +709,7 @@ mod cancel_tests {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::behavior::IconId;
|
||||
use craft::ui::primitives::{has_icon, register_app_icons};
|
||||
use craft::ui::primitives::has_icon;
|
||||
|
||||
use super::icon_for_shape;
|
||||
|
||||
@@ -717,7 +717,7 @@ mod tests {
|
||||
/// would show the placeholder instead of the toolbar's icon.
|
||||
#[test]
|
||||
fn every_shape_button_shows_its_tools_icon() {
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
crate::icons::register();
|
||||
for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] {
|
||||
let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool"));
|
||||
assert_eq!(icon_for_shape(id), crate::icons::tool_icon(tool.icon), "{id}");
|
||||
|
||||
@@ -67,7 +67,7 @@ impl VectorcraftApp {
|
||||
/// once, gives Data Recovery the host's store and makes a view for each open document.
|
||||
pub fn new(mut session: Session, mut services: Services) -> Self {
|
||||
// Every entry point (desktop, web, tests) makes the app before its first pass.
|
||||
craft::ui::primitives::register_app_icons(&super::icons::APP_ICONS);
|
||||
super::icons::register();
|
||||
craft::ui::primitives::register_app_icons(&super::cursors::CURSOR_ICONS);
|
||||
// The font menus and the first file opened need the installed fonts: catalog them now.
|
||||
vectorcraft_text::FontDb::global().scan_in_background();
|
||||
|
||||
@@ -463,7 +463,14 @@ impl CanvasTool for SessionTool<'_> {
|
||||
if claim(&mut app, EngineKey::Left) {
|
||||
claims = claims.nudges();
|
||||
}
|
||||
if claim(&mut app, EngineKey::AltTap) {
|
||||
// A lone Alt while the canvas has the keys is the tools' modifier let go without a click: the canvas takes it,
|
||||
// so it does not give the menu bar the keys and the next tool letter still chooses its tool. F10 and Alt with
|
||||
// a letter still reach the bar, and a lone Alt in a field or the bar keeps the framework's rule.
|
||||
let canvas_has_keys = app
|
||||
.ui_ctx
|
||||
.as_ref()
|
||||
.is_some_and(|ctx| !ctx.egui_wants_keyboard_input() && !craft::ui::menu::bar::is_focused(ctx) && !craft::ui::menu::bar::is_open(ctx));
|
||||
if canvas_has_keys || claim(&mut app, EngineKey::AltTap) {
|
||||
claims = claims.alt_tap();
|
||||
}
|
||||
claims
|
||||
|
||||
@@ -17,7 +17,7 @@ fn every_tool_cursors_hotspot_is_on_its_glyph() {
|
||||
use craft::ui::primitives::{painted_image, register_app_icons};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::rgba_color;
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
crate::icons::register();
|
||||
register_app_icons(&CURSOR_ICONS);
|
||||
let mut missed = Vec::new();
|
||||
crate::testing::ui_context()
|
||||
|
||||
@@ -67,7 +67,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
|
||||
ui.ctx().request_repaint_after(Duration::from_secs_f64(DELAY - age));
|
||||
return;
|
||||
}
|
||||
if app.any_dialog_open() {
|
||||
// Progress is modal for input, but the window must not block itself on its next pass.
|
||||
if app.asking_dialog_open() {
|
||||
return;
|
||||
}
|
||||
let Shown { title, step, fraction, counts, queued, cancel, hide, .. } = shown;
|
||||
@@ -208,17 +209,21 @@ mod tests {
|
||||
assert_eq!(r["background"], true, "{r}");
|
||||
}
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
assert!(!frame(&mut app, &ctx).contains("Saving a.vectorcraft"), "not before the delay");
|
||||
age(&mut app);
|
||||
frame(&mut app, &ctx);
|
||||
let shown = frame(&mut app, &ctx);
|
||||
assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("waiting"), "{shown}");
|
||||
assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}");
|
||||
let visible: Vec<_> = (0..6).map(|_| (frame(&mut app, &ctx), app.any_dialog_open())).collect();
|
||||
assert_eq!(app.run("file.saveInBackground", json!({})).unwrap()["hidden"], 2);
|
||||
assert!(!frame(&mut app, &ctx).contains("Saving"), "hidden saves aren't shown");
|
||||
assert!(crate::menus::enabled(&app, "file.cancelSave"), "they can still be canceled");
|
||||
go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
background::wait_all(&mut app);
|
||||
for (shown, modal) in visible {
|
||||
assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("waiting"), "{shown}");
|
||||
assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}");
|
||||
assert!(modal, "progress remains modal for input");
|
||||
}
|
||||
assert!(app.background.jobs.is_empty());
|
||||
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/docs/b.vectorcraft"));
|
||||
app.session.execute("prefs.set", &json!({"values": {"backgroundSave": false}})).unwrap();
|
||||
|
||||
@@ -4,31 +4,8 @@
|
||||
/// The Selection and Direct Selection arrows' fill, painted black or white under their outline.
|
||||
pub const DC_ARROW_FILL: &[u8] = include_bytes!("../../../assets/icons/dc-arrow-fill.svg");
|
||||
|
||||
/// VectorCraft's own `dc-*` icons, drawn with 1.5-unit strokes in a 24-unit view box.
|
||||
pub static ICONS: &[(&str, &[u8])] = &[
|
||||
("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")),
|
||||
("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")),
|
||||
("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")),
|
||||
("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")),
|
||||
("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")),
|
||||
("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")),
|
||||
("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")),
|
||||
("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")),
|
||||
("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")),
|
||||
("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")),
|
||||
("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")),
|
||||
("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")),
|
||||
("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")),
|
||||
("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")),
|
||||
("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")),
|
||||
("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")),
|
||||
("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")),
|
||||
("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")),
|
||||
("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")),
|
||||
("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")),
|
||||
// PLAN: circle-off.svg is plugins-w11's file; the row waits for it.
|
||||
("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")),
|
||||
("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")),
|
||||
("combine", include_bytes!("../../../assets/icons/combine.svg")),
|
||||
("dc-actions", include_bytes!("../../../assets/icons/dc-actions.svg")),
|
||||
("dc-al-bottom", include_bytes!("../../../assets/icons/dc-al-bottom.svg")),
|
||||
("dc-al-center", include_bytes!("../../../assets/icons/dc-al-center.svg")),
|
||||
@@ -244,6 +221,34 @@ pub static ICONS: &[(&str, &[u8])] = &[
|
||||
("dc-wrinkle", include_bytes!("../../../assets/icons/dc-wrinkle.svg")),
|
||||
("dc-zoom-large", include_bytes!("../../../assets/icons/dc-zoom-large.svg")),
|
||||
("dc-zoom-small", include_bytes!("../../../assets/icons/dc-zoom-small.svg")),
|
||||
];
|
||||
|
||||
/// Lucide icons the built-in catalog lacks, drawn with Lucide's 2-unit strokes in a 24-unit view box.
|
||||
pub static LUCIDE_ICONS: &[(&str, &[u8])] = &[
|
||||
("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")),
|
||||
("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")),
|
||||
("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")),
|
||||
("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")),
|
||||
("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")),
|
||||
("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")),
|
||||
("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")),
|
||||
("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")),
|
||||
("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")),
|
||||
("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")),
|
||||
("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")),
|
||||
("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")),
|
||||
("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")),
|
||||
("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")),
|
||||
("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")),
|
||||
("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")),
|
||||
("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")),
|
||||
("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")),
|
||||
("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")),
|
||||
("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")),
|
||||
// PLAN: circle-off.svg is plugins-w11's file; the row waits for it.
|
||||
("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")),
|
||||
("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")),
|
||||
("combine", include_bytes!("../../../assets/icons/combine.svg")),
|
||||
("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")),
|
||||
("eye-off", include_bytes!("../../../assets/icons/eye-off.svg")),
|
||||
("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")),
|
||||
|
||||
+60
-18
@@ -2,14 +2,24 @@
|
||||
|
||||
use craft::ui::primitives::{AppIcons, icon_names};
|
||||
|
||||
use crate::icon_data::{DC_ARROW_FILL, ICONS};
|
||||
use crate::icon_data::{DC_ARROW_FILL, ICONS, LUCIDE_ICONS};
|
||||
|
||||
/// The fills of the Selection and Direct Selection arrows: black and white whatever the theme, as users
|
||||
/// know them, under an outline in the theme's colour.
|
||||
const FILLS: &[(&str, &[u8], [u8; 4])] = &[("dc-selection", DC_ARROW_FILL, [0, 0, 0, 255]), ("dc-direct", DC_ARROW_FILL, [255, 255, 255, 255])];
|
||||
|
||||
/// The app's icons, for `register_app_icons`.
|
||||
pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.6), ICONS).with_fills(FILLS);
|
||||
/// The app's own icons, for `register_app_icons`. The stroke width is the documents' own, so the framework redraws
|
||||
/// their strokes at the width it draws the catalog's.
|
||||
pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.5), ICONS).with_fills(FILLS);
|
||||
|
||||
/// The Lucide icons the catalog lacks, with Lucide's own stroke width.
|
||||
pub static LUCIDE_APP_ICONS: AppIcons = AppIcons::new("vectorcraft-lucide", Some(2.0), LUCIDE_ICONS);
|
||||
|
||||
/// Registers both of the app's icon sets beside the framework's catalog.
|
||||
pub fn register() {
|
||||
craft::ui::primitives::register_app_icons(&APP_ICONS);
|
||||
craft::ui::primitives::register_app_icons(&LUCIDE_APP_ICONS);
|
||||
}
|
||||
|
||||
/// Map tool-catalogue icon names to the names of icons that resolve.
|
||||
pub fn tool_icon(name: &str) -> &'static str {
|
||||
@@ -114,23 +124,63 @@ pub fn tool_icon(name: &str) -> &'static str {
|
||||
"tool-print-tiling" => "dc-print-tiling",
|
||||
"tool-zoom" => "zoom_in",
|
||||
// A name that is already an icon maps to itself, as the `'static` name of the set that has it.
|
||||
other => icon_names().iter().copied().chain(APP_ICONS.icons.iter().map(|(n, _)| *n)).find(|n| *n == other).unwrap_or("rect_dashed"),
|
||||
other => icon_names()
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons).map(|(n, _)| *n))
|
||||
.find(|n| *n == other)
|
||||
.unwrap_or("rect_dashed"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::ui::primitives::{has_icon, register_app_icons};
|
||||
use craft::ui::primitives::has_icon;
|
||||
// PLAN: assumed the `craft` facade is a dependency of vectorcraft-ui-egui (Cargo.toml is not in this set's files; craft-ui does not re-export IconId)
|
||||
use craft::behavior::IconId;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn resolves(name: &'static str) -> bool {
|
||||
register_app_icons(&APP_ICONS);
|
||||
register();
|
||||
has_icon(&IconId::new(name))
|
||||
}
|
||||
|
||||
/// The SVG document of the app icon `name`, from either set.
|
||||
fn app_svg(name: &str) -> String {
|
||||
let (_, bytes) = ICONS.iter().chain(LUCIDE_ICONS).find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an app icon"));
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
|
||||
/// The `stroke-width` the document's root `<svg>` element sets, the width of every stroke that sets none of its
|
||||
/// own; `None` for a document drawn with fills.
|
||||
fn root_stroke_width(svg: &str) -> Option<f32> {
|
||||
let root = svg.split("<svg").nth(1)?.split('>').next()?;
|
||||
Some(root.split("stroke-width=\"").nth(1)?.split('"').next()?.parse().unwrap_or(f32::NAN))
|
||||
}
|
||||
|
||||
// Regression test: the tool rail's icons drew uneven outlines. The app set declared a 1.6-unit stroke while its own icons drew 1.5 and
|
||||
// its Lucide copies drew 2, so the framework drew them 6% thinner and 25% heavier than the catalog's icons.
|
||||
/// The framework scales every stroke in a set by the drawn width over the set's declared width, so an icon's
|
||||
/// outline matches the catalog's only when its root stroke width equals its set's declared width. Details with
|
||||
/// a width of their own keep their ratio to the outline.
|
||||
#[test]
|
||||
fn every_app_icon_draws_its_outline_at_the_catalog_width() {
|
||||
let mut off = Vec::new();
|
||||
for set in [&APP_ICONS, &LUCIDE_APP_ICONS] {
|
||||
let declared = set.stroke_width.unwrap_or_else(|| panic!("{} declares its stroke width", set.name));
|
||||
for (name, bytes) in set.icons {
|
||||
let Some(width) = root_stroke_width(&String::from_utf8_lossy(bytes)) else { continue };
|
||||
// The outline's drawn width relative to the catalog's.
|
||||
let relative = width / declared;
|
||||
if !(0.99..=1.01).contains(&relative) {
|
||||
off.push(format!("{name} in {}: {width} draws at {relative:.3} of the catalog width", set.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(off.is_empty(), "app icons whose outlines do not draw at the catalog width: {off:#?}");
|
||||
}
|
||||
|
||||
/// The ways a source line writes an icon id as a literal; a `const` that holds one is read by `const_icon`.
|
||||
const FORMS: [&str; 3] = ["IconId::new(\"", "icon(\"", "icon = \""];
|
||||
|
||||
@@ -153,7 +203,7 @@ mod tests {
|
||||
/// app's set. Other ids built in match arms and tuple tables are not scanned.
|
||||
#[test]
|
||||
fn every_icon_id_literal_and_panel_icon_resolves() {
|
||||
register_app_icons(&APP_ICONS);
|
||||
register();
|
||||
let resolves = |id: &str| has_icon(&IconId::from(std::borrow::Cow::Owned(id.to_owned())));
|
||||
let (mut seen, mut unknown) = (0, Vec::new());
|
||||
let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
|
||||
@@ -212,10 +262,7 @@ mod tests {
|
||||
// as opaque as the line, so the line vanished where it crossed the bar.
|
||||
#[test]
|
||||
fn the_cap_icons_mark_the_path_end_in_one_place_over_a_lighter_stroke() {
|
||||
let svg = |name: &str| {
|
||||
let (_, bytes) = crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an icon"));
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
};
|
||||
let svg = app_svg;
|
||||
// The end-of-path line is the icon's last shape, a vertical line `M{x} …V…`.
|
||||
let end_line = |icon: &str| -> String {
|
||||
let last = icon.rsplit("<path").next().unwrap_or_default();
|
||||
@@ -274,12 +321,7 @@ mod tests {
|
||||
// plus or a minus beside it.
|
||||
#[test]
|
||||
fn the_add_and_delete_anchor_tool_icons_are_the_pen_icon_with_a_badge() {
|
||||
let svg = |tool: &str| {
|
||||
let name = tool_icon(tool);
|
||||
let (_, bytes) =
|
||||
crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{tool} maps to {name}, which isn't an icon"));
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
};
|
||||
let svg = |tool: &str| app_svg(tool_icon(tool));
|
||||
let shapes =
|
||||
|svg: &str| svg.lines().map(|l| l.trim().to_string()).filter(|l| l.starts_with("<path") || l.starts_with("<circle")).collect::<Vec<_>>();
|
||||
let pen = shapes(&svg("tool-pen"));
|
||||
@@ -331,7 +373,7 @@ mod tests {
|
||||
assert!(resolves(name), "{} maps to {name}, which no icon set has", tool.icon);
|
||||
}
|
||||
let catalog = icon_names();
|
||||
for (name, _) in APP_ICONS.icons {
|
||||
for (name, _) in APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons) {
|
||||
assert!(!catalog.contains(name), "{name} is in the catalog: the app's copy is refused");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,13 +372,22 @@ pub struct VectorcraftApp {
|
||||
|
||||
impl VectorcraftApp {
|
||||
/// Whether a layer that takes the keys (a modal dialog, a popup) showed in the last pass, or a
|
||||
/// modal dialog opened since: a command or a canvas gesture waits while one does. A modeless
|
||||
/// dialog blocks nothing, and the job progress window does not count (its layer has the
|
||||
/// progress role). False before the app has a context.
|
||||
/// modal dialog opened since: a command or a canvas gesture waits while one does. This includes
|
||||
/// job progress, which is a modal layer.
|
||||
pub(crate) fn any_dialog_open(&self) -> bool {
|
||||
self.dialog_open(OpenFilter::Modal)
|
||||
}
|
||||
|
||||
/// Whether a question or popup is open. Applying a job's result can close its progress window.
|
||||
pub(crate) fn asking_dialog_open(&self) -> bool {
|
||||
self.dialog_open(OpenFilter::Asks)
|
||||
}
|
||||
|
||||
/// Whether a layer matching the filter, a popup or a pending app modal is open.
|
||||
fn dialog_open(&self, filter: OpenFilter) -> bool {
|
||||
// A modeless layer with a focus scope (the canvas's task bar) takes keys too, and blocks nothing.
|
||||
let popup = |ctx: &egui::Context| overlay::top(ctx).and_then(|id| overlay::entry(ctx, id)).is_some_and(|e| e.rank == overlay::Rank::Popup);
|
||||
self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, OpenFilter::Modal) || popup(ctx))
|
||||
self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, filter) || popup(ctx))
|
||||
|| self.dialogs().is_some_and(|d| d.with(|h| h.shows_modal()))
|
||||
}
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver<Result<ReadFile, S
|
||||
|
||||
/// May the active document change now ([`poll`])?
|
||||
pub(crate) fn may_switch(app: &mut VectorcraftApp) -> bool {
|
||||
if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) {
|
||||
if app.asking_dialog_open() || crate::dialogs::missing_fonts::waiting(app) {
|
||||
return false;
|
||||
}
|
||||
let s = &app.session;
|
||||
|
||||
@@ -545,16 +545,20 @@ fn a_file_that_takes_a_while_to_open_shows_a_progress_window() {
|
||||
// The app's clock stands still: a read is only old enough for its window after `age`.
|
||||
app.now_override = Some(0.0);
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
assert_eq!(progress(&mut app, &ctx), "", "nothing opening");
|
||||
start(&mut app, "/art/Big.vectorcraft", bytes("Big"));
|
||||
assert_eq!(progress(&mut app, &ctx), "", "not at once");
|
||||
age(&mut app);
|
||||
progress(&mut app, &ctx); // a new window measures itself unseen first
|
||||
let texts = progress(&mut app, &ctx);
|
||||
for want in ["Opening Big.vectorcraft…", "Reading the file…", "Cancel", "Continue in Background"] {
|
||||
assert!(texts.contains(want), "{want} in {texts}");
|
||||
for _ in 0..6 {
|
||||
let texts = progress(&mut app, &ctx);
|
||||
for want in ["Opening Big.vectorcraft…", "Reading the file…", "Cancel", "Continue in Background"] {
|
||||
assert!(texts.contains(want), "{want} in {texts}");
|
||||
}
|
||||
assert!(!texts.contains("waiting"), "{texts}");
|
||||
assert!(app.any_dialog_open(), "progress remains modal for input");
|
||||
}
|
||||
assert!(!texts.contains("waiting"), "{texts}");
|
||||
start(&mut app, "/art/Next.vectorcraft", bytes("Next"));
|
||||
let texts = progress(&mut app, &ctx);
|
||||
assert!(texts.contains("Opening Big.vectorcraft…") && texts.contains("waiting"), "{texts}");
|
||||
@@ -569,6 +573,24 @@ fn a_file_that_takes_a_while_to_open_shows_a_progress_window() {
|
||||
assert_eq!(app.session.documents().len(), before + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_ready_while_progress_is_visible_opens_without_hiding_progress() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
app.now_override = Some(0.0);
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
start(&mut app, "/art/Big.vectorcraft", bytes("Big"));
|
||||
age(&mut app);
|
||||
progress(&mut app, &ctx);
|
||||
assert!(progress(&mut app, &ctx).contains("Opening Big.vectorcraft"));
|
||||
assert!(app.any_dialog_open());
|
||||
|
||||
open_ready(&mut app);
|
||||
assert!(app.opening.pending.is_empty());
|
||||
assert_eq!(app.session.doc().unwrap().path.as_deref(), Some("/art/Big.vectorcraft"));
|
||||
assert_eq!(progress(&mut app, &ctx), "", "completion closes progress");
|
||||
}
|
||||
|
||||
/// #5930: the progress window's Cancel (`file.cancelOpen`): the file doesn't open, even once it
|
||||
/// has been read, and the status bar no longer says it is opening.
|
||||
#[test]
|
||||
|
||||
@@ -341,7 +341,7 @@ fn rows_list_by_depth_and_ruler_guide_nodes_get_no_object_row() {
|
||||
/// guide kind's ruler, and both glyphs are in the app's icon set.
|
||||
#[test]
|
||||
fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() {
|
||||
use craft::ui::primitives::{has_icon, register_app_icons};
|
||||
use craft::ui::primitives::has_icon;
|
||||
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
@@ -355,7 +355,7 @@ fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() {
|
||||
};
|
||||
let (across, down) = (icon_of(false), icon_of(true));
|
||||
assert_ne!(across, down, "the two kinds of guide rows look alike");
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
crate::icons::register();
|
||||
for icon in [&across, &down] {
|
||||
assert!(has_icon(icon), "{icon:?} is in no icon set, so the row draws nothing");
|
||||
}
|
||||
|
||||
@@ -445,7 +445,7 @@ fn spawn_labeled(
|
||||
/// the file is placed unless the tool has a preview open (the Flare tool after its center drag).
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
settle_swatch_paste(app);
|
||||
while !app.any_dialog_open()
|
||||
while !app.asking_dialog_open()
|
||||
&& !app.session.in_interaction()
|
||||
&& !(app.session.tool_busy() && app.session.pointer_held())
|
||||
&& let Some(p) = app.placing.pending.first()
|
||||
|
||||
@@ -1980,6 +1980,7 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() {
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
assert_eq!(progress(&mut app, &ctx), "", "nothing placing");
|
||||
|
||||
let slow_path = saved("progress", "slow.png", &picture(Png, 100, 100));
|
||||
@@ -2002,10 +2003,12 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() {
|
||||
start(&mut app, &json!({"path": next_path, "at": [200, 150]}), false).unwrap();
|
||||
let texts = progress(&mut app, &ctx);
|
||||
assert!(texts.contains("Placing slow.png…") && texts.contains("waiting"), "{texts}");
|
||||
assert!(app.any_dialog_open());
|
||||
|
||||
// Release and finish
|
||||
// Releasing the read applies both files without dismissing the progress window first.
|
||||
drop(go);
|
||||
placed(&mut app);
|
||||
assert_eq!(progress(&mut app, &ctx), "", "completion closes progress");
|
||||
}
|
||||
|
||||
/// #5930: cancelling a place aborts the operation, drops the parsed asset, leaves the document
|
||||
|
||||
@@ -458,7 +458,7 @@ pub fn poll(app: &mut VectorcraftApp) {
|
||||
poll_checks(app);
|
||||
let mut i = 0;
|
||||
while let Some(r) = app.plugin_runs.running.get(i) {
|
||||
let dialog = app.any_dialog_open() || app.session.script_running();
|
||||
let dialog = app.asking_dialog_open() || app.session.script_running();
|
||||
let ended = match &r.backend {
|
||||
Backend::Thread(_) if dialog => None,
|
||||
Backend::Worker(..) if dialog => watch_worker(app, i),
|
||||
|
||||
@@ -130,7 +130,7 @@ fn stop(app: &mut VectorcraftApp) {
|
||||
/// Runs the command of the search that is done (each frame). Not while a dialog is open, nor while
|
||||
/// an interaction is open or a tool drags with the pointer button held, as [`crate::trace_runs::poll`].
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) {
|
||||
if app.asking_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) {
|
||||
return;
|
||||
}
|
||||
let Some(r) = &app.retype_runs.running else { return };
|
||||
|
||||
@@ -11,7 +11,7 @@ fn the_cut_tools_have_their_own_icons_and_toolbar_slot() {
|
||||
let info = vectorcraft_tools::tool_info(tool).unwrap();
|
||||
assert_eq!(icons::tool_icon(info.icon), icon);
|
||||
// The app registers its icons at start; a test run alone in its process must too.
|
||||
craft::ui::primitives::register_app_icons(&icons::APP_ICONS);
|
||||
icons::register();
|
||||
assert!(craft::ui::primitives::has_icon(&IconId::new(icon)), "{icon}");
|
||||
assert!(crate::toolbar::BASIC.iter().flat_map(|(_, slots)| slots.iter()).any(|s| s.contains(&tool) && s.contains(&"knife")));
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ pub fn start(app: &mut VectorcraftApp, command: &str, p: Value, from_panel: bool
|
||||
/// dialog is open (its OK acts on the active document, which a trace's result changes), nor while
|
||||
/// an interaction is open or a tool drags with the pointer button held, as [`crate::placing::poll`].
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) {
|
||||
if app.asking_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) {
|
||||
return;
|
||||
}
|
||||
let mut i = 0;
|
||||
|
||||
@@ -164,10 +164,22 @@ fn menu_access_custom_shortcut_typing_tool_altgr_and_cancel_ownership() {
|
||||
assert_eq!(s.app.session.tool_id(), "pen", "after the dismissal the letter selects its tool");
|
||||
s.app.select_tool("selection");
|
||||
|
||||
// While the bar holds the keys after a lone Alt, the letter does not reach the tool either.
|
||||
// A lone Alt over the canvas is a tool modifier let go: the bar does not take the keys, and the next tool
|
||||
// letters choose their tools instead of opening View or Window.
|
||||
s.bare_alt();
|
||||
s.settle();
|
||||
assert!(is_focused(&s.ctx), "a lone Alt gives the bar the keys");
|
||||
assert!(!is_focused(&s.ctx) && !is_open(&s.ctx), "a lone Alt over the canvas leaves the bar alone");
|
||||
s.letter(Key::V, "v", Modifiers::NONE);
|
||||
assert!(!is_open(&s.ctx), "V after a lone Alt opens no menu");
|
||||
s.letter(Key::P, "p", Modifiers::NONE);
|
||||
assert_eq!(s.app.session.tool_id(), "pen", "P after a lone Alt chooses the Pen");
|
||||
s.app.select_tool("selection");
|
||||
|
||||
// While the bar holds the keys after F10, the letter does not reach the tool.
|
||||
s.frame(vec![key(Key::F10, true, Modifiers::NONE)]);
|
||||
s.frame(vec![key(Key::F10, false, Modifiers::NONE)]);
|
||||
s.settle();
|
||||
assert!(is_focused(&s.ctx), "F10 gives the bar the keys");
|
||||
s.letter(Key::P, "p", Modifiers::NONE);
|
||||
assert_eq!(s.app.session.tool_id(), "selection", "a focused bar takes the letter");
|
||||
s.click(outside);
|
||||
|
||||
@@ -36,6 +36,11 @@ def earlier(conclusion):
|
||||
return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}]
|
||||
|
||||
|
||||
def split_job(shard, status, completed_at=None):
|
||||
return {"name": f"gate / cache warm {shard}/5 (ubuntu-24.04)", "status": status,
|
||||
"conclusion": "success" if status == "completed" else None, "completed_at": completed_at}
|
||||
|
||||
|
||||
class SaveStep(unittest.TestCase):
|
||||
def test_the_leg_is_saving_once_its_save_step_starts(self):
|
||||
self.assertFalse(clear.saving(warm_job("in_progress", steps=[("Setup", "completed", "success"), ("Gate", "in_progress", None)])))
|
||||
@@ -99,6 +104,34 @@ class Deadline(unittest.TestCase):
|
||||
self.assertFalse(clear.started_late(warm_job("queued"), self.began))
|
||||
self.assertFalse(clear.started_late(None, self.began))
|
||||
|
||||
def test_split_progress_suspends_the_start_deadline(self):
|
||||
for status in ("queued", "in_progress"):
|
||||
with self.subTest(status=status):
|
||||
jobs = [split_job(1, "completed", "2026-11-28T06:00:00Z"), split_job(2, status)]
|
||||
ready = clear.start_wait_began(jobs, self.began)
|
||||
self.assertIsNone(ready)
|
||||
now = self.began + timedelta(seconds=clear.START_SECONDS + 60)
|
||||
self.assertFalse(clear.start_overdue(None, now, ready))
|
||||
self.assertFalse(clear.started_late(warm_job("in_progress", started_at=now.isoformat()), ready))
|
||||
|
||||
def test_the_last_split_completion_starts_the_wait(self):
|
||||
jobs = [split_job(1, "completed", "2026-11-28T08:00:00Z"),
|
||||
split_job(2, "completed", "2026-11-28T07:00:00Z")]
|
||||
ready = clear.start_wait_began(jobs, self.began)
|
||||
self.assertEqual(ready, clear.parse_time("2026-11-28T08:00:00Z"))
|
||||
self.assertFalse(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS), ready))
|
||||
self.assertTrue(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS + 1), ready))
|
||||
self.assertFalse(clear.started_late(warm_job("in_progress", started_at="2026-11-28T08:01:00Z"), ready))
|
||||
late = warm_job("in_progress", started_at=(ready + timedelta(seconds=clear.START_SECONDS + 1)).isoformat())
|
||||
self.assertTrue(clear.started_late(late, ready))
|
||||
|
||||
def test_without_split_legs_the_script_start_starts_the_wait(self):
|
||||
self.assertEqual(clear.start_wait_began([], self.began), self.began)
|
||||
self.assertEqual(clear.start_wait_began(ME + [warm_job("queued")], self.began), self.began)
|
||||
|
||||
def test_a_split_completion_without_a_timestamp_does_not_start_the_wait(self):
|
||||
self.assertIsNone(clear.start_wait_began([split_job(1, "completed")], self.began))
|
||||
|
||||
|
||||
class Workflow(unittest.TestCase):
|
||||
ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text()
|
||||
@@ -116,10 +149,17 @@ class Workflow(unittest.TestCase):
|
||||
self.fail(f"no timeout-minutes under {job}")
|
||||
|
||||
def test_the_job_outlasts_the_start_wait_and_the_save_wait(self):
|
||||
# Five minutes are left for the steps before the script and for the deletion.
|
||||
# Without split legs, five minutes remain for setup and deletion.
|
||||
spare = self.timeout_minutes("cold-cache-clear") * 60 - clear.START_SECONDS - clear.GIVE_UP_SECONDS
|
||||
self.assertGreaterEqual(spare, 5 * 60)
|
||||
|
||||
def test_the_job_allows_both_warm_builds_within_the_hosted_job_limit(self):
|
||||
# Runner waits and the full start allowance may exceed the 360-minute job limit.
|
||||
timeout = self.timeout_minutes("cold-cache-clear")
|
||||
spare = timeout * 60 - self.timeout_minutes("gate") * 60 - clear.GIVE_UP_SECONDS
|
||||
self.assertGreaterEqual(spare, 5 * 60)
|
||||
self.assertEqual(timeout, 360)
|
||||
|
||||
def test_the_save_wait_outlasts_the_gate(self):
|
||||
self.assertGreater(clear.GIVE_UP_SECONDS, self.timeout_minutes("gate") * 60)
|
||||
|
||||
@@ -156,6 +196,9 @@ class Jobs(unittest.TestCase):
|
||||
self.assertTrue(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (ubuntu-24.04)", "cancelled")]))
|
||||
self.assertFalse(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (${{ matrix.os }})", "skipped")]))
|
||||
self.assertFalse(clear.legs_stopped([done("gate / test 1/5 (ubuntu-24.04)", "failure")]))
|
||||
# With warm-split, the saving `cache warm (<os>)` leg also needs every `cache warm <k>/<N>` leg.
|
||||
self.assertTrue(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "failure")]))
|
||||
self.assertFalse(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "success")]))
|
||||
|
||||
|
||||
class Caches(unittest.TestCase):
|
||||
@@ -192,6 +235,60 @@ class Clock(datetime):
|
||||
return datetime(2026, 11, 28, 4, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
class BeforeSaving(unittest.TestCase):
|
||||
def run_main(self, polls):
|
||||
began = Clock.now()
|
||||
current = began
|
||||
remaining = iter(polls)
|
||||
|
||||
class PollClock(datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return current
|
||||
|
||||
def gh(url):
|
||||
nonlocal current
|
||||
if "/jobs?" in url:
|
||||
minutes, jobs = next(remaining)
|
||||
current = began + timedelta(minutes=minutes)
|
||||
return {"jobs": ME + jobs}
|
||||
if "/caches?" in url:
|
||||
return {"actions_caches": []}
|
||||
return {"run_started_at": began.isoformat()}
|
||||
|
||||
env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"}
|
||||
with mock.patch.object(clear, "gh", gh), mock.patch.object(clear.time, "sleep"), \
|
||||
mock.patch.object(clear, "datetime", PollClock), mock.patch.dict(os.environ, env), \
|
||||
mock.patch.object(clear.subprocess, "run") as delete, contextlib.redirect_stdout(io.StringIO()):
|
||||
status = clear.main()
|
||||
delete.assert_not_called()
|
||||
return status
|
||||
|
||||
def test_queued_and_running_split_legs_can_outlast_the_original_start_deadline(self):
|
||||
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
|
||||
saved = warm_job("completed", "success", [("Post Setup", "completed", "success")],
|
||||
started_at="2026-11-28T07:50:00Z")
|
||||
self.assertFalse(self.run_main([
|
||||
(181, [split_job(1, "queued")]),
|
||||
(201, [split_job(1, "in_progress"), warm_job("queued")]),
|
||||
(220, [done, warm_job("queued")]),
|
||||
(230, [done, saved]),
|
||||
]))
|
||||
|
||||
def test_a_saving_leg_that_never_starts_expires_after_the_last_split_completion(self):
|
||||
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
|
||||
self.assertEqual(self.run_main([
|
||||
(220, [done, warm_job("queued")]),
|
||||
(401, [done, warm_job("queued")]),
|
||||
]), 1)
|
||||
|
||||
def test_a_late_start_after_split_completion_is_rejected_even_if_already_saving(self):
|
||||
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
|
||||
late = warm_job("in_progress", steps=[("Post Setup", "in_progress", None)],
|
||||
started_at="2026-11-28T10:40:01Z")
|
||||
self.assertEqual(self.run_main([(401, [done, late])]), 1)
|
||||
|
||||
|
||||
class AfterDeletion(unittest.TestCase):
|
||||
SAVING = [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]
|
||||
|
||||
@@ -230,9 +327,17 @@ class AfterDeletion(unittest.TestCase):
|
||||
canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")])
|
||||
self.assertEqual(self.run_main(canceled), 1)
|
||||
|
||||
def test_a_saving_leg_skipped_after_a_failed_split_warm_leg_fails_this_job(self):
|
||||
skipped = warm_job("completed", conclusion="skipped")
|
||||
failed = {"name": "gate / cache warm 2/5 (ubuntu-24.04)", "status": "completed", "conclusion": "failure"}
|
||||
env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"}
|
||||
with mock.patch.object(clear, "gh", lambda url: {"jobs": ME + [failed, skipped]}), mock.patch.object(clear.time, "sleep"), \
|
||||
mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(clear.main(), 1)
|
||||
|
||||
def test_a_leg_that_starts_late_and_saves_deletes_nothing(self):
|
||||
# Clock.now() is 04:00, so the leg starts 120 minutes 5 seconds after the script.
|
||||
late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T06:00:05Z")
|
||||
# Clock.now() is 04:00, so the leg starts 180 minutes 5 seconds after the script.
|
||||
late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T07:00:05Z")
|
||||
deleted = []
|
||||
|
||||
def run(args, **kwargs):
|
||||
|
||||
@@ -16,8 +16,10 @@ save step started saves nothing: its old entries stay, and this exits 1, so "Re-
|
||||
runs it again beside the re-run leg. A save step that is canceled or fails after the old entries
|
||||
were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure
|
||||
in a later post step does not count once the save step has succeeded. This also exits 1 when the
|
||||
leg has not started START_SECONDS after this script started, and when the leg has not reached its
|
||||
save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only
|
||||
leg has not started START_SECONDS after the last split warm leg completed (or after this script
|
||||
started when there are no split legs). The start deadline does not expire while a split leg is
|
||||
queued or running. This exits 1 when the leg has not reached its save, or its save has not finished,
|
||||
GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only
|
||||
when the most recent earlier attempt that lists it reports success and the current attempt still
|
||||
lists no `gate / select legs` job RERUN_GRACE_SECONDS after this script started: "Re-run all
|
||||
jobs" lists that job from its start, and "Re-run failed jobs" after a successful leg does not.
|
||||
@@ -34,9 +36,11 @@ import time
|
||||
|
||||
REF = 'refs/heads/main'
|
||||
WARM_JOB = re.compile(r'^gate / cache warm \(')
|
||||
SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(')
|
||||
# The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of
|
||||
# them fails or is canceled, the legs are skipped and no warm leg is listed.
|
||||
NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()')
|
||||
# them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the
|
||||
# saving leg also needs every `cache warm <k>/<N>` leg.
|
||||
NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \(|cache warm \d+/\d+ \()')
|
||||
# The gate's first job. "Re-run all jobs" lists it; "Re-run failed jobs" lists it only when it
|
||||
# failed, and then no warm leg succeeded before.
|
||||
SELECT_JOB = 'gate / select legs'
|
||||
@@ -52,12 +56,11 @@ PAGE_SIZE = 100
|
||||
# Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold
|
||||
# leg that starts late and runs to its limit still reaches its save before this gives up.
|
||||
GIVE_UP_SECONDS = 160 * 60
|
||||
# How long the leg may take to start, timed from this script's start: the leg waits for
|
||||
# `gate / select legs` and then for a runner, which took 44 minutes on a push to main on
|
||||
# 2026-11-28. The `cold-cache-clear` job's `timeout-minutes` in ci.yml is longer than
|
||||
# START_SECONDS and GIVE_UP_SECONDS together, so this exits with its own error before the job
|
||||
# times out.
|
||||
START_SECONDS = 120 * 60
|
||||
# How long the saving leg may take to start after the last split warm leg completed, or after
|
||||
# this script started when there are no split legs. Queued or running split legs suspend this
|
||||
# deadline. The `cold-cache-clear` job's 360-minute timeout in ci.yml can end the wait before
|
||||
# this deadline or GIVE_UP_SECONDS expires when split builds or runner waits take too long.
|
||||
START_SECONDS = 180 * 60
|
||||
STOPPED = ('failure', 'cancelled', 'timed_out')
|
||||
# Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml.
|
||||
TOLERATED_FAILURES = ('Trim the cache entry to this build',)
|
||||
@@ -103,16 +106,25 @@ def started_at(job):
|
||||
return parse_time(started) if started else None
|
||||
|
||||
|
||||
def start_wait_began(jobs, began):
|
||||
"""The last split warm completion, the script's start without splits, or None while waiting."""
|
||||
splits = [j for j in jobs if SPLIT_WARM_JOB.match(j['name'])]
|
||||
if not splits:
|
||||
return began
|
||||
if any(j['status'] != 'completed' or not j.get('completed_at') for j in splits):
|
||||
return None
|
||||
return max(parse_time(j['completed_at']) for j in splits)
|
||||
|
||||
|
||||
def start_overdue(job, now, began):
|
||||
"""True once START_SECONDS have passed since `began` (this script's start) and the warm leg
|
||||
has not started."""
|
||||
return started_at(job) is None and (now - began).total_seconds() > START_SECONDS
|
||||
"""True once START_SECONDS have passed since the start wait began and the leg has not started."""
|
||||
return began is not None and started_at(job) is None and (now - began).total_seconds() > START_SECONDS
|
||||
|
||||
|
||||
def started_late(job, began):
|
||||
"""True when the warm leg started more than START_SECONDS after `began` (this script's start)."""
|
||||
"""True when the warm leg started more than START_SECONDS after the start wait began."""
|
||||
started = started_at(job)
|
||||
return started is not None and (started - began).total_seconds() > START_SECONDS
|
||||
return began is not None and started is not None and (started - began).total_seconds() > START_SECONDS
|
||||
|
||||
|
||||
def gave_up(job, now):
|
||||
@@ -180,7 +192,8 @@ def main():
|
||||
while True:
|
||||
jobs = gh(jobs_url) or {}
|
||||
job = warm_job(jobs.get('jobs', []))
|
||||
if started_late(job, began):
|
||||
ready = start_wait_began(jobs.get('jobs', []), began)
|
||||
if started_late(job, ready):
|
||||
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
return 1
|
||||
if job and saving(job):
|
||||
@@ -199,13 +212,14 @@ def main():
|
||||
print('::error::the gate stopped before its cache warm leg started; nothing deleted')
|
||||
return 1
|
||||
if job and job['status'] == 'completed':
|
||||
if job.get('conclusion') in STOPPED:
|
||||
# A saving leg skipped because a leg it needs failed (a `cache warm <k>/<N>` leg).
|
||||
if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])):
|
||||
print(f'::error::{NO_SAVE}')
|
||||
return 1
|
||||
print('the cache warm leg finished without a save step; nothing deleted')
|
||||
return
|
||||
now = datetime.now(timezone.utc)
|
||||
if start_overdue(job, now, began):
|
||||
if start_overdue(job, now, ready):
|
||||
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
return 1
|
||||
if gave_up(job, now):
|
||||
|
||||
+23
-7
@@ -50,6 +50,7 @@ commands:
|
||||
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs
|
||||
the tests and doctests of its crates, the last shard the other steps
|
||||
ci warm build what every shard builds, without running it (fills the gate's cache); with
|
||||
GATE_SHARD of GATE_SHARDS set, only what that shard builds; with
|
||||
CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file
|
||||
shards list the crates each shard tests; fails when a member is in no shard or in two,
|
||||
or builds with other features in its shard than in the whole workspace
|
||||
@@ -411,18 +412,26 @@ fn cmd_ci_shard() -> Result<(), String> {
|
||||
/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that
|
||||
/// only an integration test uses.
|
||||
///
|
||||
/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that
|
||||
/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build
|
||||
/// nothing in either case, since part 1 builds the same tests.
|
||||
///
|
||||
/// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS`
|
||||
/// (xtask/src/cache_units.rs), xtask's own build included.
|
||||
fn cmd_ci_warm() -> Result<(), String> {
|
||||
let var = |key: &str| match std::env::var(key) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")),
|
||||
};
|
||||
let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?);
|
||||
let only = shards::warm_only(shard.as_deref(), count.as_deref())?;
|
||||
cache_units::record_xtask()?;
|
||||
let checked = shards::run()?;
|
||||
let (tests, checks) = shards::warm_plan(&checked, only);
|
||||
let mut steps: Vec<Step> = Vec::new();
|
||||
for shard in checked {
|
||||
// A split's later parts build the same tests as its first.
|
||||
if let shards::Shard::Tests(crates, part) = shard {
|
||||
if part.is_some_and(|p| !p.is_first()) {
|
||||
continue;
|
||||
}
|
||||
for i in tests {
|
||||
if let shards::Shard::Tests(crates, _) = checked[i].clone() {
|
||||
steps.push((
|
||||
"build tests",
|
||||
Box::new(move || {
|
||||
@@ -432,6 +441,14 @@ fn cmd_ci_warm() -> Result<(), String> {
|
||||
));
|
||||
}
|
||||
}
|
||||
if checks {
|
||||
push_warm_checks(&mut steps);
|
||||
}
|
||||
run_steps(&steps)
|
||||
}
|
||||
|
||||
/// The builds of the checks shard that [`cmd_ci_warm`] runs.
|
||||
fn push_warm_checks(steps: &mut Vec<Step>) {
|
||||
steps.push((
|
||||
"clippy",
|
||||
Box::new(|| {
|
||||
@@ -455,7 +472,6 @@ fn cmd_ci_warm() -> Result<(), String> {
|
||||
}),
|
||||
));
|
||||
steps.push(("wasm", Box::new(cmd_wasm)));
|
||||
run_steps(&steps)
|
||||
}
|
||||
|
||||
/// The command `ci warm` builds one test shard's tests with, and its description.
|
||||
|
||||
@@ -364,10 +364,107 @@ pub fn run() -> Result<Vec<Shard>, String> {
|
||||
Ok(shards)
|
||||
}
|
||||
|
||||
/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's
|
||||
/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one,
|
||||
/// a value that is not a number, a count other than the number of shards, or a shard out of range
|
||||
/// is an error.
|
||||
pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result<Option<usize>, String> {
|
||||
let (shard, count) = match (shard, count) {
|
||||
(None, None) => return Ok(None),
|
||||
(Some(shard), Some(count)) => (shard, count),
|
||||
_ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()),
|
||||
};
|
||||
let number =
|
||||
|key: &str, value: &str| -> Result<usize, String> { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) };
|
||||
let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?);
|
||||
if count != GROUPS.len() {
|
||||
return Err(format!(
|
||||
"ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
|
||||
GROUPS.len()
|
||||
));
|
||||
}
|
||||
if !(1..=count).contains(&shard) {
|
||||
return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}"));
|
||||
}
|
||||
Ok(Some(shard - 1))
|
||||
}
|
||||
|
||||
/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it
|
||||
/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it
|
||||
/// builds that shard alone, and without it every shard. A split's later parts build nothing: they
|
||||
/// build the same tests as part 1, whose leg puts them in the cache.
|
||||
pub fn warm_plan(shards: &[Shard], only: Option<usize>) -> (Vec<usize>, bool) {
|
||||
let mut tests = Vec::new();
|
||||
let mut checks = false;
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
if only.is_some_and(|k| k != i) {
|
||||
continue;
|
||||
}
|
||||
match shard {
|
||||
Shard::Checks => checks = true,
|
||||
Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {}
|
||||
Shard::Tests(..) => tests.push(i),
|
||||
}
|
||||
}
|
||||
(tests, checks)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warm_builds_every_shard_unless_the_gate_names_one() {
|
||||
let n = GROUPS.len().to_string();
|
||||
assert_eq!(warm_only(None, None), Ok(None));
|
||||
assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0)));
|
||||
assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1)));
|
||||
for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] {
|
||||
assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}");
|
||||
}
|
||||
let past = (GROUPS.len() + 1).to_string();
|
||||
assert!(warm_only(Some(&past), Some(&n)).is_err());
|
||||
assert!(warm_only(Some("1"), Some(&past)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_builds_each_shard_of_the_plan() {
|
||||
let ws = [m("a"), m("b")];
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(warm_plan(&shards, None), (vec![0, 2], true));
|
||||
assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false));
|
||||
assert_eq!(warm_plan(&shards, Some(1)), (vec![], false));
|
||||
assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false));
|
||||
assert_eq!(warm_plan(&shards, Some(3)), (vec![], true));
|
||||
// The real plan: every leg the gate names builds its own shard (a split's later part
|
||||
// builds nothing), and the legs together, like a full warm, build every crate's tests
|
||||
// once and the checks.
|
||||
let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap();
|
||||
let mut owned: Vec<&str> = real.iter().flat_map(owners).collect();
|
||||
owned.sort_unstable();
|
||||
let (mut legs, mut leg_checks) = (Vec::new(), 0);
|
||||
for i in 0..GROUPS.len() {
|
||||
let n = GROUPS.len().to_string();
|
||||
let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap();
|
||||
let (tests, checks) = warm_plan(&real, only);
|
||||
let want = match &real[i] {
|
||||
Shard::Checks => (vec![], true),
|
||||
Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false),
|
||||
Shard::Tests(..) => (vec![i], false),
|
||||
};
|
||||
assert_eq!((tests.clone(), checks), want, "shard {}", i + 1);
|
||||
legs.extend(tests);
|
||||
leg_checks += usize::from(checks);
|
||||
}
|
||||
let (tests, checks) = warm_plan(&real, None);
|
||||
assert!(checks);
|
||||
assert_eq!(leg_checks, 1);
|
||||
assert_eq!(tests, legs);
|
||||
let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect();
|
||||
built.sort_unstable();
|
||||
assert_eq!(built, owned);
|
||||
}
|
||||
|
||||
fn m(name: &str) -> Member {
|
||||
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user