Merge remote-tracking branch 'upstream/main' into HEAD

This commit is contained in:
vangel76 committed 2026-11-13 00:34:30 +01:00
commit 64fc07d421
11 files changed
+245 -42

No files matched your search

+2 -5
View File
@@ -627,17 +627,14 @@ mod native {
/// True for a symlink, or on Windows any reparse point, whose target could be swapped.
/// Expects `symlink_metadata`, which describes the link itself rather than its target.
fn is_redirect(metadata: &Metadata) -> bool {
if metadata.file_type().is_symlink() {
return true;
}
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT
metadata.file_type().is_symlink() || metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT
}
#[cfg(not(windows))]
{
false
metadata.file_type().is_symlink()
}
}
+2 -2
View File
@@ -167,8 +167,8 @@ impl BandChol {
let n = a.diag.len();
let mut p = 0;
for i in 0..n {
for k in a.rows[i]..a.rows[i + 1] {
p = p.max(i.abs_diff(a.cols[k]));
for &j in &a.cols[a.rows[i]..a.rows[i + 1]] {
p = p.max(i.abs_diff(j));
}
}
if n.saturating_mul(p + 1) > 40_000_000 {
+2 -2
View File
@@ -119,7 +119,7 @@ impl CmykModel {
(v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0)
});
let mut s = [0.0; 3];
for m in 0..16 {
for (m, prim) in self.prim_n.iter().enumerate() {
let mut w = 1.0;
for (i, ai) in a.iter().enumerate() {
w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai };
@@ -127,7 +127,7 @@ impl CmykModel {
if w == 0.0 {
continue;
}
for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) {
for (acc, p) in s.iter_mut().zip(prim) {
*acc += w * p;
}
}
@@ -110,8 +110,8 @@ fn flattens_layers_and_keeps_alpha_channels() {
assert_eq!(d.channels.len(), 4);
assert!(d.channels[3].spot.is_none(), "the saved selection stays an alpha channel");
// The black fill on the upper layer is solid ink in all three plates.
for k in 0..3 {
assert!(d.channels[k].surface.pixel(1, 1)[0] > 0.99);
for c in &d.channels[..3] {
assert!(c.surface.pixel(1, 1)[0] > 0.99);
}
// Back to RGB: the alpha channel survives, the inks become colour channels.
s.execute("image.mode.rgb", json!({})).unwrap();
+24 -2
View File
@@ -6,6 +6,7 @@ use super::{
Affine, Color, Document, EngineError, Fill, FillRule, Layer, LayerContent, LayerId, LiveShape, Path, PathOp, Point, Result, SHAPE_BLOCKS, Session,
ShapeLayer, Value, bad, json, sel, vector,
};
use std::borrow::Cow;
fn active_shape(s: &Session) -> std::result::Result<&ShapeLayer, String> {
let d = s.active().ok_or("no document open")?;
@@ -70,7 +71,22 @@ pub(super) fn paste_shape_stroke(s: &mut Session, p: &Value) -> Result<Value> {
/// The path `shape.create` draws for live-shape params `p` (the Shape tools preview it while dragging).
pub fn shape_path(p: &Value) -> Result<Path> {
let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect");
Ok(vector::shapes::live_path(&live_from_params("shape.create", kind, p, None)?))
let (kind, p) = triangle_as_polygon(kind, p);
Ok(vector::shapes::live_path(&live_from_params("shape.create", kind, &p, None)?))
}
/// `kind: "triangle"` (the Triangle tool, Create Triangle) is a 3-sided polygon: the live-shape
/// kind and params to build it from. Its own kind only names the new layer (Triangle N).
fn triangle_as_polygon<'a>(kind: &'a str, p: &'a Value) -> (&'a str, Cow<'a, Value>) {
if kind != "triangle" {
return (kind, Cow::Borrowed(p));
}
let mut q = p.clone();
if let Some(o) = q.as_object_mut() {
o.insert("sides".into(), json!(3));
o.remove("starRatio");
}
("polygon", Cow::Owned(q))
}
fn live_kind(l: &LiveShape) -> &'static str {
@@ -426,6 +442,7 @@ fn default_name(kind: &str) -> &'static str {
"roundedRect" | "roundRect" => "Rounded Rectangle",
"ellipse" => "Ellipse",
"polygon" => "Polygon",
"triangle" => "Triangle",
"star" => "Star",
"line" => "Line",
_ => "Shape",
@@ -443,7 +460,8 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
let v = p.get("path").ok_or_else(|| bad(CMD, "kind \"path\" needs `path`"))?;
(parse_path(v).map_err(|e| bad(CMD, e))?, None)
} else {
let l = live_from_params(CMD, kind, p, None)?;
let (live_kind, q) = triangle_as_polygon(kind, p);
let l = live_from_params(CMD, live_kind, &q, None)?;
(vector::shapes::live_path(&l), Some(l))
};
let (fill, stroke) = new_fill_stroke(s, CMD, p)?;
@@ -786,6 +804,10 @@ pub(super) fn selection_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
shape_create(s, &q)
}
#[cfg(test)]
#[path = "triangle_layer_name_tests.rs"]
mod triangle_layer_name_tests;
#[cfg(test)]
mod arrow_affine_regression_tests {
use super::*;
@@ -0,0 +1,70 @@
//! The Triangle tool and Create Triangle name their shape layers Triangle N, not Polygon N (#13353).
use serde_json::{Value, json};
use super::super::{LayerContent, LayerId, LiveShape, shape_path};
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 200, "height": 160, "background": "white"})).unwrap();
s
}
/// The params the Triangle tool's drag and Create Triangle's OK send.
fn triangle(rect: [f64; 4]) -> Value {
json!({"kind": "triangle", "rect": rect})
}
fn name(info: &Value) -> &str {
info["name"].as_str().unwrap()
}
#[test]
fn triangles_are_named_triangle_n() {
let mut s = session();
let first = s.execute("shape.create", triangle([20.0, 20.0, 60.0, 40.0])).unwrap();
let second = s.execute("shape.create", triangle([90.0, 30.0, 50.0, 50.0])).unwrap();
assert_eq!((name(&first), name(&second)), ("Triangle 1", "Triangle 2"));
}
#[test]
fn a_triangle_is_a_live_three_sided_polygon() {
let mut s = session();
// Any `sides` or `starRatio` sent along is ignored: a triangle has 3 sides and no star.
let p = json!({"kind": "triangle", "rect": [20, 20, 60, 40], "sides": 7, "starRatio": 0.3, "cornerRadius": 4});
let id = s.execute("shape.create", p.clone()).unwrap()["layer"].as_u64().unwrap();
let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content else { panic!("not a shape layer") };
assert_eq!(sh.live, Some(LiveShape::Polygon { rect: [20.0, 20.0, 60.0, 40.0], sides: 3, star_ratio: 1.0, corner_radius: 4.0 }));
// The drag's preview and Path mode draw the same outline.
let polygon = json!({"kind": "polygon", "rect": [20, 20, 60, 40], "sides": 3, "cornerRadius": 4});
assert_eq!(shape_path(&p).unwrap(), shape_path(&polygon).unwrap());
assert_eq!(sh.path, shape_path(&polygon).unwrap());
}
#[test]
fn polygons_and_triangles_count_on_their_own() {
let mut s = session();
let tri = s.execute("shape.create", triangle([20.0, 20.0, 60.0, 40.0])).unwrap();
let poly = s.execute("shape.create", json!({"kind": "polygon", "rect": [90, 30, 50, 50], "sides": 5})).unwrap();
let three = s.execute("shape.create", json!({"kind": "polygon", "rect": [90, 90, 50, 50], "sides": 3})).unwrap();
assert_eq!((name(&tri), name(&poly), name(&three)), ("Triangle 1", "Polygon 1", "Polygon 2"));
}
#[test]
fn an_explicit_name_wins() {
let mut s = session();
let info = s.execute("shape.create", json!({"kind": "triangle", "rect": [20, 20, 60, 40], "name": "Roof"})).unwrap();
assert_eq!(name(&info), "Roof");
}
#[test]
fn a_triangle_without_a_rect_is_refused() {
let mut s = session();
let history = s.active().unwrap().history.past_len();
for p in [json!({"kind": "triangle"}), json!({"kind": "triangle", "rect": "x"})] {
assert!(s.execute("shape.create", p.clone()).is_err(), "{p}");
}
assert!(shape_path(&json!({"kind": "triangle"})).is_err());
assert_eq!(s.active().unwrap().history.past_len(), history);
}
+1 -4
View File
@@ -107,14 +107,11 @@ pub fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> {
/// Use fallback only when the exclusive rename primitive itself is unsupported.
fn unsupported_rename(error: &io::Error) -> bool {
if error.kind() == io::ErrorKind::Unsupported {
return true;
}
#[cfg(unix)]
if matches!(error.raw_os_error(), Some(code) if code == rustix::io::Errno::INVAL.raw_os_error() || code == rustix::io::Errno::NOSYS.raw_os_error()) {
return true;
}
false
error.kind() == io::ErrorKind::Unsupported
}
/// Linking claims an absent destination atomically; a later unlink failure is already published.
+138 -16
View File
@@ -127,12 +127,12 @@ pub(super) mod linux {
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Mount {
root: String,
mount_point: String,
fstype: String,
options: String,
super_options: String,
pub(super) struct Mount {
pub(super) root: String,
pub(super) mount_point: String,
pub(super) fstype: String,
pub(super) options: String,
pub(super) super_options: String,
}
/// Measures available RAM and free swap from `/proc/meminfo`, capped by the process's memory
@@ -206,14 +206,14 @@ pub(super) mod linux {
MembershipParse::Malformed => return CgroupLimits::Unreadable,
};
let mountinfo = std::fs::read_to_string(proc_root.join("self/mountinfo")).ok();
// A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak)
// shows the process its membership path but no interface files, so no limit is
// observable. Failing closed there reported 0 bytes free and refused every PSD on a
// machine with tens of GB. A present directory still takes the guarded path below.
// Only a confirmed NotFound counts as absent: a stat that fails for another reason
// (permissions) leaves the directory possibly present, so that case stays fail-closed.
let sys_root_absent = matches!(std::fs::metadata(sys_root), Err(e) if e.kind() == std::io::ErrorKind::NotFound);
if sys_root_absent && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) {
// A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) or
// only an empty mount-point directory left by `sysfs` shows the process its membership path
// but no interface files, so no limit is observable. Failing closed there reported 0 bytes
// free and refused every PSD on a machine with tens of GB. Only a present non-empty or
// unreadable directory takes the guarded path below: a stat or read_dir that fails for
// another reason (permissions, non-directory) leaves a mounted hierarchy possibly present,
// so that case stays fail-closed.
if sys_root_absent_or_empty(sys_root) && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) {
return CgroupLimits::NotConstrained;
}
@@ -273,16 +273,34 @@ pub(super) mod linux {
MembershipParse::Parsed(membership)
}
/// Whether `/sys/fs/cgroup` is absent (`ErrorKind::NotFound`) or a readable empty directory.
///
/// Permission errors, non-directory paths, and unreadable directories return `false` and stay
/// fail-closed.
pub(super) fn sys_root_absent_or_empty(sys_root: &Path) -> bool {
match std::fs::metadata(sys_root) {
Err(e) => e.kind() == std::io::ErrorKind::NotFound,
Ok(meta) => meta.is_dir() && std::fs::read_dir(sys_root).is_ok_and(|mut entries| entries.next().is_none()),
}
}
/// Parses `/proc/self/mountinfo` into the mount fields used to locate a cgroup hierarchy.
///
/// Malformed lines are skipped; callers fail closed when no matching mount is found.
fn parse_mountinfo(text: &str) -> Vec<Mount> {
pub(super) fn parse_mountinfo(text: &str) -> Vec<Mount> {
let mut mounts = Vec::new();
for line in text.lines() {
let fields: Vec<&str> = line.split_whitespace().collect();
let Some(separator) = fields.iter().position(|f| *f == "-") else { continue };
let super_options = fields.get(separator + 3).copied().or_else(|| {
// `show_mountinfo` writes `<fstype> <source> <super_options>`; an empty source
// (e.g. a bubblewrap tmpfs mount) leaves two spaces between `fstype` and options.
let after = line.split_once(" - ")?.1.trim_start();
let fstype = fields.get(separator + 1).copied()?;
after.strip_prefix(fstype)?.starts_with(" ").then(|| fields.get(separator + 2).copied()).flatten()
});
let (Some(root), Some(point), Some(fstype), Some(super_options)) =
(fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), fields.get(separator + 3).copied())
(fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), super_options)
else {
continue;
};
@@ -966,6 +984,23 @@ mod tests {
assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained);
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
// Isolated case 1: a readable empty `/sys/fs/cgroup` mount-point directory with normal
// non-cgroup `mountinfo` also reports `NotConstrained`.
let (proc, sys) = fixture("empty-cgroup-mountpoint");
write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n");
write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n");
assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained);
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
// Isolated case 2: absent `/sys/fs/cgroup` with a bubblewrap empty-source non-cgroup mount
// (`- tmpfs rw,...`) parses cleanly and reports `NotConstrained`.
let (proc, _) = fixture("absent-cgroup-empty-source");
let sys = proc.parent().unwrap().join("absent-sys");
write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n");
write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev\n");
assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained);
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
// A truncated mount line may be the cgroup mount: with /sys/fs/cgroup absent, fail closed.
let (proc, _) = fixture("truncated-mountinfo-line");
let sys = proc.parent().unwrap().join("absent-sys");
@@ -1269,4 +1304,91 @@ mod tests {
assert_eq!(linux::available_at(&proc, &sys), Some((4 << 30) + (512 << 20)), "legacy helper keeps RAM + swap");
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
}
#[cfg(target_os = "linux")]
#[test]
fn linux_parse_mountinfo_handles_empty_mount_source() {
let tmpfs = "26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev,size=65536k\n";
let cg2 = "30 20 0:26 /user.slice /sys/fs/cg\\0402 rw,relatime - cgroup2 rw,nsdelegate\n";
let truncated = "31 20 0:27 / /sys/fs/cgroup rw - cgroup2 rw\n";
let mounts = linux::parse_mountinfo(&format!("{tmpfs}{cg2}{truncated}"));
assert_eq!(mounts.len(), 2, "single-space line missing super_options is skipped");
let m0 = &mounts[0];
assert_eq!((&m0.root[..], &m0.mount_point[..], &m0.fstype[..]), ("/", "/tmp", "tmpfs"));
assert_eq!((&m0.options[..], &m0.super_options[..]), ("rw,nosuid,nodev", "rw,nosuid,nodev,size=65536k"));
let m1 = &mounts[1];
assert_eq!((&m1.root[..], &m1.mount_point[..], &m1.fstype[..]), ("/user.slice", "/sys/fs/cg 2", "cgroup2"));
assert_eq!((&m1.options[..], &m1.super_options[..]), ("rw,relatime", "rw,nsdelegate"));
}
/// An empty `/sys/fs/cgroup` directory only reports `NotConstrained` when `mountinfo` parses
/// cleanly with no cgroup mount; cgroup mounts (including empty-source lines), missing/empty/
/// truncated `mountinfo`, non-empty directories, files, and unreadable directories fail closed.
#[cfg(target_os = "linux")]
#[test]
fn linux_empty_or_invalid_sys_root_fails_closed_unless_proven_unmounted() {
use std::os::unix::fs::PermissionsExt;
let bad_mountinfo: [(&str, Option<&str>); 6] = [
("empty-sys-missing-mountinfo", None),
("empty-sys-empty-mountinfo", Some("")),
("empty-sys-garbage-mountinfo", Some("not a mountinfo line\n")),
("empty-sys-truncated-mountinfo", Some("25 20 0:23 / /proc rw - proc proc rw\n30 20 0:26 / /sys/fs/cgroup rw - cgroup2\n")),
("empty-sys-cgroup2-mount", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n")),
("empty-sys-empty-source-cgroup2", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 rw\n")),
];
for (name, mountinfo) in bad_mountinfo {
let (proc, sys) = fixture(name);
write(&proc.join("self/cgroup"), "0::/app\n");
if let Some(text) = mountinfo {
write(&proc.join("self/mountinfo"), text);
}
assert!(linux::sys_root_absent_or_empty(&sys), "{name}");
assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "{name}");
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
}
// Empty `/sys/fs/cgroup` with a v1 memory mount in `mountinfo` also fails closed.
let (proc, sys) = fixture("empty-sys-cgroup-v1-mount");
write(&proc.join("self/cgroup"), "4:memory:/app\n");
write(&proc.join("self/mountinfo"), "31 24 0:26 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n");
assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable);
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
// A non-empty `/sys/fs/cgroup` directory is not treated as unmounted even with non-cgroup mountinfo.
let (proc, sys) = fixture("non-empty-sys-root");
write(&proc.join("self/cgroup"), "0::/app\n");
write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n");
write(&sys.join("memory.max"), "1073741824\n");
assert!(!linux::sys_root_absent_or_empty(&sys));
assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable);
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
// `sys_root` as a regular file and a `NotADirectory` path component return false and fail closed.
let (proc, _) = fixture("file-sys-root");
let file_sys = proc.parent().unwrap().join("sys-as-file");
write(&file_sys, "");
write(&proc.join("self/cgroup"), "0::/app\n");
write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n");
for path in [&file_sys, &file_sys.join("cgroup")] {
assert!(!linux::sys_root_absent_or_empty(path));
assert_eq!(linux::cgroup_limits(&proc, path), linux::CgroupLimits::Unreadable);
}
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
// An unreadable `/sys/fs/cgroup` directory (`read_dir` error) returns false and fails closed.
let (proc, sys) = fixture("unreadable-sys-root");
write(&proc.join("self/cgroup"), "0::/app\n");
write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n");
std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o000)).unwrap();
let read_blocked = std::fs::read_dir(&sys).is_err();
let absent = linux::sys_root_absent_or_empty(&sys);
let limits = linux::cgroup_limits(&proc, &sys);
std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o700)).unwrap();
std::fs::remove_dir_all(proc.parent().unwrap()).unwrap();
if read_blocked {
assert!(!absent);
assert_eq!(limits, linux::CgroupLimits::Unreadable);
}
}
}
+1 -1
View File
@@ -124,7 +124,7 @@ pub fn geometry(f: &Map<String, Value>) -> Result<Value, String> {
if radii.iter().any(|r| *r > 0.0) { json!({"kind": "roundedRect", "rect": rect, "radii": radii}) } else { json!({"kind": "rect", "rect": rect}) }
}
"ellipse" => json!({"kind": "ellipse", "rect": rect}),
"triangle" => json!({"kind": "polygon", "rect": rect, "sides": 3}),
"triangle" => json!({"kind": "triangle", "rect": rect}),
"polygon" => {
let sides = num(f, "sides").map_or(5.0, |s| s.round().clamp(3.0, 100.0));
let ratio = num(f, "starRatio").map_or(100.0, |r| r.clamp(1.0, 100.0));
+2 -7
View File
@@ -82,18 +82,13 @@ impl ThumbnailCache {
/// Check if two path strings match, tolerating slash direction and Windows case differences.
fn paths_match(a: &str, b: &str) -> bool {
if a == b {
return true;
}
#[cfg(windows)]
{
let a_norm = a.replace('\\', "/");
let b_norm = b.replace('\\', "/");
a_norm.eq_ignore_ascii_case(&b_norm)
a == b || a.replace('\\', "/").eq_ignore_ascii_case(&b.replace('\\', "/"))
}
#[cfg(not(windows))]
{
false
a == b
}
}
+1 -1
View File
@@ -129,7 +129,7 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end:
Tool::Rectangle if o.corner_radius > 0.0 => json!({"kind": "roundedRect", "rect": rect, "radii": vec![o.corner_radius; 4]}),
Tool::Rectangle | Tool::CustomShape => json!({"kind": "rect", "rect": rect}),
Tool::EllipseShape => json!({"kind": "ellipse", "rect": rect}),
Tool::Triangle => json!({"kind": "polygon", "rect": rect, "sides": 3}),
Tool::Triangle => json!({"kind": "triangle", "rect": rect}),
// PhotoCraft's star defaults; the Star Tool's own options are not measured yet (#11377).
Tool::Star => json!({"kind": "star", "rect": rect, "sides": 5, "starRatio": 0.5}),
_ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3)}),