Merge main into fix/ui-sweep-dock-panels-b

This commit is contained in:
dotCooCoo committed 2026-11-28 13:35:03 -08:00
commit c35288f4d1
45 files changed
+1299 -106

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": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_tooling_revision": "main",
"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@main
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: main
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.
+3 -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@main
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: main
app-name: vectorcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
@@ -32,3 +32,4 @@ jobs:
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+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();
+3 -1
View File
@@ -253,6 +253,8 @@ pub(crate) fn item_target(s: &Session, p: &Value, cmd: &str) -> Result<ItemTarge
/// [`item_target`] read from param `key` (e.g. `fromItem`).
pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<ItemTarget> {
let aligned = aligned(p, cmd)?;
// Read `target` whatever names the objects, so that a bad one is refused with `ids` or `id` too.
let contents = targets_contents(p)?;
match p.get(key) {
Some(Value::Null) => Ok(ItemTarget::Top),
Some(v) => v
@@ -260,7 +262,7 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re
.map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned })
.ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))),
// The active item is a row of the first selected object's own stack.
None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top),
None if p.get("ids").is_some() || p.get("id").is_some() || contents => Ok(ItemTarget::Top),
// A row of a graph design's art in a series stands for nothing: the commands leave that art out.
None if s.active().and_then(|st| st.selection.subjects().first().map(|id| super::graph::is_design_art(&st.doc, *id))) == Some(true) => {
Ok(ItemTarget::Top)
+4 -2
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: selected characters take
// the paint before `item_target` reads either.
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))?;
@@ -1470,8 +1474,6 @@ fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result<Option<(Nod
}
let part = super::brushsym::selected_part(s)?;
if part.is_some() {
// Read `target` first: `item_target` stops at a null `id` or `ids` before it reads `target`.
super::appearance::targets_contents(p)?;
item_target(s, p, cmd)?;
}
Ok(part)
+17
View File
@@ -513,6 +513,23 @@ fn a_bad_target_is_refused_with_an_id_or_selected_characters() {
}
}
/// The other commands that name their appearance item the same way refuse a bad `target` with an
/// `id` or `ids` too, and leave the document alone; a good one still edits the object.
#[test]
fn a_stroke_edit_refuses_a_bad_target_with_an_id() {
let mut s = session();
let r = rect(&mut s, 10.0);
select(&mut s, &[r]);
let doc = s.doc().unwrap().doc.clone();
for p in [json!({"weight": 9, "target": "content", "id": r.0}), json!({"weight": 9, "target": "content", "ids": [r.0]})] {
let e = s.execute("stroke.set", &p).unwrap_err();
assert!(e.to_string().contains("`target` must be"), "{p}: {e}");
assert_eq!(*s.doc().unwrap().doc, *doc, "{p}");
}
s.execute("stroke.set", &json!({"weight": 9, "target": "object", "id": r.0})).unwrap();
assert_ne!(*s.doc().unwrap().doc, *doc);
}
/// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows
/// it; the object's fill item and the other points stay as they were.
#[test]
+19 -3
View File
@@ -35,7 +35,7 @@ impl WantedFonts {
pub fn new(fonts: &[WantedFont]) -> Self {
let mut by_name: HashMap<String, Vec<usize>> = HashMap::new();
for (i, w) in fonts.iter().enumerate() {
let mut names = vec![w.family.to_ascii_lowercase(), norm(&w.family)];
let mut names = vec![w.family.to_ascii_lowercase(), norm(&w.family), joined(w)];
names.extend(w.installed.as_ref().map(|c| c.to_ascii_lowercase()));
names.sort();
names.dedup();
@@ -136,6 +136,22 @@ fn provides(w: &WantedFont, faces: &[FaceStyle]) -> bool {
}) {
return true;
}
// A legacy family with another style: that style of the family.
faces.iter().find(|f| f.keys.legacy.iter().any(|(family, _)| *family == key)).is_some_and(|f| styled(&f.family))
// A legacy family with another style: that style of the family, among every face of the
// legacy family (in a collection they can be of different families). Once installed, the
// legacy family resolves the name, and `FontDb::canonical` doesn't join it.
let mut legacy = faces.iter().filter(|f| f.keys.legacy.iter().any(|(family, _)| *family == key)).peekable();
if legacy.peek().is_some() {
return legacy.any(|f| styled(&f.family));
}
// A family and style split from a PostScript name by an importer that didn't have the font
// (`Gilroy-Black` → Gilroy, Black), as `FontDb::canonical` joins them again: a face whose
// PostScript name is that name, whatever family and style the file gives it. Of a cataloged
// face, `canonical` reads the PostScript name only, so a full name alone isn't enough.
let joined = joined(w);
!sk.is_empty() && faces.iter().any(|f| f.keys.postscript.contains(&joined))
}
/// The family and style of `w` as one normalized name (`Gilroy` and `Black` → `gilroyblack`).
fn joined(w: &WantedFont) -> String {
format!("{}{}", norm(&w.family), norm(&w.style))
}
+61
View File
@@ -1257,3 +1257,64 @@ fn a_name_asked_for_before_its_font_is_installed_finds_it_after_a_rescan() {
}
let _ = std::fs::remove_dir_all(dir);
}
/// A document names `Gilroy-Black` as the family Gilroy in the style Black. A file whose own family is
/// `Gilroy-Black`, with no style, is that face, once cataloged and in a search of a folder.
#[test]
fn a_search_finds_the_file_of_a_postscript_name_split_into_family_and_style() {
let data = named(&[(3, EN, 1, "Gilroy-Black"), (3, EN, 4, "Gilroy-Black"), (3, EN, 6, "Gilroy-Black")]);
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-split-ps", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Gilroy-Black.ttf");
std::fs::write(&file, &data).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let (face, matched) = db.resolve("Gilroy", "Black").unwrap();
assert_eq!(matched, FontMatch::Exact, "{face:?}");
let wanted = |style: &str| WantedFonts::new(&[WantedFont { family: "Gilroy".into(), style: style.into(), installed: None }]);
assert_eq!(wanted("Black").provided_by(&file), [0]);
assert!(wanted("Bold").provided_by(&file).is_empty(), "another style of the family is another file");
assert!(wanted("").provided_by(&file).is_empty(), "without a style, the family alone is not the PostScript name");
let _ = std::fs::remove_dir_all(dir);
// The search offers a file only when installing it resolves the name exactly: not when the
// joined name is only a full name, and not when a legacy family of the same name resolves it
// first, to another style.
let cases = [
("full-name", vec![(3, EN, 1, "Gilroy Black"), (3, EN, 4, "Gilroy Black"), (3, EN, 6, "GilroyBlk")]),
(
"legacy",
vec![(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Display"), (3, EN, 17, "Regular"), (3, EN, 6, "Gilroy-Black")],
),
];
for (name, records) in cases {
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-split-ps-{name}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join(format!("{name}.ttf"));
std::fs::write(&file, named(&records)).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let exact = db.resolve("Gilroy", "Black").is_some_and(|(_, matched)| matched == FontMatch::Exact);
assert!(!exact, "{name}: installing the file doesn't resolve Gilroy Black exactly");
assert!(wanted("Black").provided_by(&file).is_empty(), "{name}: so the search doesn't offer it");
let _ = std::fs::remove_dir_all(dir);
}
}
/// In a collection whose faces share a legacy family but not a typographic one, the search looks
/// for the style asked for in each face's family, in either order.
#[test]
fn a_search_finds_a_style_among_the_faces_of_a_shared_legacy_family() {
let regular = named(&[(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Text"), (3, EN, 17, "Regular")]);
let black =
named(&[(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Display"), (3, EN, 17, "Black"), (3, EN, 6, "Gilroy-Black")]);
for (order, faces) in [("regular-first", [regular.clone(), black.clone()]), ("black-first", [black.clone(), regular.clone()])] {
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-shared-legacy-{order}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("shared.ttc");
std::fs::write(&file, collection(&faces)).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let (face, matched) = db.resolve("Gilroy", "Black").unwrap();
assert_eq!(matched, FontMatch::Exact, "{order}: {face:?}");
let wanted = WantedFonts::new(&[WantedFont { family: "Gilroy".into(), style: "Black".into(), installed: None }]);
assert_eq!(wanted.provided_by(&file), [0], "{order}");
let _ = std::fs::remove_dir_all(dir);
}
}
+7 -3
View File
@@ -262,6 +262,9 @@ fn distance_overlays(cx: &ToolContext, to: DistanceTo) -> Vec<Overlay> {
/// it snaps to the original too.
pub(crate) struct MoveSnap {
bounds: Option<Rect>,
/// The selection's geometric bounds, which Smart Guides line up with the other art's geometric
/// bounds and space evenly between them, whether Use Preview Bounds is on or off (#6436).
edges: Option<Rect>,
targets: Option<Targets>,
points: Option<Targets>,
/// The targets and points for a copy, gathered with the others before the previews move the
@@ -300,6 +303,7 @@ impl MoveSnap {
let points = |exclude: &[NodeId]| if cx.snap_to_grid { None } else { Targets::snap_to_point(cx, exclude) };
Self {
bounds: selection_bounds(cx),
edges: guides.then(|| cx.doc.bounds_of(&cx.selection.objects, false)).flatten(),
targets: guides.then(|| for_move(cx, &cx.selection.objects)),
points: points(&cx.selection.objects),
copy_targets: guides.then(|| for_move(cx, &[])),
@@ -312,7 +316,7 @@ impl MoveSnap {
/// Snap to Grid and Snap to Pixel alone, for a move whose box is `bounds`: the grid lands an
/// edge of the box on a gridline, and pixels put its top-left on whole pixels.
pub(crate) fn grid_only(bounds: Option<Rect>) -> Self {
Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false }
Self { bounds, edges: None, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false }
}
/// The ruler guides stopped showing since the move began (View › Hide Guides, or Trim View,
@@ -353,7 +357,7 @@ impl MoveSnap {
// The grabbed anchor landed on a path or a crossing, which a ruler guide does not pull
// it off.
let mut on_path = false;
if let (Some(t), Some(b)) = (targets, self.bounds) {
if let (Some(t), Some(b)) = (targets, self.edges) {
// The point the selection was grabbed by, near another object's anchor or centre,
// lands on it, rather than the bounds lining up a little beside it (#955).
if t.has_point_near(start + d, cx.snap_tol()) {
@@ -434,7 +438,7 @@ impl MoveSnap {
d = q - start;
guides = ov;
}
if let (Some(t), Some(b)) = (targets, self.bounds) {
if let (Some(t), Some(b)) = (targets, self.edges) {
if t.has_point_near(start + d, cx.snap_tol()) {
let (q, ov) = t.snap_point_along(start + d, u, cx.snap_tol());
d = q - start;
+36
View File
@@ -1255,6 +1255,42 @@ fn an_alt_copy_snaps_to_the_original_left_behind() {
assert_eq!(dx(&t.pointer(&c, &ev(PointerKind::Drag, 253.0, 150.0))), 103.0);
}
/// With Use Preview Bounds on, Smart Guides line up the moved selection's geometric bounds with
/// the other art's, as they do with it off: an edge lands exactly on the other path's edge, and the
/// edge of a stroke does not pull it there (#6436).
#[test]
fn a_move_lines_up_geometric_edges_with_use_preview_bounds_on() {
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Node};
// An artboard whose edges and center are out of reach, and two rectangles stroked 20 pt.
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let mut add = |r: Rect| {
let id = d.alloc_id();
let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0);
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap();
id
};
let a = add(Rect::new(100.0, 100.0, 200.0, 200.0));
add(Rect::new(300.0, 100.0, 400.0, 200.0));
let s = Selection { objects: vec![a], ..Default::default() };
let p = paint();
for preview in [false, true] {
let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) };
let dragged = |to: f64| {
let mut t = SelectionTool::default();
t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0));
let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0));
let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") };
(v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap())
};
// The right edge, 1 pt short of the other rectangle's left edge (x = 300), lands on it.
assert_eq!(dragged(249.0), (100.0, 0.0), "preview {preview}");
// 9 pt short, it stays where it is dragged, though the edge of its stroke is 1 pt past there.
assert_eq!(dragged(241.0), (91.0, 0.0), "preview {preview}");
}
}
/// Smart Guides › Snap to Last Location: a move that comes within Snapping Tolerance of where it
/// began goes back there, labeled "last location", a Shift move too; farther out, with the option
/// or Smart Guides off, it stays where it is dragged, and an Alt copy snaps as it does with the
+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 {
@@ -404,7 +404,7 @@ impl BulletsDialog {
let entries = [Entry::new(0usize, tl!("Left")), Entry::new(1, tl!("Right"))];
let current = self.fields.get("listAlign").and_then(Value::as_str).and_then(|a| ALIGNS.iter().position(|x| *x == a));
let edit = Select::new(tl!("Alignment:"), Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui);
if let Some(&i) = edit.value()
if let Some(&i) = edit.events.committed()
&& let Some(a) = ALIGNS.get(i)
{
self.fields.insert("listAlign".into(), json!(a));
@@ -924,6 +924,48 @@ mod tests {
assert!(app.run("ui.bulletsAndNumbering", json!({})).is_err(), "no type selected");
}
/// Alignment: an entry highlighted with the arrow keys changes no field and leaves the type as it was, Escape
/// closes the list with the dialog open and nothing changed, and Enter applies the entry.
#[test]
fn a_highlighted_alignment_applies_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = app.run("text.create", json!({"x": 10, "y": 10, "text": "One\nTwo", "area": {"width": 200, "height": 100}})).unwrap()["id"]
.as_u64()
.unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
panel.app().run("ui.bulletsAndNumbering", json!({})).unwrap();
panel.frame();
panel.frame();
let state = |panel: &Panel| {
let app = panel.app();
(fields(&app)["listAlign"].clone(), first(&app, id))
};
let before = state(&panel);
assert_eq!(before.0, "left");
panel.click_role("Alignment:", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.frame();
assert_eq!(state(&panel), before, "a highlighted alignment changes no field and leaves the type as it was");
panel.key(Key::Escape, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "Escape closes the list, not the dialog");
assert_eq!(state(&panel), before, "Escape leaves the alignment as it was");
panel.click_role("Alignment:", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "Enter in the list keeps the dialog open");
assert_eq!(state(&panel).0, "right", "Enter applies the alignment");
}
/// Cancel puts back what the preview changed: the list, its alignment and the indents.
#[test]
fn cancel_puts_the_type_back_as_it_was() {
@@ -826,7 +826,7 @@ fn paint_row(key: &'static str, label: &'static str, swatches: Vec<(String, Valu
entries.push(Entry::new(selected.clone(), Label::from(shown)));
}
let out = Select::new(Label::from(label), Bind::given(selected), &entries).show(ui);
if let Some(id) = out.value().cloned() {
if let Some(id) = out.events.committed().cloned() {
let paint = match id.as_str() {
"" => Some(Value::Null),
"none" => Some(json!({"type": "none"})),
@@ -1007,6 +1007,46 @@ fn color_and_features_preview_cancel_commit_and_new_style() {
assert!(t.runs.iter().all(|r| r.style.style_name.as_deref() == Some("Body")));
}
/// Character Color's Fill and Stroke: a paint highlighted with the arrow keys changes no field and leaves the
/// document as it was, Escape closes the list with the dialog open and nothing changed, and Enter sets the paint.
#[test]
fn a_highlighted_character_color_paint_applies_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
for (name, key) in [("Fill", "fill"), ("Stroke", "stroke")] {
let mut app = app();
styled(&mut app, json!({"size": 24.0}), "Text");
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
open(&mut panel.app(), "Body");
set::<Existing>(&panel.app(), "tab", json!("color"));
panel.frame();
panel.frame();
let state = |panel: &Panel| {
let app = panel.app();
(fields::<Existing>(&app), app.session.doc().unwrap().doc.clone())
};
let before = state(&panel);
panel.click_role(name, Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.frame();
assert_eq!(state(&panel), before, "a highlighted {name} paint changes nothing");
panel.key(Key::Escape, Modifiers::NONE);
panel.frame();
assert!(is_open::<Existing>(&panel.app()), "Escape closes the {name} list, not the dialog");
assert_eq!(state(&panel), before, "Escape leaves {name} as it was");
panel.click_role(name, Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
panel.frame();
assert!(is_open::<Existing>(&panel.app()), "Enter in the {name} list keeps the dialog open");
assert_ne!(state(&panel).0[key], before.0[key], "Enter sets the {name} paint");
}
}
/// A size or leading below the minimum is refused by OK and runs no preview.
#[test]
fn size_and_leading_below_minimum_do_not_preview_or_commit() {
@@ -604,7 +604,7 @@ impl CompositeFontsDialog {
}
})
.cell_field(STYLE, style, move |out| {
if let Some(style) = out.value().cloned() {
if let Some(style) = out.events.committed().cloned() {
edits.borrow_mut().push((at, PartEdit::Style(style)));
}
});
@@ -612,6 +612,44 @@ fn custom_character_sets_draw_their_characters_and_the_buttons() {
}
}
/// The parts table's Style: a style highlighted with the arrow keys leaves the font's parts as they were, Escape closes
/// the list with nothing changed, and Enter sets the style.
#[test]
fn a_highlighted_part_style_applies_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let mut p = Panel::new(app(), crate::tests::picks::dialogs);
p.room(egui::vec2(1280.0, 1100.0));
open(&mut p.app()).unwrap();
new_font(&mut p.app());
dialog(&mut p.app(), |d| {
for class in CharClass::ALL {
d.edit_part(row(class), PartEdit::Font("Source Sans 3".into(), Some("Regular".into())));
}
});
p.frame();
p.frame();
let parts = |p: &Panel| dialog(&mut p.app(), |d| d.font().map(|f| f.parts.clone()));
let before = parts(&p);
p.click_role("Style", Role::COMBO_BOX);
p.key(Key::ArrowDown, Modifiers::NONE);
p.frame();
assert_eq!(parts(&p), before, "a highlighted style changes no part");
p.key(Key::Escape, Modifiers::NONE);
p.frame();
assert!(is_open(&p.app()), "Escape closes the list, not the dialog");
assert_eq!(parts(&p), before, "Escape leaves the parts as they were");
p.click_role("Style", Role::COMBO_BOX);
p.key(Key::ArrowDown, Modifiers::NONE);
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert!(is_open(&p.app()), "Enter in the list keeps the dialog open");
assert_ne!(parts(&p), before, "Enter sets the style");
}
#[test]
fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() {
let mut app = app();
+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:")),
@@ -158,6 +158,61 @@ fn map_art_maps_a_symbol_onto_a_surface_of_extrude_and_bevel_classic() {
assert!(params.get("__mapArt").is_none() && params.get("__mapSurface").is_none(), "the dialog's own state stays out of the effect");
}
/// Map Art's Symbol: a symbol highlighted with the arrow keys maps nothing and leaves the drawing as it was, Escape
/// closes the list with the dialog open and nothing changed, and Enter maps the symbol.
#[test]
fn a_highlighted_map_art_symbol_applies_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use craft::ui::dialog::StackDialog as _;
use super::super::three_d;
use crate::tests::panel_harness::Panel;
fn whole_frame(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
app.tick(ui.ctx());
app.ui(ui);
}
fn settle(panel: &mut Panel) {
for _ in 0..6 {
panel.frame();
}
}
let mut panel = Panel::new(with_symbol("M50 50L150 50L150 150L50 150Z"), whole_frame);
panel.room(vec2(1440.0, 900.0));
settle(&mut panel);
if let Err(e) = effect::open(&mut panel.app(), &json!({"effect": CLASSIC_EXTRUDE, "item": null})) {
panic!("the dialog did not open: {e}");
}
settle(&mut panel);
let ctx = panel.ctx().clone();
let page = three_d::with_fields(&mut panel.app(), |d| d.set_json_field(&ctx, "__page", json!("mapArt")));
assert!(matches!(page, Some(Ok(()))), "{page:?}");
settle(&mut panel);
let state = |panel: &Panel| {
let mut app = panel.app();
let maps = three_d::with_fields(&mut app, |d| d.json_fields()).flatten().and_then(|v| v.get("mapArt").cloned()).unwrap_or(Value::Null);
(maps, app.session.doc().unwrap().doc.clone())
};
let before = state(&panel);
assert!(vectorcraft_effects::surface_maps(&json!({"mapArt": before.0})).is_empty(), "no surface has a map yet");
panel.click_role("Symbol", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
settle(&mut panel);
assert_eq!(state(&panel), before, "a highlighted symbol maps nothing");
panel.key(Key::Escape, Modifiers::NONE);
settle(&mut panel);
assert!(panel.app().three_d_dialog.is_some(), "Escape closes the list, not the dialog");
assert_eq!(state(&panel), before, "Escape leaves the maps as they were");
panel.click_role("Symbol", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
settle(&mut panel);
assert!(panel.app().three_d_dialog.is_some(), "Enter in the list keeps the dialog open");
let maps = vectorcraft_effects::surface_maps(&json!({"mapArt": state(&panel).0}));
assert_eq!(maps.iter().map(|m| (m.surface, m.symbol.as_str())).collect::<Vec<_>>(), [(1, "Mark")], "Enter maps the symbol");
}
/// The theme's plot size, as a pass of the app's interface resolves it.
fn plot_size() -> egui::Vec2 {
let mut plot = None;
+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)) => {
@@ -485,7 +485,7 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) -
// A custom row, so a pick and automation both write the map through `set_map_value`.
let symbol = Param::custom(MAP_SYMBOL, tl!("Symbol"), move |ui, fields, _| {
let picked = Select::new(tl!("Symbol"), Bind::given(shown.clone()), &entries).id_salt(MAP_SYMBOL).show(ui);
if let Some(name) = picked.value().cloned() {
if let Some(name) = picked.events.committed().cloned() {
// The select lists only what the map takes: a refusal cannot come from it.
let _ = set_map_value(fields, MAP_SYMBOL, json!(name));
}
+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);
+44 -2
View File
@@ -529,7 +529,7 @@ impl StackDialog for FindFontDialog {
crate::panels::section(tl!("Replace With Font").to_string()).show(ui, |ui, _| {
Field::new(tl!("Replace With Font From").to_string()).show(ui, |ui, _| {
let edit = Select::new(tl!("Replace With Font From").to_string(), Bind::given(source), &source_entries).show(ui);
new_source = edit.events.value().copied();
new_source = edit.events.committed().copied();
});
let edit = TextField::search(tl!("Search").to_string(), Bind::given(self.search.clone())).show(ui);
new_search = edit.events.value().cloned();
@@ -544,7 +544,7 @@ impl StackDialog for FindFontDialog {
});
Field::new(tl!("Find In").to_string()).show(ui, |ui, _| {
let edit = Select::new(tl!("Find In").to_string(), Bind::given(find_in), &find_in_entries).show(ui);
new_find_in = edit.events.value().copied();
new_find_in = edit.events.committed().copied();
});
});
});
@@ -1013,6 +1013,48 @@ mod tests {
// PLAN: files-w11 owns Missing Fonts' hosted type; its test asserts the search there
}
/// Replace With Font From and Find In: an entry highlighted with the arrow keys changes no choice, Escape closes
/// the list with the dialog open and nothing changed, and Enter applies the entry.
#[test]
fn a_highlighted_source_or_find_in_applies_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
// Replace With Font From opens on System, its last entry, and Find In on Document, its first.
for (name, step) in [("Replace With Font From", Key::ArrowUp), ("Find In", Key::ArrowDown)] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Inter"})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
open(&mut panel.app());
panel.frame();
panel.frame();
let state = |panel: &Panel| {
let d = opened(&panel.app());
(d.replace_from, d.find_in)
};
let before = state(&panel);
assert_eq!(before, ("system".to_string(), "document".to_string()));
panel.click_role(name, Role::COMBO_BOX);
panel.key(step, Modifiers::NONE);
panel.frame();
assert_eq!(state(&panel), before, "a highlighted {name} entry changes no choice");
panel.key(Key::Escape, Modifiers::NONE);
panel.frame();
assert!(panel.app().dialogs().unwrap().with(|host| host.is_open::<FindFontDialog>()), "Escape closes the {name} list, not the dialog");
assert_eq!(state(&panel), before, "Escape leaves {name} as it was");
panel.click_role(name, Role::COMBO_BOX);
panel.key(step, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
panel.frame();
assert!(panel.app().dialogs().unwrap().with(|host| host.is_open::<FindFontDialog>()), "Enter in the {name} list keeps the dialog open");
assert_ne!(state(&panel), before, "Enter applies the {name} entry");
}
}
/// `f`'s answer, read while the font menu held still: tests running alongside add fonts to
/// the shared database and lend it composite fonts.
fn while_fonts_hold<T>(mut f: impl FnMut() -> T) -> T {
-5
View File
@@ -9200,11 +9200,6 @@ file-filter Applications Aplikasi
@msg the layer effects of {n} layers weren't drawn efek lapisan dari {n} lapisan tidak digambar
@msg the vector masks of 1 layer weren't applied masker vektor dari 1 lapisan tidak diterapkan
@msg the vector masks of {n} layers weren't applied masker vektor dari {n} lapisan tidak diterapkan
@msg `opacity` must be a number from 0 to 100 `opacity` harus berupa angka dari 0 sampai 100
@msg `opacity` must be true or false `opacity` harus true atau false
@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke karakter teks tidak memiliki opasitas sendiri: tambahkan isian atau guratan dengan Tambahkan isian baru atau Tambahkan guratan baru di panel Tampilan
@msg an object selected in a symbol instance has no fill or stroke opacity of its own objek yang dipilih dalam instans simbol tidak memiliki opasitas isian atau guratan sendiri
@msg no target has that fill or stroke to take the opacity tidak ada target yang memiliki isian atau guratan itu untuk menerima opasitas
@msg give color, none, swatch, gradient or opacity berikan color, none, swatch, gradient, atau opacity
@msg the knockout of 1 layer wasn't applied knockout dari 1 lapisan tidak diterapkan
@msg the knockout of {n} layers wasn't applied knockout dari {n} lapisan tidak diterapkan
Can't render this file because it is too large.
+36 -1
View File
@@ -25,6 +25,8 @@ pub struct PropertiesUi {
/// The cache of `appearance_section::edited_strokes_profiled`, keyed by (document uid, revision,
/// active Appearance row).
pub edited_profiled: Option<(ProfiledKey, bool)>,
/// The Quick Actions last listed, with the [`quick_actions_key`] they were listed at.
quick_actions: Option<(u64, Vec<QuickAction>)>,
}
/// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row).
@@ -34,6 +36,7 @@ type ProfiledKey = (u64, u64, Option<usize>);
const HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(1.0); 2];
/// One Quick Actions button: its label and the command it runs.
#[derive(Clone, Debug)]
pub(crate) struct QuickAction {
/// The button's label.
pub label: &'static str,
@@ -169,12 +172,42 @@ fn quick_action_buttons(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
}
for action in quick_actions(app) {
for action in shown_quick_actions(app) {
Button::command(action.command).label(action.label).show(ui);
}
});
}
/// What the Quick Actions are listed from: the menus' state ([`crate::menus::model::state_key`]), which
/// moves with every command run, the document and its revision, the tool and isolation mode.
fn quick_actions_key(app: &VectorcraftApp) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
crate::menus::model::state_key(app, None).hash(&mut h);
app.session.tool_id().hash(&mut h);
app.session.active().map(|st| (st.uid, st.revision, st.isolation)).hash(&mut h);
h.finish()
}
#[cfg(test)]
thread_local! {
/// How many times this thread has listed the Quick Actions.
pub(crate) static QUICK_ACTION_LISTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// [`quick_actions`], listed again only when [`quick_actions_key`] changed.
fn shown_quick_actions(app: &mut VectorcraftApp) -> Vec<QuickAction> {
let key = quick_actions_key(app);
if let Some((kept, actions)) = &app.ui.properties_panel.quick_actions
&& *kept == key
{
return actions.clone();
}
let actions = quick_actions(app);
app.ui.properties_panel.quick_actions = Some((key, actions.clone()));
actions
}
/// The ellipsis button that shows the panel `panel` for the section's further options.
fn more_options(ui: &mut Ui, panel: &str, tip: &'static str) {
IconButton::command(IconId::new("ellipsis"), CommandRef::with_params("window.panel", json!({ "panel": panel }))).label(tip).show(ui);
@@ -183,6 +216,8 @@ fn more_options(ui: &mut Ui, panel: &str, tip: &'static str) {
/// The Quick Actions the selection offers, in order. Lock and Isolate Group are left out while their commands are
/// off (in isolation mode, while an opacity mask is edited).
pub(crate) fn quick_actions(app: &mut VectorcraftApp) -> Vec<QuickAction> {
#[cfg(test)]
QUICK_ACTION_LISTS.with(|n| n.set(n.get() + 1));
let n_sel = super::selection_len(app);
let first = first_selected(app);
let kind = first.as_deref().map(|n| &n.kind);
@@ -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]
@@ -1056,6 +1084,37 @@ fn quick_actions_follow_the_selection() {
}
}
/// The panel lists the Quick Actions once per change of what they depend on, not in every frame.
#[test]
fn quick_actions_are_listed_again_only_after_a_change() {
let mut app = new_app();
rect(&mut app, 10.0, 10.0, 40.0, 40.0);
rect(&mut app, 80.0, 10.0, 40.0, 40.0);
let ctx = crate::testing::ui_context();
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 0.05;
crate::testing::app_frame(app, &ctx, egui::RawInput { time: Some(time), screen_rect, ..Default::default() });
};
for _ in 0..3 {
frame(&mut app);
}
let lists = || QUICK_ACTION_LISTS.with(|n| n.get());
let shown = |app: &VectorcraftApp| app.ui.properties_panel.quick_actions.as_ref().map(|(_, a)| a.iter().map(|a| a.command).collect::<Vec<_>>());
assert!(shown(&app).is_some_and(|a| !a.contains(&"object.group")), "one object selected: no Group");
let before = lists();
frame(&mut app);
frame(&mut app);
assert_eq!(lists() - before, 0, "frames with nothing changed list no Quick Actions");
app.run("select.all", json!({})).unwrap();
let before = lists();
frame(&mut app);
frame(&mut app);
assert_eq!(lists() - before, 1, "a new selection lists them once");
assert!(shown(&app).is_some_and(|a| a.contains(&"object.group")), "two objects selected: Group");
}
/// A brushed stroke with a variable width: the Width Profile list lists only Uniform, which removes
/// the profile.
#[test]
@@ -120,17 +120,32 @@ fn show_hex_field_is_a_setting_of_the_panel() {
}
/// An explicit null for any `ui.colorWheel` key keeps that key's value, as leaving the key out does,
/// and the other keys of the same call still apply.
/// and the other keys of the same call still apply. `contrastBackground` is the exception: null
/// unpins the background.
#[test]
fn ui_color_wheel_keeps_a_key_given_as_null() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let set = json!({
"view": "box", "channel": "red", "opacity": true, "hexField": true, "sliders": "oklch",
"gamut": true, "harmony": true, "harmonyRule": "triad", "vision": true, "documentColors": true
"gamut": true, "harmony": true, "harmonyRule": "triad", "contrast": true, "contrastFor": "largeText",
"contrastBackground": null, "vision": true, "documentColors": true
});
let all = app.run("ui.colorWheel", set.clone()).unwrap();
assert_eq!(all, set);
for key in ["view", "channel", "opacity", "hexField", "sliders", "gamut", "harmony", "harmonyRule", "vision", "documentColors"] {
for key in [
"view",
"channel",
"opacity",
"hexField",
"sliders",
"gamut",
"harmony",
"harmonyRule",
"contrast",
"contrastFor",
"vision",
"documentColors",
] {
assert_eq!(app.run("ui.colorWheel", json!({ key: null })).unwrap(), all, "{key}: null");
}
let got = app.run("ui.colorWheel", json!({"view": null, "channel": "blue", "opacity": null, "hexField": false})).unwrap();
@@ -138,7 +153,8 @@ fn ui_color_wheel_keeps_a_key_given_as_null() {
got,
json!({
"view": "box", "channel": "blue", "opacity": true, "hexField": false, "sliders": "oklch",
"gamut": true, "harmony": true, "harmonyRule": "triad", "vision": true, "documentColors": true
"gamut": true, "harmony": true, "harmonyRule": "triad", "contrast": true, "contrastFor": "largeText",
"contrastBackground": null, "vision": true, "documentColors": true
})
);
}
+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 -1
View File
@@ -876,10 +876,12 @@ fn controls_are_drawn_at_the_size_the_script_gave_them() {
.unwrap_or_else(|| panic!("no {role:?} {label:?}"))
};
let w = app.session.script_window().unwrap();
// The field is the text input named for screen readers; the editor inside its padding is a text
// input too, and the update lists the two in no fixed order.
let (wide, ok, field) = (
bounds(egui::accesskit::Role::Button, Some("Wide")),
bounds(egui::accesskit::Role::Button, Some("OK")),
bounds(egui::accesskit::Role::TextInput, None),
bounds(egui::accesskit::Role::TextInput, Some("Text")),
);
assert!(wide.width() > ok.width() && wide.height() > ok.height(), "the wide button is larger than OK: {wide:?} {ok:?}");
assert!((wide.width() - f64::from(w.nodes[1].rect.w)).abs() < 1.0, "the wide button is as wide as its preferred size: {wide:?}");
+59 -13
View File
@@ -184,7 +184,15 @@ pub(crate) fn slots(app: &VectorcraftApp) -> Vec<(Option<&'static str>, Vec<&'st
/// The slot a group of tools is in the rail's last-used memory: the index of its first tool in the
/// catalog, which stays put while the user edits the toolbar.
pub(crate) fn slot_id(first: &str) -> SlotId {
vectorcraft_tools::catalog::all_tools().position(|t| t.id == first).and_then(|i| SlotId::try_from(i).ok()).unwrap_or(SlotId::MAX)
static IDS: std::sync::OnceLock<std::collections::HashMap<&'static str, SlotId>> = std::sync::OnceLock::new();
let ids = IDS.get_or_init(|| {
let mut ids = std::collections::HashMap::new();
for (i, tool) in vectorcraft_tools::catalog::all_tools().enumerate() {
ids.entry(tool.id).or_insert_with(|| SlotId::try_from(i).unwrap_or(SlotId::MAX));
}
ids
});
ids.get(first).copied().unwrap_or(SlotId::MAX)
}
/// A rail tool that selects `id`: the tool's command in the catalog, which gives the button its name, its icon and
@@ -196,6 +204,8 @@ pub(crate) fn rail_tool(id: &str) -> RailTool<String> {
/// The rail's slots for `slots`: a category's first slot carries its caption, and its last ends the
/// group.
pub(crate) fn rail_slots(slots: &[(Option<&'static str>, Vec<&'static str>)]) -> Vec<ToolSlot<String>> {
#[cfg(test)]
SLOT_BUILDS.with(|n| n.set(n.get() + slots.len()));
slots
.iter()
.enumerate()
@@ -344,19 +354,54 @@ pub(crate) fn rail_view(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at:
height
}
/// The tool groups a rail's slots are built from, with the language their captions are in.
#[derive(Clone, Debug, PartialEq, Eq)]
struct SlotSource {
/// A strip's slots hold one tool each.
strip: bool,
/// The UI language.
lang: crate::i18n::Lang,
/// Each slot's caption and tools.
groups: Vec<(Option<&'static str>, Vec<&'static str>)>,
}
impl SlotSource {
/// The rail's slots for these groups.
fn slots(&self) -> Vec<ToolSlot<String>> {
if !self.strip {
return rail_slots(&self.groups);
}
#[cfg(test)]
SLOT_BUILDS.with(|n| n.set(n.get() + self.groups.len()));
self.groups.iter().flat_map(|(_, tools)| tools).map(|tool| ToolSlot::new(slot_id(tool), vec![rail_tool(tool)])).collect()
}
}
#[cfg(test)]
thread_local! {
/// How many rail slots this thread has built.
pub(crate) static SLOT_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// What a rail reads across passes: its slots and the tools they showed last, each edited only when
/// it changed, so a pass where neither changed reads neither.
/// it changed, so a pass where neither changed reads neither. The slots are built again only when
/// the groups they come from change.
#[derive(Default)]
pub(crate) struct RailModel {
source: Option<SlotSource>,
slots: Tracked<Vec<ToolSlot<String>>>,
last_used: Tracked<LastUsed<String>>,
}
impl RailModel {
/// Brings the model up to `slots` and `last_used`.
fn refresh(&mut self, slots: Vec<ToolSlot<String>>, last_used: LastUsed<String>) {
if *self.slots != slots {
self.slots.edit(|kept| *kept = slots);
/// Brings the model up to `source` and `last_used`.
fn refresh(&mut self, source: SlotSource, last_used: LastUsed<String>) {
if self.source.as_ref() != Some(&source) {
let slots = source.slots();
if *self.slots != slots {
self.slots.edit(|kept| *kept = slots);
}
self.source = Some(source);
}
if *self.last_used != last_used {
self.last_used.edit(|kept| *kept = last_used);
@@ -366,21 +411,22 @@ impl RailModel {
/// [`rail_view`] over `model`, the rail's own.
fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, model: &mut RailModel) -> f32 {
let (slots, last_used) = match &owner {
Owner::Tools => (rail_slots(&slots(app)), app.ui.tools_last_used.clone()),
let lang = crate::i18n::current();
let (source, last_used) = match &owner {
Owner::Tools => (SlotSource { strip: false, lang, groups: slots(app) }, app.ui.tools_last_used.clone()),
Owner::Toolbar(id) => {
let Some(bar) = bar_of(&app.ui, *id) else { return 0.0 };
let groups: Vec<_> = groups_of(app, &owner).into_iter().map(|g| (None, g)).collect();
(rail_slots(&groups), bar.last_used.clone())
let groups = groups_of(app, &owner).into_iter().map(|g| (None, g)).collect();
(SlotSource { strip: false, lang, groups }, bar.last_used.clone())
}
// One slot per tool, so a strip has no flyouts. A group no longer in the toolbar draws
// nothing; `keep_strips` closes its panel.
Owner::Strip(parent, first) => {
let tools = strip_tools(app, parent, first);
(tools.iter().map(|tool| ToolSlot::new(slot_id(tool), vec![rail_tool(tool)])).collect(), Default::default())
let groups = vec![(None, strip_tools(app, parent, first))];
(SlotSource { strip: true, lang, groups }, Default::default())
}
};
model.refresh(slots, last_used);
model.refresh(source, last_used);
let current = app.session.tool_id().to_string();
// PLAN: the sheet's `Cards<'a> { app }` cannot be held beside the footer's `&mut app`; Cards copies the two prefs.
let cards = card::Cards::new(app);
+21
View File
@@ -473,3 +473,24 @@ fn a_tool_card_shows_what_the_tool_does_and_what_its_keys_do() {
app.run("prefs.set", json!({"key": "showToolTips", "value": false})).unwrap();
assert!(!card::Cards::new(&app).has(&"selection".to_string()), "tool tips off: no card");
}
#[test]
fn the_rail_builds_its_slots_only_when_its_tool_groups_change() {
let mut app = app_with(300, 300);
let ctx = reader();
settled(&mut app, &ctx, 0.0, 800.0);
let built = || SLOT_BUILDS.with(|n| n.get());
let before = built();
frame(&mut app, &ctx, 0.2, vec![], 800.0);
frame(&mut app, &ctx, 0.25, vec![], 800.0);
assert_eq!(built() - before, 0, "frames with the same tool groups build no slots");
let basic = rail_slots(&slots(&app)).len();
app.run("window.toolbarAdvanced", json!({"advanced": true})).unwrap();
let before = built();
frame(&mut app, &ctx, 0.3, vec![], 800.0);
let advanced = slots(&app).len();
assert_ne!(advanced, basic);
assert_eq!(built() - before, advanced, "the Advanced toolbar's slots are built once");
let kept = app.dock_rt.rail_models.get(&Owner::Tools.panel()).map(|model| model.slots.len());
assert_eq!(kept, Some(advanced), "the rail shows the Advanced toolbar's slots");
}
+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"):
+96 -6
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("}}"):
@@ -143,7 +192,7 @@ def reviewed_manual_actors(caller_source, policy):
def caller_pin(name):
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$",
return re.findall(r"(?m)^ tooling-revision: (\S+)$",
(ROOT / ".github/workflows" / name).read_text())[0]
@@ -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):
@@ -269,7 +359,7 @@ class NightlyTrustAnchors(unittest.TestCase):
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
pins.update(uses)
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main")
class NightlyEnabledCallers(unittest.TestCase):
@@ -687,7 +777,7 @@ def trust_closure_problems(workflows):
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
if name == "nightly-sign.yml":
signer_calls += 1
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
if name != "nightly-sign.yml" or ref != "main":
problems.append(name + " calls nightly-release.yml@" + ref)
if workflow.lower() in ("release.yml", "release.yaml"):
stable_callers.add(name)
@@ -737,7 +827,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
"a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
"a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")},
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
}