Merge main into fix/three-d-dialog-tests

This commit is contained in:
dotCooCoo committed 2026-11-28 12:03:06 -08:00
commit c4c672a855
25 files changed
+758 -63

No files matched your search

+3 -3
View File
@@ -4,10 +4,10 @@
"repository_id": 1398097510,
"producer_workflow_id": 430275079,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
+16 -2
View File
@@ -34,12 +34,26 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: vectorcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+2 -2
View File
@@ -22,9 +22,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: vectorcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
+111
View File
@@ -7,11 +7,17 @@
//! fails in a Flatpak sandbox (`XCURSOR_PATH` unset, no cursor theme in the runtime) and where the
//! `default` theme is a dangling symlink; the desktop's own setting names a theme that loads.
//!
//! Where no cursor theme can be found at all (KDE or sway without gsettings), the env fix does
//! nothing: [`shell_caps`] leaves out [`Caps::SYSTEM_CURSOR`], and the framework keeps the system
//! pointer and paints no tool cursor beside it (#5311).
//!
//! This reads the desktop's cursor theme and size and sets what the user left unset, once, before
//! any thread starts and before the window opens.
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
use craft::host::target::Caps;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
/// Where a Flatpak sandbox mounts the host's cursor themes (user and system).
const FLATPAK_HOST_ICONS: [&str; 2] = ["/run/host/user-share/icons", "/run/host/share/icons"];
@@ -48,6 +54,74 @@ pub fn plan(var: impl Fn(&str) -> Option<OsString>, host_icons: &[&str], desktop
out
}
/// Xcursor's default search path when `XCURSOR_PATH` is unset (relative entries are in `$HOME`).
const DEFAULT_ICON_DIRS: [&str; 5] = ["~/.local/share/icons", "~/.icons", "/usr/share/icons", "/usr/share/pixmaps", "/usr/X11R6/lib/X11/icons"];
/// The themes `index.theme` lists after `Inherits=`.
fn inherits(index: &str) -> Vec<String> {
index
.lines()
.find_map(|l| l.trim().strip_prefix("Inherits="))
.map(|v| v.split([',', ';']).map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect())
.unwrap_or_default()
}
/// Can Xcursor load a pointer for the environment's theme (`XCURSOR_THEME`, else `default`)? It does
/// when the theme, or one it inherits from, has a `default` or `left_ptr` cursor file in a folder of
/// `XCURSOR_PATH` (else Xcursor's default folders). `read` returns a file's text, `exists` tells
/// whether a file is there.
pub fn theme_usable(
var: impl Fn(&str) -> Option<OsString>,
home: Option<&Path>,
read: impl Fn(&Path) -> Option<String>,
exists: impl Fn(&Path) -> bool,
) -> bool {
let dirs: Vec<PathBuf> = match var("XCURSOR_PATH").filter(|v| !v.is_empty()) {
Some(v) => std::env::split_paths(&v).collect(),
None => DEFAULT_ICON_DIRS
.iter()
.filter_map(|d| match d.strip_prefix("~/") {
Some(rest) => home.map(|h| h.join(rest)),
None => Some(PathBuf::from(d)),
})
.collect(),
};
let first = var("XCURSOR_THEME").and_then(|v| v.into_string().ok()).filter(|t| !t.is_empty()).unwrap_or_else(|| "default".into());
let mut todo = vec![first];
let mut seen: Vec<String> = Vec::new();
while let Some(theme) = todo.pop() {
// Bounded: themes inherit in short chains, and a cycle must end.
if seen.contains(&theme) || seen.len() >= 16 {
continue;
}
for dir in &dirs {
let base = dir.join(&theme);
if ["default", "left_ptr"].iter().any(|c| exists(&base.join("cursors").join(c))) {
return true;
}
if let Some(index) = read(&base.join("index.theme")) {
todo.extend(inherits(&index));
}
}
seen.push(theme);
}
false
}
/// On this machine, after [`apply`]: is there no cursor theme Xcursor can load? Then winit never
/// sets a pointer, and a hidden system pointer does not come back (#2450).
pub fn theme_missing() -> bool {
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
!theme_usable(|n| std::env::var_os(n), home.as_deref(), |p| std::fs::read_to_string(p).ok(), |p| p.exists())
}
/// The shell's capabilities `caps`, without [`Caps::SYSTEM_CURSOR`] when the window opens on
/// Wayland and `theme_missing` finds no cursor theme. The framework then keeps the system pointer
/// and paints no tool cursor beside it (#5311). `theme_missing` runs only on Wayland.
pub fn shell_caps(caps: Caps, wayland: bool, theme_missing: impl FnOnce() -> bool) -> Caps {
if wayland && theme_missing() { caps.difference(Caps::SYSTEM_CURSOR) } else { caps }
}
/// The value of a `gsettings get` line: `'Adwaita'` becomes `Adwaita`, `24` stays `24`.
fn gsettings_value(output: &str) -> &str {
output.trim().trim_matches('\'')
@@ -113,6 +187,43 @@ mod tests {
assert!(plan(env(&[("WAYLAND_DISPLAY", "wayland-0")]), &[], odd).is_empty());
}
#[test]
fn a_theme_is_usable_directly_or_through_inherits_and_missing_otherwise() {
let files = ["/i/Bibata/cursors/left_ptr", "/i/Breeze/index.theme", "/i/Loop/index.theme"];
// Compared as paths, so the joins match on Windows too, where they use `\`.
let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p);
let read = |p: &Path| {
if p == Path::new("/i/Breeze/index.theme") {
Some("[Icon Theme]\nInherits=Other, Bibata\n".to_owned())
} else if p == Path::new("/i/Loop/index.theme") {
Some("Inherits=Loop\n".to_owned())
} else {
None
}
};
let with = |theme: &'static str| {
move |n: &str| (n == "XCURSOR_PATH").then(|| OsString::from("/i")).or((n == "XCURSOR_THEME").then(|| OsString::from(theme)))
};
assert!(theme_usable(with("Bibata"), None, read, exists));
assert!(theme_usable(with("Breeze"), None, read, exists));
// No such theme, a theme without cursors, an inheritance loop: nothing to load.
assert!(!theme_usable(with("Nope"), None, read, exists));
assert!(!theme_usable(with("Loop"), None, read, exists));
// Unset: Xcursor's default folders and the `default` theme.
assert!(!theme_usable(|_| None, Some(Path::new("/home/u")), read, exists));
}
#[test]
fn without_a_cursor_theme_on_wayland_the_system_pointer_stays_alone() {
let native = Caps::native(craft::host::target::Os::Linux);
assert!(native.contains(Caps::SYSTEM_CURSOR));
let without = shell_caps(native, true, || true);
assert!(!without.contains(Caps::SYSTEM_CURSOR), "Wayland with no cursor theme: no painted cursor beside the system pointer");
assert_eq!(without.union(Caps::SYSTEM_CURSOR), native, "only the system cursor is left out");
assert_eq!(shell_caps(native, true, || false), native, "Wayland with a theme");
assert_eq!(shell_caps(native, false, || panic!("the theme is looked up only on Wayland")), native, "X11 and XWayland");
}
#[test]
fn gsettings_output_is_unquoted() {
assert_eq!(gsettings_value("'Adwaita'\n"), "Adwaita");
+5
View File
@@ -667,6 +667,11 @@ fn main() -> std::process::ExitCode {
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
// Preferences › User Interface › System Title Bar.
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
// beside it (#2450, #5311).
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
let shell_info = shell_info.caps(caps);
let titlebar_pref =
if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated };
let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref);
+111 -2
View File
@@ -175,7 +175,16 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>,
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
let target = chosen.join(name);
match std::fs::symlink_metadata(&target) {
Ok(metadata) if !metadata.is_dir() => {
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
let child = canonical_future(&target)?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
@@ -192,11 +201,86 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(all(windows, feature = "wgpu"))]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) || info.dwFileAttributes.has(co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(all(windows, not(feature = "wgpu")))]
{
use std::os::windows::fs::MetadataExt as _;
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
return Err("the nightly profile file must not be an alias or directory".into());
}
}
let _ = (path, metadata);
Ok(())
}
const PROFILE_FOLDERS: [&str; 18] = [
"Data Recovery",
"Fonts",
"logs",
"Launch",
"Color Profiles",
"Plug-ins",
"Scripts",
"Startup Scripts",
"Metadata Templates",
"New Document Profiles",
"Proof Setups",
"Script Data",
"PDF Presets",
"Swatches",
"Graphic Styles",
"Symbols",
"Brushes",
"Libraries",
];
/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to
/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated
/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile.
@@ -557,6 +641,31 @@ mod tests {
assert!(result.unwrap_err().contains("not writable"));
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn the_platform_case_rules_are_the_file_systems_ones() {
let fixture = Fixture::new();
+4
View File
@@ -945,6 +945,10 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option<Paint>, opacity
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
let for_tool = tool_color_params(s, p, cmd, !fill)?;
let p = for_tool.as_ref().unwrap_or(p);
// A bad `target` or `aligned` is refused for every kind of target: `item_target` reads no
// `target` once `id` or `ids` names an object, and selected characters read neither.
super::appearance::aligned(p, cmd)?;
super::appearance::targets_contents(p)?;
let focus = switch_or(p, "focus", true, cmd)?;
// An opacity alone places no gradient, so `span` may only be "object" with it.
let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?;
+12 -1
View File
@@ -395,7 +395,7 @@ fn compass(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<Can
return None;
}
let mut turn = space.view.rotation;
let rect = RotateView::compass_rect(ui, space.view.rect);
let rect = RotateView::compass_rect(ui, clear_of_scroll_bars(app, ui, space.view.rect));
RotateView::new(tl!("Rotate View"), Bind::bound(&mut turn), false).show_at(ui, rect);
(turn != space.view.rotation).then(|| {
let mut view = space.view;
@@ -404,6 +404,17 @@ fn compass(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<Can
})
}
/// `rect` without the strip the vertical scroll bar takes along its right edge (the bar's thickness and its margin,
/// the sizes `CanvasScrollbars` draws with), in the screen modes that show the scroll bars.
fn clear_of_scroll_bars(app: &VectorcraftApp, ui: &Ui, rect: egui::Rect) -> egui::Rect {
if app.ui.screen_mode >= 2 {
return rect;
}
let env = Env::of(ui);
let strip = env.tokens.size.icon.md + env.tokens.space.gap.tight;
egui::Rect::from_min_max(rect.min, egui::pos2((rect.right() - strip).max(rect.left()), rect.bottom()))
}
/// The scroll bars along the right and bottom edges (Normal and Full Screen with Menu Bar): the view
/// a thumb drag or page press moved.
fn scroll_bars(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<CanvasView> {
+9 -1
View File
@@ -987,7 +987,15 @@ fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, view: &CanvasV
let old = CanvasView::new(old_rect, Point::new(k.cx, k.cy), k.zoom).rotation(rotation);
let a = view.to_screen(old.to_doc(old_rect.min));
let b = view.to_screen(old.to_doc(old_rect.max));
let placed = snapped_rect(a, b - a, painter.pixels_per_point());
// A frame shown for the view, size and pixel density it was rendered for lands on
// whole device pixels so its strokes stay sharp. A cached frame shown while the
// canvas is panned, zoomed, resized or moved to another display keeps its exact
// document mapping until the replacement arrives.
let device_ppp = painter.pixels_per_point();
let current = (k.ppp - device_ppp).abs() < 1e-4
&& (k.cx, k.cy, k.zoom) == (view.center.x, view.center.y, view.zoom)
&& (old_rect.size() - rect.size()).abs().max_elem() < 1.0;
let placed = if current { snapped_rect(a, b - a, device_ppp) } else { egui::Rect::from_min_max(a, b) };
painter.image(tex.id(), placed, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
// The view turned after the last frame was rendered, and the worker renders the frame at
+11 -8
View File
@@ -6,7 +6,7 @@ use std::cell::RefCell;
use craft::behavior::IconId;
use craft::menu::MenuBarUi;
use craft::ui::buttons::{Button, IconButton, ToggleButton};
use craft::ui::contract::{Bind, BodyCx, Props, Show, ShowContainer};
use craft::ui::contract::{Bind, BodyCx, Gap, Props, Show, ShowContainer};
use craft::ui::display::Picture;
use craft::ui::layout_components::Row;
use craft::ui::primitives::IconSpec;
@@ -114,17 +114,20 @@ fn leading(ui: &mut Ui, app: &mut VectorcraftApp) {
}
/// The end of the bar: each ranked control in a row of its own, which the fitted title bar gives up whole, lowest rank
/// first, before the menus narrow.
/// first, before the menus narrow. The controls are `space.gap.item` apart, the gap between neighboring controls in a
/// bar.
fn trailing(ui: &mut Ui, app: &mut VectorcraftApp) {
let safe = vectorcraft_plugins::safe_mode::active();
for t in Trailing::SHOWN.into_iter().filter(|t| safe || *t != Trailing::Safe) {
match t.rank() {
Some(rank) => {
Row::new().fit_rank(rank).show(ui, |ui, _| t.show(app, ui));
Row::new().gap(Gap::Item).show(ui, |ui, _| {
for t in Trailing::SHOWN.into_iter().filter(|t| safe || *t != Trailing::Safe) {
match t.rank() {
Some(rank) => {
Row::new().fit_rank(rank).show(ui, |ui, _| t.show(app, ui));
}
None => t.show(app, ui),
}
None => t.show(app, ui),
}
}
});
}
/// The application bar, the body of the shell's title bar: brand mark, Home and menus, then Discord,
+18 -2
View File
@@ -120,8 +120,15 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| {
if let Some(i) =
Select::new(tl!("Artboard"), Bind::given(cur), &boards).look(SelectLook::Filled).enabled(nab > 0).show(ui).events.committed().copied()
// With no document the navigator shows a dash, as the info readout does.
if let Some(i) = Select::new(tl!("Artboard"), Bind::given(cur), &boards)
.placeholder("\u{2013}")
.look(SelectLook::Filled)
.enabled(nab > 0)
.show(ui)
.events
.committed()
.copied()
{
go = Some(json!(i));
}
@@ -264,6 +271,15 @@ mod tests {
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
}
#[test]
fn with_no_document_the_artboard_navigator_shows_a_dash() {
let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let mut panel = Panel::new(app, status_bar);
panel.room(egui::vec2(1200.0, 300.0));
panel.frame();
assert_eq!(panel.value_role("Artboard", Role::COMBO_BOX).as_deref(), Some("\u{2013}"), "the empty navigator reads as a dash");
}
}
/// What the bar shows as work in progress: the running script, then background jobs, opens and places. The first
+22
View File
@@ -473,6 +473,28 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() {
assert!(widest.zip(narrowest).is_some_and(|(w, n)| n >= w - 0.5), "the search keeps its width until it goes: {search_widths:?}");
}
/// The app bar's right-hand controls stand at least `space.gap.item` apart, the gap between neighboring controls in a
/// bar, so a hovered control's highlight does not touch the one beside it.
#[test]
fn the_app_bar_keeps_its_right_hand_controls_an_item_gap_apart() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let app = crate::VectorcraftApp::new(Session::new(), Default::default());
let gap = Rc::new(std::cell::Cell::new(0.0_f32));
let read = Rc::clone(&gap);
let mut bar = Shown::new(app, egui::vec2(1600.0, 600.0), move |app, ui| {
read.set(craft::ui::runtime::env::Env::of(ui).tokens.space.gap.item);
app.ui(ui);
});
bar.frame(Vec::new()).frame(Vec::new());
assert!(gap.get() > 0.0, "the item gap is read from the theme");
let controls = ["Discord", "Search commands", "Choose a workspace"];
let rects: Vec<egui::Rect> = controls.iter().map(|c| bar.starting(c).unwrap_or_else(|| panic!("{c} shows")).rect).collect();
for pair in rects.windows(2) {
let between = pair[1].left() - pair[0].right();
assert!(between >= gap.get() - 0.5, "neighboring controls {pair:?} are {between} apart, under the item gap {}", gap.get());
}
}
/// A text the status bar painted, with where it lies.
#[derive(Debug)]
struct StatusText {
+5 -2
View File
@@ -87,8 +87,11 @@ fn dialog<'a>(relative: bool, lengths: LengthUnits) -> ParamDialog<'a> {
Param::number("radius", tl!("Radius:"), 0.0, 1.0, 3).length(lengths).bounds(Some(0.0), None)
};
let radii = vec![("relative".to_owned(), tl!("Relative").into()), ("absolute".to_owned(), tl!("Absolute").into())];
let params =
vec![Param::new("kind", tl!("Corner:"), ParamKind::radio(kinds, None)), Param::new("radii", "", ParamKind::radio(radii, None)), radius];
let params = vec![
Param::new("kind", tl!("Corner:"), ParamKind::radio(kinds, None)),
Param::new("radii", "", ParamKind::radio(radii, None)).options_in_row(),
radius,
];
ParamDialog::new(KIND, tl!("Corners"), params)
}
+11 -7
View File
@@ -58,7 +58,7 @@ fn sized_row(key: &str, label: Label, default: f64, relative: bool, lengths: Len
/// the flag's JSON values, which `form::json_of` writes back as a bool.
pub(super) fn relative_radio(label: impl Into<Label>, default: bool) -> Param {
let options = vec![("true".to_owned(), lbl!("Relative")), ("false".to_owned(), lbl!("Absolute"))];
Param::new("relative", label, ParamKind::radio(options, Some(default.to_string())))
Param::new("relative", label, ParamKind::radio(options, Some(default.to_string()))).options_in_row()
}
/// Whether the pair's rows are shares of the object's size.
@@ -71,14 +71,16 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec<Param> {
let lengths = cx.lengths;
vec![
Param::custom("transform", lbl!("Transform"), move |ui, fields, _| transform_each::rows(ui, fields, lengths, ScaleLink::None))
.companions(["scaleH", "scaleV", "moveH", "moveV", "rotate"]),
.companions(["scaleH", "scaleV", "moveH", "moveV", "rotate"])
.full_width(),
Param::section(lbl!("Options")),
Param::new("objects", lbl!("Transform Objects"), ParamKind::bool(true)),
Param::new("patterns", lbl!("Transform Patterns"), ParamKind::bool(false)),
Param::new("strokes", lbl!("Scale Strokes & Effects"), ParamKind::bool(false)),
Param::new("copies", lbl!("Copies:"), ParamKind::int(Some(0), Some(1000), 0)),
Param::custom("__reflect", lbl!("Reflect"), |ui, fields, _| transform_each::reflect_checks(ui, fields))
.companions(["reflectX", "reflectY", "random"]),
Param::new("reflectX", lbl!("Reflect X"), ParamKind::bool(false)),
Param::new("reflectY", lbl!("Reflect Y"), ParamKind::bool(false)),
Param::new("random", lbl!("Random"), ParamKind::bool(false)),
Param::custom("__reference", lbl!("Reference Point"), |ui, fields, _| transform_each::reference_point(ui, fields)).companions(["reference"]),
]
}
@@ -102,7 +104,8 @@ pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
"points",
Label::from(crate::i18n::tr_ctx(crate::i18n::current(), "effect", "Points").to_string()),
ParamKind::radio(points, None),
),
)
.options_in_row(),
]
}
@@ -185,12 +188,13 @@ pub(super) fn drop_shadow(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
.map(|p| if matches!(p.key.as_str(), "opacity" | "x" | "y" | "blur") { p.step_arrows(StepArrows::Leading) } else { p });
rows.chain([
Param::new("shade", Label::Empty, ParamKind::radio(shades, None)),
Param::new("color", lbl!("Color"), ParamKind::color(None)).enabled_when("shade", "color"),
Param::new("color", lbl!("Color"), ParamKind::color(None)).enabled_when("shade", "color").under_option("color"),
Param::number("darkness", lbl!("Darkness"), 100.0, 1.0, 0)
.bounds(Some(0.0), Some(100.0))
.unit(UnitKind::Percent)
.step_arrows(StepArrows::Leading)
.enabled_when("shade", "darkness"),
.enabled_when("shade", "darkness")
.under_option("darkness"),
])
.collect()
}
+4 -1
View File
@@ -706,7 +706,10 @@ fn sections(lists: &Lists) -> Vec<PrintSection> {
flag("collate", tl!("Collate")).enabled_when_in("copies", counts),
flag("reverse", tl!("Reverse Order")),
Param::new("artboards", tl!("Artboards"), ParamKind::radio(artboards, None)),
Param::new("range", tl!("Range:"), ParamKind::text("")).hint("1-3, 5").enabled_when("artboards", PrintArtboards::Range.id()),
Param::new("range", tl!("Range:"), ParamKind::text(""))
.hint("1-3, 5")
.enabled_when("artboards", PrintArtboards::Range.id())
.under_option(PrintArtboards::Range.id()),
flag("skipBlank", tl!("Skip Blank Artboards")).enabled_when_in("artboards", [PrintArtboards::All.id(), PrintArtboards::Range.id()]),
Param::section(tl!("Media")),
pick::<Media>("media", tl!("Size:")),
+4 -2
View File
@@ -254,8 +254,10 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> {
return Err(why);
}
let (cmd, p, _) = s.request(&answer.fields);
// OK must validate afresh: the live preview also caches refused requests.
s.preview = LivePreview::default();
// OK must validate afresh: the live preview also caches refused requests. The running preview is ended first;
// a fresh preview refuses to start while another interaction is open, which left OK refused and the old
// preview's interaction open.
s.cancel_preview(app);
match s.run_preview(app, cmd, &p) {
Some(Ok(())) if finish_unchanged_preview(app) => return Ok(()),
Some(Err(why)) => {
+10 -1
View File
@@ -445,6 +445,15 @@ pub(crate) fn reference_point(ui: &mut Ui, fields: &mut DialogFields) -> Respons
shown.response
}
/// The reference point picker with its name beside it, for a full-width row that draws no label of its own.
fn labelled_reference_point(ui: &mut Ui, fields: &mut DialogFields) -> Response {
let shown = Row::new().show(ui, |ui, _| {
reference_point(ui, fields);
Text::new(tl!("Reference Point")).show(ui);
});
shown.output
}
/// The dialog's rows: Scale, Move and Rotate in one row, then the options.
fn dialog_params(lengths: LengthUnits) -> Vec<Param> {
vec![
@@ -464,7 +473,7 @@ fn dialog_params(lengths: LengthUnits) -> Vec<Param> {
Ok(())
})
.full_width(),
Param::custom("reference", tl!("Reference Point"), |ui, f, _| reference_point(ui, f))
Param::custom("reference", tl!("Reference Point"), |ui, f, _| labelled_reference_point(ui, f))
.on_set(|f, key, value| {
let at = value.as_i64().filter(|at| (0..=8).contains(at)).ok_or_else(|| FieldRefusal::Rejects(&value).message(key))?;
f.set(key, at);
@@ -5,10 +5,10 @@ use craft::behavior::IconId;
use craft::keymap::CommandRef;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, clicked};
use craft::ui::contract::{Bind, Gap, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, clicked};
use craft::ui::display::{Elide, Shade, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Row;
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::menu::Menu;
use craft::ui::popover::Popover;
use craft::ui::style::TypeRole;
@@ -194,27 +194,40 @@ pub(crate) fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) {
let caption = |ui: &mut Ui, text: &'static str| {
Text::new(text).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
};
caption(ui, tl!("Match"));
if let Some(on) = option_check(ui, tl!("Appearance"), o.appearance) {
set(app, json!({ "appearance": on }));
let results = global_edit_results(global_edit_count(app));
// Each group is its caption over its options a row gap apart; the groups and the Results line are a stack gap
// apart. A click is kept and run after the stack returns.
let mut changes = Vec::new();
Stack::new().gap(Gap::Stack).show(ui, |ui, _| {
FieldGroup::new(tl!("Match")).show(ui, |ui, _| {
caption(ui, tl!("Match"));
if let Some(on) = option_check(ui, tl!("Appearance"), o.appearance) {
changes.push(json!({ "appearance": on }));
}
if let Some(on) = option_check(ui, tl!("Size"), o.size) {
changes.push(json!({ "size": on }));
}
});
FieldGroup::new(tl!("On Artboards")).show(ui, |ui, _| {
caption(ui, tl!("On Artboards"));
if let Some(all) = option_check(ui, tl!("All Artboards"), o.artboards.is_none()) {
changes.push(json!({ "artboards": if all { "all" } else { "1" } }));
}
if let Some(range) = &o.artboards {
let typed = Field::new(tl!("Range:")).show(ui, |ui, _| TextField::new(tl!("Range:"), Bind::given(range.clone())).show(ui)).inner;
if let Some(range) = typed.and_then(|t| t.events.committed().cloned()) {
changes.push(json!({ "artboards": range }));
}
}
if let Some(on) = option_check(ui, tl!("Include Objects On Canvas"), o.include_canvas) {
changes.push(json!({ "includeCanvas": on }));
}
});
Text::new(results.clone()).shade(Shade::Muted).show(ui);
});
for p in changes {
set(app, p);
}
if let Some(on) = option_check(ui, tl!("Size"), o.size) {
set(app, json!({ "size": on }));
}
caption(ui, tl!("On Artboards"));
if let Some(all) = option_check(ui, tl!("All Artboards"), o.artboards.is_none()) {
set(app, json!({ "artboards": if all { "all" } else { "1" } }));
}
if let Some(range) = &o.artboards {
let typed = Field::new(tl!("Range:")).show(ui, |ui, _| TextField::new(tl!("Range:"), Bind::given(range.clone())).show(ui)).inner;
if let Some(range) = typed.and_then(|t| t.events.committed().cloned()) {
set(app, json!({ "artboards": range }));
}
}
if let Some(on) = option_check(ui, tl!("Include Objects On Canvas"), o.include_canvas) {
set(app, json!({ "includeCanvas": on }));
}
Text::new(global_edit_results(global_edit_count(app))).shade(Shade::Muted).show(ui);
}
/// The options' line with how many objects Start Global Edit would take, in the interface language.
@@ -181,6 +181,34 @@ fn global_edit_starting_closes_the_quick_action_options() {
assert!(!panel.app().ui.properties_panel.global_edit_open && !panel.shows(&results), "the options stay closed once Global Edit stops");
}
/// The Global Edit Options are two groups, Match and On Artboards, and the Results line: the On Artboards caption is a
/// stack gap below the Size option, and the Results line a stack gap below Include Objects On Canvas.
#[test]
fn global_edit_options_groups_are_a_stack_gap_apart() {
use craft::ui::contract::Role;
crate::i18n::set_current(crate::i18n::Lang::EN);
let stack = std::rc::Rc::new(std::cell::Cell::new(0.0));
let seen = std::rc::Rc::clone(&stack);
craft::ui::testing::Fixture::new(move |ui| seen.set(craft::ui::runtime::env::Env::of(ui).tokens.space.gap.stack)).frame(vec![]);
let stack = stack.get();
assert!(stack > 0.0, "the interface resolved its stack gap");
let mut app = new_app();
let a = rect(&mut app, 20.0, 20.0, 40.0, 40.0);
rect(&mut app, 200.0, 20.0, 40.0, 40.0);
app.run("select.set", json!({"ids": [a]})).unwrap();
let mut panel = Panel::new(app, super::appearance_section::global_edit_row);
panel.click("Global Edit Options");
let results = global_edit_results(2);
assert!(panel.shows(&results), "the options open");
let size = panel.rect_role("Size", Role::CHECK_BOX);
let caption = panel.rect_role("On Artboards", Role::LABEL);
let canvas = panel.rect_role("Include Objects On Canvas", Role::CHECK_BOX);
let line = panel.rect(&results);
let (above, below) = (caption.top() - size.bottom(), line.top() - canvas.bottom());
assert!(above >= stack - 0.5, "On Artboards is {above} below Size, under the stack gap {stack}");
assert!(below >= stack - 0.5, "Results is {below} below the last option, under the stack gap {stack}");
}
/// The options' Results count is found once per document revision, options and selected
/// object, not every frame; another selected object or other options find it again.
#[test]
+1
View File
@@ -5,6 +5,7 @@ pub(super) mod background;
mod clipboard;
mod contextmenu;
mod cut;
mod dialog_layout;
mod distortkeys;
mod document_drag;
mod drag_commands;
+138
View File
@@ -0,0 +1,138 @@
//! Where the parameter dialogs draw their rows: option rows stand beside or under the choice they belong to, and
//! every check box and picker shows its name.
use egui::{Pos2, Rect};
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
type Window = egui_kittest::Harness<'static, VectorcraftApp>;
/// A document with one selected rectangle, in a window that runs whole app frames.
fn window() -> Window {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 90})).unwrap();
app.run("select.all", json!({})).unwrap();
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if !std::mem::replace(&mut fonts, true) {
crate::testing::install(ui.ctx());
return;
}
app.tick(ui.ctx());
app.ui(ui);
},
app,
);
let root = h.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default();
root.inner_rect = Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 900.0)));
root.focused = Some(true);
for _ in 0..2 {
step(&mut h);
}
h
}
/// One frame as the hosts run the window's; the commands it fired run as the next frame begins.
fn step(h: &mut Window) {
let ctx = h.ctx.clone();
let app = h.state_mut();
app.adopt_context(&ctx);
craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out));
h.step();
crate::testing::run_fired(h.state_mut(), &ctx);
}
/// The texts the window paints with `command` run, each with where it was drawn, a field label's colon left off.
fn texts(command: &str, params: Value) -> Vec<(String, Rect)> {
fn collect(s: &egui::Shape, out: &mut Vec<(String, Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().trim().trim_end_matches(':').to_owned(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
_ => {}
}
}
let mut h = window();
crate::menus::invoke(h.state_mut(), command, params);
for _ in 0..6 {
step(&mut h);
}
let mut out = vec![];
h.output().shapes.iter().for_each(|c| collect(&c.shape, &mut out));
out
}
/// Where each painted `label` was drawn, top to bottom.
fn all(texts: &[(String, Rect)], label: &str) -> Vec<Rect> {
let mut found: Vec<Rect> = texts.iter().filter(|(t, _)| t == label).map(|(_, r)| *r).collect();
found.sort_by(|a, b| a.top().total_cmp(&b.top()));
found
}
/// The one painted `label`.
fn one(texts: &[(String, Rect)], label: &str) -> Rect {
let found = all(texts, label);
assert_eq!(found.len(), 1, "`{label}` drawn {} times in {:?}", found.len(), texts.iter().map(|t| &t.0).collect::<Vec<_>>());
found[0]
}
/// `b` stands on `a`'s line, to its right.
fn beside(a: Rect, b: Rect) -> bool {
(a.center().y - b.center().y).abs() < a.height() / 2.0 && b.left() > a.right()
}
/// The Transform effect names its Reflect X, Reflect Y and Random check boxes.
#[test]
fn the_transform_effect_names_its_reflect_options() {
let shown = texts("effect.dialog", json!({"effect": "distort.transform"}));
for label in ["Reflect X", "Reflect Y", "Random"] {
one(&shown, label);
}
}
/// Transform Each names its reference point picker.
#[test]
fn transform_each_names_its_reference_point() {
let shown = texts("object.transformEach", json!({}));
one(&shown, "Reference Point");
}
/// Roughen's Relative and Absolute stand on one line, and so do Smooth and Corner.
#[test]
fn roughen_puts_each_choice_on_one_line() {
let shown = texts("effect.dialog", json!({"effect": "distort.roughen"}));
assert!(beside(one(&shown, "Relative"), one(&shown, "Absolute")), "Relative, then Absolute on its line");
// The Properties panel also shows a Corner row; the dialog's Corner is the one on Smooth's line.
let smooth = one(&shown, "Smooth");
assert!(all(&shown, "Corner").into_iter().any(|corner| beside(smooth, corner)), "Smooth, then Corner on its line");
}
/// The Corners dialog's Relative and Absolute stand on one line.
#[test]
fn corners_puts_relative_and_absolute_on_one_line() {
let shown = texts("ui.corners", json!({}));
assert!(beside(one(&shown, "Relative"), one(&shown, "Absolute")), "Relative, then Absolute on its line");
}
/// Drop Shadow's color row stands under the Color choice, before Darkness, and the Darkness row under Darkness.
#[test]
fn drop_shadow_rows_stand_under_their_choice() {
let shown = texts("effect.dialog", json!({"effect": "stylize.dropShadow"}));
let mut order: Vec<(f32, &str)> = ["Color", "Darkness"].iter().flat_map(|l| all(&shown, l).into_iter().map(move |r| (r.top(), *l))).collect();
order.sort_by(|a, b| a.0.total_cmp(&b.0));
let labels: Vec<&str> = order.iter().map(|(_, l)| *l).collect();
assert_eq!(labels, ["Color", "Color", "Darkness", "Darkness"], "each choice, then its row");
}
/// Print's Range field stands under the Range choice, before Ignore Artboards.
#[test]
fn print_range_stands_under_its_choice() {
let shown = texts("file.print", json!({}));
let ignore = one(&shown, "Ignore Artboards (all the art as one page)");
let ranges = all(&shown, "Range");
assert_eq!(ranges.len(), 2, "the choice and the field");
assert!(ranges.iter().all(|r| r.bottom() <= ignore.top()), "the Range field before Ignore Artboards");
}
+20
View File
@@ -318,6 +318,26 @@ fn rotate_view_to_selection_squares_the_view_to_the_selected_object() {
assert!(square_on_screen(&app));
}
/// The Rotate View compass of a turned view sits clear of the vertical scroll bar, so the bar does not cover it.
#[test]
fn the_rotate_view_compass_is_clear_of_the_vertical_scroll_bar() {
let mut w = Window::new();
w.ctx.enable_accesskit();
w.after(0.0, vec![]);
let out = w.after(0.0, vec![]);
let nodes = out.platform_output.accesskit_update.as_ref().map_or(&[][..], |u| &u.nodes[..]);
let bounds = |label: &str| {
nodes
.iter()
.find(|(_, n)| n.label() == Some(label))
.and_then(|(_, n)| n.bounds())
.map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))
.unwrap_or_else(|| panic!("no {label} in the access tree"))
};
let (compass, bar) = (bounds("Rotation compass"), bounds("Vertical scroll bar"));
assert!(compass.right() <= bar.left(), "the compass {compass:?} reaches under the scroll bar {bar:?}");
}
/// The window, with a 400 × 300 document whose view is turned to 30°, and the Selection tool. Each
/// frame comes the given number of seconds, zero or more, after the one before it.
struct Window {
+3 -2
View File
@@ -35,11 +35,12 @@ OUTPUT="$DIST/vectorcraft-$VERSION-macos-aarch64-nightly.zip"
nightly_compile_gui
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/VectorCraft"
chmod 755 "$APP/Contents/MacOS/VectorCraft"
cp "$ROOT/assets/app-icon/vectorcraft-nightly.icns" "$APP/Contents/Resources/vectorcraft-nightly.icns"
nightly_copy_notices "$APP/Contents/Resources"
# Launcher admits notices under Resources/docs, not beside the icon.
nightly_copy_notices "$APP/Contents/Resources/docs"
# The private mktemp cwd is the helper authority root: stage the template inside it.
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
+82 -2
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
real signature, notarization or Mac run."""
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
import base64
import importlib.util
import json
@@ -27,6 +27,8 @@ COMMIT = "b" * 40
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
ASSET = f"vectorcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "VectorCraft Nightly.app"
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
# Every fixture credential carries the same value, so no line here reads like a real one.
@@ -185,6 +187,50 @@ class Fixture:
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
return self.input
def package(self, font_licences):
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
source = HERE.parents[1]
checkout = self.root / "source"
checkout.mkdir()
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
"assets/app-icon/vectorcraft-nightly.icns"):
target = checkout / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / relative, target)
env = self.env(**dict.fromkeys(SECRETS))
def git(*args):
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
git("init", "-q")
git("add", "--", ".")
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture")
commit = git("rev-parse", "HEAD").strip()
version = VERSION[:-12] + commit[:12]
# Generated licence text exercises the copier without depending on a font checkout.
fonts = self.root / "craft-fonts"
for family, data in font_licences.items():
licence = fonts / "fonts" / family / "OFL.txt"
licence.parent.mkdir(parents=True)
licence.write_bytes(data)
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
(self.bin / "cargo").write_text(
'#!/bin/sh\nset -eu\n'
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/vectorcraft"\n'
'mkdir -p "$(dirname "$gui")"\n'
"printf \"#!/bin/sh\\necho 'VectorCraft %s (nightly-v1)'\\n\" \"$VECTORCRAFT_VERSION\" >\"$gui\"\n",
)
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
VECTORCRAFT_BUILD_CHANNEL="nightly-v1", VECTORCRAFT_VERSION=version,
VECTORCRAFT_BUILD_SHA=commit, VECTORCRAFT_BUILD_DATE="2026-11-23")
assert result.returncode == 0, result.stdout
return self.dist / ASSET.replace(VERSION, version)
def env(self, **changes):
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
@@ -433,6 +479,40 @@ class Verify(unittest.TestCase):
class Build(unittest.TestCase):
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
f = Fixture(self)
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
archive = f.package(fonts)
source = HERE.parents[1]
resources = f"{APP}/Contents/Resources"
icon = "vectorcraft-nightly.icns"
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
contents = f"{APP}/Contents"
gui = f"{contents}/MacOS/VectorCraft"
with zipfile.ZipFile(archive) as zipped:
entries = zipped.infolist()
names = {entry.filename for entry in entries}
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
for path, data in expected_files.items():
with self.subTest(path=path):
self.assertEqual(zipped.read(path), data)
mode = zipped.getinfo(path).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode))
self.assertFalse(mode & 0o111)
mode = zipped.getinfo(gui).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
self.assertEqual(result.returncode, 0, result.stdout)
def test_compilation_refuses_signing_material_before_building(self):
f = Fixture(self)
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
+92 -2
View File
@@ -28,6 +28,12 @@ APP_NAME = "vectorcraft"
PRODUCER_WORKFLOW_NAME = "VectorCraft unsigned nightly"
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# The pinned shared registry enables Windows, Linux and macOS for VectorCraft.
SIGNER_SECRETS = {
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
}
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
"windows-x86_64": ("publisher_subject",
@@ -65,6 +71,49 @@ def assert_nightly_serialization(source):
raise ValueError("nightly serialization must use its stable group and no cancellation")
def caller_entries(lines, indent):
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
entries = {}
children = None
for line in lines:
if children is not None and line.startswith(" " * (indent + 1)):
children.append(line)
continue
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
if row is None or row[1] in entries:
raise ValueError("malformed or duplicate caller mapping entry")
children = []
entries[row[1]] = row[2], children
return entries
def assert_caller_secrets(source, job_name, names):
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
root = caller_entries(lines, 0)
job_marker, job_lines = root.pop("jobs", (None, []))
jobs = caller_entries(job_lines, 2)
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
raise ValueError("the caller must have one plain job block")
job = caller_entries(jobs[job_name][1], 4)
if "environment" in job or "environment" in root or "secrets" in root:
raise ValueError("only the native callee may bind the environment")
if names:
if "secrets" not in job:
raise ValueError("signer requires an explicit target-specific secret map")
mode, secret_lines = job.pop("secrets")
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
if mode is not None or caller_entries(secret_lines, 6) != expected:
raise ValueError("signer must forward exactly the reviewed same-name secret references")
elif "secrets" in job:
raise ValueError("unsigned caller must not pass secrets")
for value, children in (*root.values(), *job.values()):
outside_map = "\n".join([value or "", *children])
# Scan all remaining text: quoted braces can appear before a secret reference.
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
raise ValueError("secret bindings belong only in the signer map")
def literal_off(condition):
expression = " ".join(condition.split())
if expression.startswith("${{") and expression.endswith("}}"):
@@ -231,8 +280,49 @@ class TrustedSourcePreparation(unittest.TestCase):
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
header = " secrets:\n"
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
self.assertIn(linux, signer)
mutations = {
"missing name": signer.replace(linux, ""),
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
"duplicate name": signer.replace(linux, linux + linux),
"duplicate map": signer + header + linux,
"quoted duplicate map": signer + ' "secrets": inherit\n',
"inherit": signer.split(header)[0] + " secrets: inherit\n",
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
"yaml merge": signer + " <<: *other\n",
"environment": signer + " environment: release\n",
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
}
for change, source in mutations.items():
with self.subTest(change=change), self.assertRaises(ValueError):
assert_caller_secrets(source, "release", SIGNER_SECRETS)
def test_unsigned_caller_has_no_secrets(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
assert_caller_secrets(producer, "unsigned", set())
for suffix in (" secrets: {}\n", " secrets: inherit\n",
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
assert_caller_secrets(producer + suffix, "unsigned", set())
def test_unsigned_caller_refuses_secret_after_format_brace(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
# This inert fixture is never dispatched; the brace is part of the format string.
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
assert_caller_secrets(source, "unsigned", set())
class NightlyTrustAnchors(unittest.TestCase):