>()
+ };
+
+ assert!(pieces(r#"["M",0,0]"#).is_empty());
+ assert!(pieces(r#"["M",0,0],["Z"]"#).is_empty());
+ assert_eq!(pieces(r#"["M",0,0],["L",1,0],["M",5,5],["M",6,6],["L",7,7],["L",8,8]"#), [2, 3]);
+ assert_eq!(pieces(r#"["M",0,0],["L",1,0],["Z"],["L",9,9],["L",8,8]"#), [2, 2]);
+ }
+
+ /// Each curve starts where the one before ended, whatever it was.
+ #[test]
+ fn a_curve_starts_where_the_pen_was() {
+ for before in [r#"["M",10,0]"#, r#"["M",0,0],["L",10,0]"#, r#"["M",0,0],["Q",5,0,10,0]"#] {
+ let marks = marks_of(&format!(r#"{{"type":"Path","path":[{before},["Q",10,100,10,200]]}}"#));
+ let (points, ..) = line(&marks[0]);
+ let x = points[points.len() - 1].x;
+ let curve = &points[points.len() - usize::try_from(CURVE_STEPS).unwrap()..];
+ assert!(curve.iter().all(|at| (at.x - x).abs() < 1e-9), "{before}: {curve:?}");
+ }
+ }
+
+ /// The head of an arrow closes; a pen's line that closes is no head.
+ #[test]
+ fn a_closed_piece_is_filled_on_an_arrow_alone() {
+ let closed = marks_of(r#"{"type":"Path","path":[["M",0,0],["L",10,0],["L",5,5],["Z"]]}"#);
+
+ assert!(line(&closed[0]).1);
+ assert_eq!(line(&closed[0]).2, Fill::None);
+ }
}
diff --git a/crates/drawing/src/picture.rs b/crates/drawing/src/picture.rs
index 258bdb8ff..e65c5f835 100644
--- a/crates/drawing/src/picture.rs
+++ b/crates/drawing/src/picture.rs
@@ -64,24 +64,14 @@ pub fn pictures(drawing: &Drawing, palette: &Palette, fonts: &Fonts) -> Option Option> {
+pub fn export(drawing: &Drawing, palette: &Palette, fonts: &Fonts, format: Format) -> Option> {
match format {
Format::Png => png(drawing, palette, fonts, PICTURE),
Format::Svg => svg(drawing, palette, fonts).map(String::into_bytes),
}
}
-fn png(
- drawing: &Drawing,
- palette: &Palette,
- fonts: &Fonts,
- (side, most): (f64, f64),
-) -> Option> {
+fn png(drawing: &Drawing, palette: &Palette, fonts: &Fonts, (side, most): (f64, f64)) -> Option> {
let frame = frame(drawing)?;
let options = usvg::Options {
font_family: fonts.family.clone(),
@@ -95,15 +85,11 @@ fn png(
clippy::cast_sign_loss,
reason = "positive, and a picture's side at most"
)]
- let (width, height) = (
- (frame.width * scale).ceil() as u32,
- (frame.height * scale).ceil() as u32,
- );
+ let (width, height) = ((frame.width * scale).ceil() as u32, (frame.height * scale).ceil() as u32);
let mut pixmap = Pixmap::new(width, height)?;
let drawn = tree.size();
#[expect(clippy::cast_precision_loss, reason = "a picture's side")]
- let transform =
- Transform::from_scale(width as f32 / drawn.width(), height as f32 / drawn.height());
+ let transform = Transform::from_scale(width as f32 / drawn.width(), height as f32 / drawn.height());
resvg::render(&tree, transform, &mut pixmap.as_mut());
pixmap.encode_png().ok()
}
@@ -144,11 +130,8 @@ pub fn svg(drawing: &Drawing, palette: &Palette, fonts: &Fonts) -> Option return,
Kind::Group => {
@@ -163,12 +146,8 @@ fn write_object(out: &mut String, object: &Object, palette: &Palette, fonts: &Fo
Kind::Rect | Kind::Ellipse | Kind::Polygon | Kind::Path => {}
}
let shape = shape(object, drawn_at);
- let _ = write!(
- out,
- r#"<{shape} transform="{}" {}/>"#,
- transform(object, drawn_at),
- paint(object, palette)
- );
+ let _ =
+ write!(out, r#"<{shape} transform="{}" {}/>"#, transform(object, drawn_at), paint(object, palette));
}
/// The tag and geometry of a shape, around the plane's origin: what `left` and `top` place.
@@ -187,11 +166,7 @@ fn shape(object: &Object, (scale_x, scale_y): (f64, f64)) -> String {
number(radius * scale_y),
)
}
- Kind::Ellipse => format!(
- r#"ellipse rx="{}" ry="{}""#,
- number(width / 2.0),
- number(height / 2.0)
- ),
+ Kind::Ellipse => format!(r#"ellipse rx="{}" ry="{}""#, number(width / 2.0), number(height / 2.0)),
Kind::Polygon => {
let points = object.points();
let middle = points_box(&points).map(|bounds| bounds.centre());
@@ -206,10 +181,7 @@ fn shape(object: &Object, (scale_x, scale_y): (f64, f64)) -> String {
.collect();
format!(r#"polygon points="{}""#, points.join(" "))
}
- _ => format!(
- r#"path d="{}""#,
- path_data(&object.path(), (scale_x, scale_y))
- ),
+ _ => format!(r#"path d="{}""#, path_data(&object.path(), (scale_x, scale_y))),
}
}
@@ -274,12 +246,7 @@ fn paint(object: &Object, palette: &Palette) -> String {
fn write_text(out: &mut String, object: &Object, palette: &Palette, fonts: &Fonts) {
let font_size = object.font_size();
- let lines = wrap(
- object.text().unwrap_or_default(),
- object.width(),
- font_size,
- fonts,
- );
+ let lines = wrap(object.text().unwrap_or_default(), object.width(), font_size, fonts);
let step = line_step(font_size, object.line_height());
let left = -object.width() / 2.0;
let top = -object.height() / 2.0 + first_baseline(font_size);
@@ -293,13 +260,8 @@ fn write_text(out: &mut String, object: &Object, palette: &Palette, fonts: &Font
);
let mut baseline = top;
for line in lines {
- let _ = write!(
- out,
- r#"{}"#,
- number(left),
- number(baseline),
- escaped(&line)
- );
+ let _ =
+ write!(out, r#"{}"#, number(left), number(baseline), escaped(&line));
baseline += step;
}
out.push_str("");
diff --git a/crates/drawing/src/picture/tests.rs b/crates/drawing/src/picture/tests.rs
index a56ae5e19..7ec7f1533 100644
--- a/crates/drawing/src/picture/tests.rs
+++ b/crates/drawing/src/picture/tests.rs
@@ -3,20 +3,12 @@ use crate::text::tests::fonts;
fn palette() -> Palette {
let each = |prefix: &str| Hue::ALL.map(|hue| format!("{prefix}-{}", hue.name()));
- Palette {
- stroke: each("stroke"),
- fill: each("fill"),
- paper: "#101010".to_owned(),
- }
+ Palette { stroke: each("stroke"), fill: each("fill"), paper: "#101010".to_owned() }
}
fn colours() -> Palette {
let each = |colour: &str| [colour; 6].map(str::to_owned);
- Palette {
- stroke: each("#e5e7eb"),
- fill: each("rgba(96, 165, 250, 0.14)"),
- paper: "#101010".to_owned(),
- }
+ Palette { stroke: each("#e5e7eb"), fill: each("rgba(96, 165, 250, 0.14)"), paper: "#101010".to_owned() }
}
fn scene(objects: &str) -> Drawing {
@@ -59,13 +51,9 @@ fn nothing_drawn_has_no_picture() {
#[test]
fn the_frame_is_what_is_drawn_with_room_on_its_paper() {
- let svg =
- svg_of(r#"{"type":"Rect","left":100,"top":50,"width":100,"height":50,"strokeWidth":0}"#);
+ let svg = svg_of(r#"{"type":"Rect","left":100,"top":50,"width":100,"height":50,"strokeWidth":0}"#);
- assert!(
- svg.contains(r#"viewBox="26 1 148 98" width="148" height="98""#),
- "{svg}"
- );
+ assert!(svg.contains(r#"viewBox="26 1 148 98" width="148" height="98""#), "{svg}");
assert!(svg.contains(r##""##));
}
@@ -77,14 +65,16 @@ fn each_shape_is_drawn_round_its_centre_in_its_hues_colours() {
{"type":"Polygon","left":0,"top":0,"width":40,"height":20,"points":[{"x":20,"y":0},{"x":40,"y":10},{"x":20,"y":20},{"x":0,"y":10}]}"#,
);
- assert!(svg.contains(r#" Option {
let boxes: Vec<_> = self.objects.iter().map(Object::bounds).collect();
crate::geometry::scene_box(&boxes, 0.0)
}
+ /// `None` for a body that holds no scene, or one whose objects are not objects: what
+ /// opens as a new drawing.
pub fn read(content: &str) -> Option {
let Value::Object(mut body) = serde_json::from_str(content).ok()? else {
return None;
@@ -120,11 +116,7 @@ impl Drawing {
return None;
};
let objects = take_objects(&mut scene)?;
- Some(Self {
- body,
- scene,
- objects,
- })
+ Some(Self { body, scene, objects })
}
/// The body to store.
@@ -152,10 +144,7 @@ fn put_objects(fields: &mut Map, objects: &[Object]) {
if objects.is_empty() && !fields.contains_key(OBJECTS) {
return;
}
- let objects = objects
- .iter()
- .map(|object| Value::Object(object.fields()))
- .collect();
+ let objects = objects.iter().map(|object| Value::Object(object.fields())).collect();
fields.insert(OBJECTS.to_owned(), Value::Array(objects));
}
@@ -170,10 +159,7 @@ impl Object {
/// A new object of Fabric's `kind`, in `hue`, on nothing yet.
pub(crate) fn make(kind: &str, id: String, hue: Hue) -> Self {
- let mut object = Self {
- fields: Map::new(),
- children: Vec::new(),
- };
+ let mut object = Self { fields: Map::new(), children: Vec::new() };
object.put("type", kind);
object.put("version", FABRIC);
object.put("originX", "center");
@@ -299,10 +285,7 @@ impl Object {
/// ⚠️ Fabric 7 places an object by its centre: `left` and `top` are the box's middle.
pub fn centre(&self) -> Point {
- Point {
- x: self.number("left", 0.0),
- y: self.number("top", 0.0),
- }
+ Point { x: self.number("left", 0.0), y: self.number("top", 0.0) }
}
pub fn width(&self) -> f64 {
@@ -391,15 +374,9 @@ impl Object {
let stroke = self.stroke_width();
let (scale_x, scale_y) = (self.scale_x().abs(), self.scale_y().abs());
if self.stroke_uniform() {
- (
- self.width() * scale_x + stroke,
- self.height() * scale_y + stroke,
- )
+ (self.width() * scale_x + stroke, self.height() * scale_y + stroke)
} else {
- (
- (self.width() + stroke) * scale_x,
- (self.height() + stroke) * scale_y,
- )
+ ((self.width() + stroke) * scale_x, (self.height() + stroke) * scale_y)
}
}
@@ -410,17 +387,9 @@ impl Object {
let (sin, cos) = self.angle().to_radians().sin_cos();
let corners = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].map(|(x, y)| {
let (x, y) = (x * width / 2.0, y * height / 2.0);
- Point {
- x: centre.x + x * cos - y * sin,
- y: centre.y + x * sin + y * cos,
- }
+ Point { x: centre.x + x * cos - y * sin, y: centre.y + x * sin + y * cos }
});
- points_box(&corners).unwrap_or(Box {
- left: centre.x,
- top: centre.y,
- width: 0.0,
- height: 0.0,
- })
+ points_box(&corners).unwrap_or(Box { left: centre.x, top: centre.y, width: 0.0, height: 0.0 })
}
/// Whether a point falls on it: its whole box, as Fabric finds a target, not its ink.
@@ -437,10 +406,7 @@ impl Object {
}
fn number(&self, name: &str, otherwise: f64) -> f64 {
- self.fields
- .get(name)
- .and_then(Value::as_f64)
- .unwrap_or(otherwise)
+ self.fields.get(name).and_then(Value::as_f64).unwrap_or(otherwise)
}
fn list(&self, name: &str, read: impl Fn(&Value) -> Option) -> Vec {
@@ -459,21 +425,11 @@ fn stored(value: f64) -> Value {
}
fn point_of(value: &Value) -> Option {
- Some(Point {
- x: value.get("x")?.as_f64()?,
- y: value.get("y")?.as_f64()?,
- })
+ Some(Point { x: value.get("x")?.as_f64()?, y: value.get("y")?.as_f64()? })
}
impl Hue {
- pub const ALL: [Self; 6] = [
- Self::Ink,
- Self::Blue,
- Self::Green,
- Self::Amber,
- Self::Red,
- Self::Purple,
- ];
+ pub const ALL: [Self; 6] = [Self::Ink, Self::Blue, Self::Green, Self::Amber, Self::Red, Self::Purple];
pub fn name(self) -> &'static str {
match self {
@@ -488,10 +444,7 @@ impl Hue {
/// A name no theme paints is ink, as an object with none.
fn named(name: &str) -> Self {
- Self::ALL
- .into_iter()
- .find(|hue| hue.name() == name)
- .unwrap_or_default()
+ Self::ALL.into_iter().find(|hue| hue.name() == name).unwrap_or_default()
}
}
@@ -514,12 +467,8 @@ impl PathCommand {
fn read(value: &Value) -> Option {
let parts = value.as_array()?;
- let at = |index: usize| {
- Some(Point {
- x: parts.get(index)?.as_f64()?,
- y: parts.get(index + 1)?.as_f64()?,
- })
- };
+ let at =
+ |index: usize| Some(Point { x: parts.get(index)?.as_f64()?, y: parts.get(index + 1)?.as_f64()? });
match parts.first()?.as_str()? {
"M" => Some(Self::Move(at(1)?)),
"L" => Some(Self::Line(at(1)?)),
diff --git a/crates/drawing/src/scene/tests.rs b/crates/drawing/src/scene/tests.rs
index f82d8d0a6..4134c9a04 100644
--- a/crates/drawing/src/scene/tests.rs
+++ b/crates/drawing/src/scene/tests.rs
@@ -59,11 +59,7 @@ fn a_body_with_no_scene_opens_as_a_new_drawing() {
#[test]
fn each_object_reads_as_its_kind_and_hue() {
let drawing = drawn();
- let read: Vec<_> = drawing
- .objects
- .iter()
- .map(|object| (object.kind(), object.hue()))
- .collect();
+ let read: Vec<_> = drawing.objects.iter().map(|object| (object.kind(), object.hue())).collect();
assert_eq!(
read,
@@ -111,19 +107,12 @@ fn an_object_is_placed_by_its_centre_with_fabrics_transform() {
#[test]
fn a_field_left_out_reads_as_fabrics_default() {
let drawing =
- Drawing::read(r#"{"scene":{"objects":[{"type":"Textbox","hue":"teal","ends":[1,2]}]}}"#)
- .unwrap();
+ Drawing::read(r#"{"scene":{"objects":[{"type":"Textbox","hue":"teal","ends":[1,2]}]}}"#).unwrap();
let object = &drawing.objects[0];
assert_eq!(object.centre(), at(0.0, 0.0));
assert_eq!(
- [
- object.scale_x(),
- object.scale_y(),
- object.angle(),
- object.stroke_width(),
- object.font_size(),
- ],
+ [object.scale_x(), object.scale_y(), object.angle(), object.stroke_width(), object.font_size(),],
[1.0, 1.0, 0.0, 1.0, 40.0]
);
assert_eq!(object.hue(), Hue::Ink);
@@ -139,14 +128,8 @@ fn an_arrow_holds_its_ends_its_shapes_and_its_path() {
assert_eq!(arrow.from(), Some("rect-1"));
assert_eq!(arrow.to(), Some("ellipse-1"));
- assert_eq!(
- arrow.ends().map(|ends| ends[0]),
- Some(240.000_000_000_000_03)
- );
- assert_eq!(
- arrow.path().first(),
- Some(&PathCommand::Move(at(240.0, 90.1)))
- );
+ assert_eq!(arrow.ends().map(|ends| ends[0]), Some(240.000_000_000_000_03));
+ assert_eq!(arrow.path().first(), Some(&PathCommand::Move(at(240.0, 90.1))));
assert_eq!(arrow.path().last(), Some(&PathCommand::Close));
}
@@ -167,8 +150,7 @@ fn a_freehand_line_is_read_with_its_curves() {
#[test]
fn a_path_command_the_app_never_wrote_is_not_drawn_and_stays_stored() {
- let body =
- r#"{"scene":{"objects":[{"type":"Path","path":[["M",1,2],["C",1,2,3,4,5,6],["L",3]]}]}}"#;
+ let body = r#"{"scene":{"objects":[{"type":"Path","path":[["M",1,2],["C",1,2,3,4,5,6],["L",3]]}]}}"#;
let drawing = Drawing::read(body).unwrap();
assert_eq!(drawing.objects[0].path(), [PathCommand::Move(at(1.0, 2.0))]);
@@ -179,25 +161,10 @@ fn a_path_command_the_app_never_wrote_is_not_drawn_and_stays_stored() {
fn a_diamond_keeps_its_corners_a_text_its_words_a_group_its_children() {
let drawing = drawn();
- assert_eq!(
- drawing.objects[2].points(),
- [
- at(60.0, 0.0),
- at(120.0, 40.0),
- at(60.0, 80.0),
- at(0.0, 40.0)
- ]
- );
- assert_eq!(
- drawing.objects[5].text(),
- Some("API gateway\nsits in front of « everything »")
- );
+ assert_eq!(drawing.objects[2].points(), [at(60.0, 0.0), at(120.0, 40.0), at(60.0, 80.0), at(0.0, 40.0)]);
+ assert_eq!(drawing.objects[5].text(), Some("API gateway\nsits in front of « everything »"));
assert_eq!(drawing.objects[5].font_size(), 18.0);
- let inside: Vec<_> = drawing.objects[6]
- .children
- .iter()
- .map(Object::kind)
- .collect();
+ let inside: Vec<_> = drawing.objects[6].children.iter().map(Object::kind).collect();
assert_eq!(inside, [Kind::Rect, Kind::Textbox]);
}
@@ -215,18 +182,105 @@ fn an_object_taken_away_leaves_the_rest_as_stored() {
drawing.objects.remove(0);
- assert_eq!(
- drawing.write(),
- r#"{"version":1,"scene":{"objects":[{"id":"b"}],"background":"x"}}"#
- );
+ assert_eq!(drawing.write(), r#"{"version":1,"scene":{"objects":[{"id":"b"}],"background":"x"}}"#);
}
#[test]
fn the_first_object_put_on_an_empty_scene_is_stored() {
let mut drawing = Drawing::read(r#"{"scene":{}}"#).unwrap();
- drawing.objects = Drawing::read(r#"{"scene":{"objects":[{"id":"a"}]}}"#)
- .unwrap()
- .objects;
+ drawing.objects = Drawing::read(r#"{"scene":{"objects":[{"id":"a"}]}}"#).unwrap().objects;
assert_eq!(drawing.write(), r#"{"scene":{"objects":[{"id":"a"}]}}"#);
}
+
+/// As Fabric stores one: two decimals, and no `.0`.
+#[test]
+fn a_number_is_stored_with_two_decimals_at_most() {
+ for (value, expected) in [
+ (1.0, "1"),
+ (-0.5, "-0.5"),
+ (1.005_1, "1.01"),
+ (0.001, "0"),
+ (1e14, "100000000000000"),
+ (1e15, "1000000000000000.0"),
+ ] {
+ assert_eq!(stored(value).to_string(), expected);
+ }
+}
+
+#[test]
+fn an_angle_is_stored_within_one_turn() {
+ let mut object = Object::make("Rect", "a".to_owned(), Hue::Ink);
+ for (degrees, angle) in [(90.0, 90.0), (360.0, 0.0), (-90.0, 270.0), (725.0, 5.0)] {
+ object.set_angle(degrees);
+ assert_eq!(object.angle().to_string(), angle.to_string());
+ }
+}
+
+/// Its whole box, its stroke counted, turned with it.
+#[test]
+fn a_point_is_on_an_object_by_its_box() {
+ let object = |angle: f64| {
+ let body = format!(
+ r#"{{"scene":{{"objects":[{{"type":"Ellipse","left":10,"top":20,"width":98,"height":18,"strokeWidth":2,"angle":{angle}}}]}}}}"#
+ );
+ Drawing::read(&body).unwrap().objects.remove(0)
+ };
+
+ let level = object(0.0);
+ for (x, y, on) in [
+ (60.0, 20.0, true),
+ (60.1, 20.0, false),
+ (10.0, 30.0, true),
+ (10.0, 30.1, false),
+ (-40.0, 10.0, true),
+ ] {
+ assert_eq!(level.contains(at(x, y)), on, "{x} {y}");
+ }
+ let turned = object(90.0);
+ assert!(turned.contains(at(10.0, 69.0)) && !turned.contains(at(59.0, 20.0)));
+}
+
+#[test]
+fn a_drawing_covers_all_that_is_drawn() {
+ let body = r#"{"scene":{"objects":[
+ {"type":"Rect","left":0,"top":0,"width":10,"height":10,"strokeWidth":0},
+ {"type":"Rect","left":50,"top":20,"width":20,"height":10,"strokeWidth":0}]}}"#;
+ let covered = Drawing::read(body).unwrap().bounds().unwrap();
+
+ assert_eq!(
+ [covered.left, covered.top, covered.width, covered.height].map(|side| side.to_string()),
+ ["-5", "-5", "65", "30"]
+ );
+ assert_eq!(Drawing::empty().bounds(), None);
+}
+
+#[test]
+fn a_new_drawing_is_empty_and_read_back() {
+ let empty = Drawing::empty();
+
+ assert_eq!(empty.write(), r#"{"version":1,"scene":{"version":"7.4.0"}}"#);
+ let read = Drawing::read(&empty.write()).unwrap();
+ assert_eq!(read.write(), empty.write());
+}
+
+#[test]
+fn a_shape_let_go_is_null_and_its_point_goes_with_it() {
+ let mut arrow = Object::make("Path", "a".to_owned(), Hue::Ink);
+ arrow.set_bound("from", Some("b"));
+ arrow.set_anchor("from", Some(Side::Left));
+ assert_eq!((arrow.from(), arrow.anchor("from")), (Some("b"), Some(Side::Left)));
+
+ arrow.set_bound("from", None);
+ assert_eq!((arrow.from(), arrow.anchor("from")), (None, None));
+ assert_eq!(arrow.fields().get("from"), Some(&Value::Null));
+}
+
+#[test]
+fn each_side_is_read_back_by_its_word() {
+ let mut arrow = Object::make("Path", "a".to_owned(), Hue::Ink);
+ for side in Side::ALL {
+ arrow.set_anchor("to", Some(side));
+ assert_eq!(arrow.anchor("to"), Some(side));
+ }
+}
diff --git a/crates/drawing/src/text.rs b/crates/drawing/src/text.rs
index ab1505d93..448cdffe2 100644
--- a/crates/drawing/src/text.rs
+++ b/crates/drawing/src/text.rs
@@ -36,10 +36,7 @@ impl Fonts {
.map_or_else(String::new, |(name, _)| name.clone());
database.set_sans_serif_family(family.clone());
Self {
- faces: files
- .iter()
- .filter_map(|file| FontRef::new(file).ok())
- .collect(),
+ faces: files.iter().filter_map(|file| FontRef::new(file).ok()).collect(),
database: Arc::new(database),
family,
}
@@ -54,9 +51,7 @@ impl Fonts {
}
fn width(&self, word: &str, font_size: f64) -> f64 {
- word.chars()
- .map(|character| self.advance(character) * font_size)
- .sum()
+ word.chars().map(|character| self.advance(character) * font_size).sum()
}
}
diff --git a/crates/drawing/src/text/tests.rs b/crates/drawing/src/text/tests.rs
index 9d944ebb5..6439e4de2 100644
--- a/crates/drawing/src/text/tests.rs
+++ b/crates/drawing/src/text/tests.rs
@@ -14,8 +14,7 @@ fn wrapped(text: &str, width: f64) -> Vec {
}
/// Where Fabric's lines, in a browser, kerned, break elsewhere than these.
-const KERNED_ELSEWHERE: [&str; 1] =
- ["The quick brown fox jumps over the lazy dog, twice over, then rests"];
+const KERNED_ELSEWHERE: [&str; 1] = ["The quick brown fox jumps over the lazy dog, twice over, then rests"];
#[test]
fn the_lines_are_those_fabric_broke_in_a_browser() {
@@ -42,10 +41,7 @@ fn the_lines_are_those_fabric_broke_in_a_browser() {
#[test]
fn a_word_is_never_broken_and_widens_the_box() {
- assert_eq!(
- wrapped("supercalifragilistic ok", 10.0),
- ["supercalifragilistic", "ok"]
- );
+ assert_eq!(wrapped("supercalifragilistic ok", 10.0), ["supercalifragilistic", "ok"]);
}
#[test]
@@ -64,3 +60,16 @@ fn the_baselines_are_fabrics() {
assert!((line_step(18.0, 1.16) - 23.5944).abs() < 1e-9);
assert!((first_baseline(18.0) - 15.82452).abs() < 1e-9);
}
+
+/// Spaces that do not fit end a line; a blank line is a line.
+#[test]
+fn lines_break_at_spaces_and_at_line_ends() {
+ for (text, width, lines) in [
+ ("", 180.0, vec![""]),
+ ("a\n\nb", 180.0, vec!["a", "", "b"]),
+ ("a b", 1.0, vec!["a", "b"]),
+ ("ab cd", 1000.0, vec!["ab cd"]),
+ ] {
+ assert_eq!(wrapped(text, width), lines, "{text:?}");
+ }
+}
diff --git a/crates/engine/benches/commands.rs b/crates/engine/benches/commands.rs
index 264fd2427..034290ad4 100644
--- a/crates/engine/benches/commands.rs
+++ b/crates/engine/benches/commands.rs
@@ -77,10 +77,7 @@ fn whole_corpus_read(c: &mut Criterion) {
// Narrowed in SQL to the 160 pinned notes: what a filtered query pays for its side tables.
group.bench_function("query_notes, pinned only", |b| {
- let pinned = NotesQuery {
- filter: NoteFilter::Pinned,
- ..query("")
- };
+ let pinned = NotesQuery { filter: NoteFilter::Pinned, ..query("") };
b.iter(|| black_box(run_query(&mut corpus, &pinned)));
});
@@ -97,10 +94,7 @@ fn single_write(c: &mut Criterion) {
let mut at = 0u32;
b.iter(|| {
at += 1;
- let patch = NotePatch {
- title: Some(format!("Retitled {at}")),
- ..NotePatch::default()
- };
+ let patch = NotePatch { title: Some(format!("Retitled {at}")), ..NotePatch::default() };
black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write"));
});
});
@@ -122,10 +116,7 @@ fn body_writes(c: &mut Criterion) {
// A full history, so every save below also rotates the oldest body out.
for kept in 0..=engine::notes::revision::KEEP {
- let patch = NotePatch {
- content: Some(format!("{body}\n-- {kept}")),
- ..NotePatch::default()
- };
+ let patch = NotePatch { content: Some(format!("{body}\n-- {kept}")), ..NotePatch::default() };
store::update(&mut corpus.connection, &id, &patch, now()).expect("a write");
}
@@ -133,10 +124,7 @@ fn body_writes(c: &mut Criterion) {
let mut at = 0u32;
b.iter(|| {
at += 1;
- let patch = NotePatch {
- content: Some(format!("{body}\n-- saved {at}")),
- ..NotePatch::default()
- };
+ let patch = NotePatch { content: Some(format!("{body}\n-- saved {at}")), ..NotePatch::default() };
black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write"));
});
});
@@ -145,10 +133,7 @@ fn body_writes(c: &mut Criterion) {
let mut pinned = false;
b.iter(|| {
pinned = !pinned;
- let patch = NotePatch {
- pinned: Some(pinned),
- ..NotePatch::default()
- };
+ let patch = NotePatch { pinned: Some(pinned), ..NotePatch::default() };
black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write"));
});
});
@@ -164,10 +149,7 @@ fn bulk(c: &mut Criterion) {
group.bench_function("tag_notes", |b| {
b.iter(|| {
- black_box(
- store::tag_many(&mut corpus.connection, &ids, &["bulk".to_string()])
- .expect("a batch"),
- );
+ black_box(store::tag_many(&mut corpus.connection, &ids, &["bulk".to_string()]).expect("a batch"));
});
});
@@ -183,9 +165,7 @@ fn bulk(c: &mut Criterion) {
group.bench_function("delete_notes then restore_notes", |b| {
b.iter(|| {
store::trash::trash_many(&mut corpus.connection, &ids, now()).expect("a trashing");
- black_box(
- store::trash::restore_many(&mut corpus.connection, &ids).expect("a restoration"),
- );
+ black_box(store::trash::restore_many(&mut corpus.connection, &ids).expect("a restoration"));
});
});
@@ -209,9 +189,7 @@ fn aggregation(c: &mut Criterion) {
group.bench_function("list_global_placeholders", |b| {
b.iter(|| {
- black_box(
- store::global_placeholder_values(&mut corpus.connection).expect("the globals"),
- );
+ black_box(store::global_placeholder_values(&mut corpus.connection).expect("the globals"));
});
});
@@ -227,14 +205,9 @@ fn corpus_rewrite(c: &mut Criterion) {
let mut at = 0u32;
b.iter(|| {
at += 1;
- let (from, into) = if at.is_multiple_of(2) {
- ("ops", "operations")
- } else {
- ("operations", "ops")
- };
- black_box(
- store::retag(&mut corpus.connection, &[from.to_string()], into).expect("a retag"),
- );
+ let (from, into) =
+ if at.is_multiple_of(2) { ("ops", "operations") } else { ("operations", "ops") };
+ black_box(store::retag(&mut corpus.connection, &[from.to_string()], into).expect("a retag"));
});
});
@@ -259,14 +232,8 @@ fn disk(c: &mut Criterion) {
let notes = store::all(&mut corpus.connection, None).expect("the corpus");
let packed = bundle::collect(&mut corpus.connection, notes).expect("a bundle");
black_box(
- file::write(
- &target,
- &packed,
- &attachments,
- corpus.connection.vault(),
- None,
- )
- .expect("a written file"),
+ file::write(&target, &packed, &attachments, corpus.connection.vault(), None)
+ .expect("a written file"),
);
});
});
@@ -275,8 +242,7 @@ fn disk(c: &mut Criterion) {
b.iter(|| {
let (incoming, mut payload) = file::read(&target, None).expect("a readable file");
black_box(
- bundle::merge(&mut corpus.connection, incoming, &mut payload, &attachments)
- .expect("a merge"),
+ bundle::merge(&mut corpus.connection, incoming, &mut payload, &attachments).expect("a merge"),
);
});
});
@@ -304,25 +270,19 @@ fn attachment(c: &mut Criterion) {
created_at: now(),
};
let (db, vault) = corpus.connection.split();
- sealed::write_sealed(
- vault,
- &directory.join(screenshot.stored_name()),
- &vec![7u8; 256 * 1024],
- )
- .expect("a sealed file");
+ sealed::write_sealed(vault, &directory.join(screenshot.stored_name()), &vec![7u8; 256 * 1024])
+ .expect("a sealed file");
attachments::store::create(db, vault, &screenshot).expect("a record");
group.bench_function("read_attachment, 256 kB", |b| {
b.iter(|| {
black_box(
- attachments::files::read_plain(&mut corpus.connection, "a-screenshot")
- .expect("the bytes"),
+ attachments::files::read_plain(&mut corpus.connection, "a-screenshot").expect("the bytes"),
)
});
});
- let profile =
- std::env::temp_dir().join(format!("devnotes-bench-profile-{}", uuid::Uuid::new_v4()));
+ let profile = std::env::temp_dir().join(format!("devnotes-bench-profile-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&profile).expect("a writable temporary directory");
libraries::registry::open_directory_in(&profile).expect("a registry");
@@ -348,12 +308,8 @@ fn unlock(c: &mut Criterion) {
group.bench_function("Vault::derive at the shipped cost", |b| {
b.iter(|| {
black_box(
- Vault::derive(
- black_box("a passphrase"),
- b"0123456789abcdef",
- Cost::default(),
- )
- .expect("a key"),
+ Vault::derive(black_box("a passphrase"), b"0123456789abcdef", Cost::default())
+ .expect("a key"),
)
});
});
@@ -367,11 +323,9 @@ fn cookie_jar(c: &mut Criterion) {
use engine::http::cookies::{self, Change, JarCookie};
let scratch = tempfile::tempdir().expect("a temporary directory");
- let mut library = engine::db::open(
- &scratch.path().join("jar.sqlite3"),
- engine::db::test_vault().expect("a key"),
- )
- .expect("a library");
+ let mut library =
+ engine::db::open(&scratch.path().join("jar.sqlite3"), engine::db::test_vault().expect("a key"))
+ .expect("a library");
let changes: Vec = (0..500)
.map(|at| {
Change::Set(JarCookie {
diff --git a/crates/engine/benches/corpus.rs b/crates/engine/benches/corpus.rs
index 9d71d0a5a..1e760976b 100644
--- a/crates/engine/benches/corpus.rs
+++ b/crates/engine/benches/corpus.rs
@@ -29,9 +29,7 @@ pub(crate) const NOTES: usize = 8000;
/// Roughly 13 kB of body.
const LINES_PER_NOTE: usize = 200;
const SPACES: usize = 4;
-const TAGS: &[&str] = &[
- "angular", "api", "ci", "db", "docker", "git", "ops", "rust", "sql", "ssh",
-];
+const TAGS: &[&str] = &["angular", "api", "ci", "db", "docker", "git", "ops", "rust", "sql", "ssh"];
/// A database file of its own per group, erased with the guard.
pub(crate) struct Corpus {
@@ -82,23 +80,14 @@ fn draft(seed: usize, space_id: &str) -> NoteDraft {
language: Language::Rs,
content: if checklist { String::new() } else { body(seed) },
source: "Runbook".to_string(),
- tags: vec![
- TAGS[seed % TAGS.len()].to_string(),
- TAGS[(seed + 3) % TAGS.len()].to_string(),
- ],
+ tags: vec![TAGS[seed % TAGS.len()].to_string(), TAGS[(seed + 3) % TAGS.len()].to_string()],
pinned: seed.is_multiple_of(50),
lifecycle: if seed.is_multiple_of(25) {
- NoteLifecycle::Expires {
- at: now() + TimeDelta::days(3),
- }
+ NoteLifecycle::Expires { at: now() + TimeDelta::days(3) }
} else {
NoteLifecycle::Permanent
},
- kind: if checklist {
- NoteKind::Checklist
- } else {
- NoteKind::Snippet
- },
+ kind: if checklist { NoteKind::Checklist } else { NoteKind::Snippet },
priority: Priority::None,
items: if checklist {
(0..5u32)
@@ -125,11 +114,7 @@ pub(crate) fn run_query(corpus: &mut Corpus, request: &NotesQuery) -> Vec Corpus {
// The corpus is sealed like a real library, so the benchmarks measure what the
// commands really pay, encryption included.
- let mut connection = db::open(
- &directory.join("bench.sqlite3"),
- db::test_vault().expect("a key"),
- )
- .expect("a fresh database");
+ let mut connection = db::open(&directory.join("bench.sqlite3"), db::test_vault().expect("a key"))
+ .expect("a fresh database");
let space_ids: Vec = (0..SPACES)
- .map(|at| {
- spaces::create(&mut connection, &format!("Space {at}"))
- .expect("a space")
- .id
- })
+ .map(|at| spaces::create(&mut connection, &format!("Space {at}")).expect("a space").id)
.collect();
let at = now();
let note_ids: Vec = (0..notes)
.map(|seed| {
let space_id = &space_ids[seed % SPACES];
- store::create(&mut connection, draft(seed, space_id), at)
- .expect("a note")
- .id
+ store::create(&mut connection, draft(seed, space_id), at).expect("a note").id
})
.collect();
- Corpus {
- connection,
- space_ids,
- note_ids,
- _directory: TempDir(directory),
- }
+ Corpus { connection, space_ids, note_ids, _directory: TempDir(directory) }
}
diff --git a/crates/engine/benches/corpus_size.rs b/crates/engine/benches/corpus_size.rs
index a70f41796..ede273c5a 100644
--- a/crates/engine/benches/corpus_size.rs
+++ b/crates/engine/benches/corpus_size.rs
@@ -66,13 +66,9 @@ fn query_by_corpus_size(c: &mut Criterion) {
// The same query stopped before the view is built: the gap between the two is
// what the view costs, and what a LIMIT could not take away.
- group.bench_with_input(
- BenchmarkId::new(format!("{name}, read only"), size),
- &size,
- |b, _| {
- b.iter(|| black_box(read_only(&mut corpus, &request)));
- },
- );
+ group.bench_with_input(BenchmarkId::new(format!("{name}, read only"), size), &size, |b, _| {
+ b.iter(|| black_box(read_only(&mut corpus, &request)));
+ });
}
}
diff --git a/crates/engine/benches/index.rs b/crates/engine/benches/index.rs
index 8229dabaa..2142503bf 100644
--- a/crates/engine/benches/index.rs
+++ b/crates/engine/benches/index.rs
@@ -31,27 +31,16 @@ struct Bench {
fn bench(size: Size) -> Bench {
let mut corpus = build(size);
let runtime = tokio::runtime::Runtime::new().unwrap();
- let paths = Paths {
- profile: std::env::temp_dir(),
- };
- let engine = Arc::new(Engine::new(
- paths,
- Arc::new(RecordingSink::default()),
- runtime.handle().clone(),
- ));
+ let paths = Paths { profile: std::env::temp_dir() };
+ let engine = Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone()));
*engine.db().lock().unwrap() = corpus.library.take();
reference::attach(&engine, &corpus.note_ids);
- Bench {
- engine,
- runtime,
- corpus,
- }
+ Bench { engine, runtime, corpus }
}
impl Bench {
fn fill(&self) {
- self.runtime
- .block_on(engine::index::fill(Arc::clone(&self.engine)));
+ self.runtime.block_on(engine::index::fill(Arc::clone(&self.engine)));
}
}
@@ -103,17 +92,11 @@ fn index_query(c: &mut Criterion) {
let engine = &bench.engine;
let mut group = c.benchmark_group(format!("index_query/{}", label(size)));
group.sample_size(20);
- for (name, search) in [
- ("unfiltered", ""),
- ("search matching nothing", "zzzzzz"),
- ("search folding accents", "etape"),
- ] {
+ for (name, search) in
+ [("unfiltered", ""), ("search matching nothing", "zzzzzz"), ("search folding accents", "etape")]
+ {
group.bench_function(name, |b| {
- b.iter(|| {
- black_box(run_here(engine, |e| {
- query_notes(e, &query(search)).unwrap()
- }))
- });
+ b.iter(|| black_box(run_here(engine, |e| query_notes(e, &query(search)).unwrap())));
});
}
let space = bench.corpus.space_ids[0].clone();
@@ -145,10 +128,7 @@ fn index_refresh(c: &mut Criterion) {
let mut n = 0_u32;
b.iter(|| {
n += 1;
- let patch = NotePatch {
- title: Some(format!("Retitrée {n}")),
- ..NotePatch::default()
- };
+ let patch = NotePatch { title: Some(format!("Retitrée {n}")), ..NotePatch::default() };
black_box(run_here(engine, |e| update_note(e, &id, &patch).unwrap()))
});
});
diff --git a/crates/engine/benches/reference.rs b/crates/engine/benches/reference.rs
index d8162d08e..a7a631829 100644
--- a/crates/engine/benches/reference.rs
+++ b/crates/engine/benches/reference.rs
@@ -88,20 +88,13 @@ fn line(seed: usize) -> &'static str {
}
fn lines(seed: usize, count: usize) -> String {
- (0..count)
- .map(|n| line(seed + n))
- .collect::>()
- .join("\n")
+ (0..count).map(|n| line(seed + n)).collect::>().join("\n")
}
fn markdown(seed: usize) -> String {
let mut text = format!("# Procédure {seed}\n\n");
for section in 0..4 {
- let _ = write!(
- text,
- "## Étape {section}\n\n{}\n\n",
- lines(seed + section, 4)
- );
+ let _ = write!(text, "## Étape {section}\n\n{}\n\n", lines(seed + section, 4));
text.push_str("- vérifier\n- **déployer**\n- surveiller\n\n");
text.push_str("| hôte | rôle |\n| --- | --- |\n| db-1 | primaire |\n\n");
let _ = write!(text, "```sql\n{}\n```\n\n", lines(seed, 3));
@@ -169,17 +162,10 @@ fn note(n: usize, size: Size, space_id: &str, folder_id: Option<&str>) -> Note {
space_id: space_id.to_string(),
folder_id: folder_id.map(str::to_string),
title: format!("Note {n} — étape de déploiement"),
- language: if kind == NoteKind::Snippet {
- LANGUAGES[n % LANGUAGES.len()]
- } else {
- Language::Txt
- },
+ language: if kind == NoteKind::Snippet { LANGUAGES[n % LANGUAGES.len()] } else { Language::Txt },
content,
source: format!("API Gateway / Auth / {}", n % 50),
- tags: vec![
- format!("tag-{}", n % TAGS),
- format!("tag-{}", (n * 7) % TAGS),
- ],
+ tags: vec![format!("tag-{}", n % TAGS), format!("tag-{}", (n * 7) % TAGS)],
pinned: n.is_multiple_of(97),
created_at: at,
updated_at: at,
@@ -196,30 +182,20 @@ fn uuid(n: usize) -> String {
}
pub(crate) fn build(size: Size) -> Reference {
- let directory =
- std::env::temp_dir().join(format!("devnotes-reference-{}", uuid::Uuid::new_v4()));
+ let directory = std::env::temp_dir().join(format!("devnotes-reference-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&directory).unwrap();
let vault = engine::vault::file::create(&directory, "a passphrase", Cost::FOR_TESTS).unwrap();
let mut library = db::open(&directory.join("devnotes.sqlite3"), vault).unwrap();
let (space_ids, note_ids) = seed(&mut library, size);
std::fs::create_dir_all(directory.join("attachments")).unwrap();
- Reference {
- library: Some(library),
- note_ids,
- space_ids,
- _directory: Directory(directory),
- }
+ Reference { library: Some(library), note_ids, space_ids, _directory: Directory(directory) }
}
/// Everything but the attachments, into a library already open: the spaces, then the notes.
pub(crate) fn seed(library: &mut Library, size: Size) -> (Vec, Vec) {
let space_ids: Vec = (0..SPACES)
- .map(|n| {
- engine::spaces::store::create(library, &format!("Espace {n}"))
- .unwrap()
- .id
- })
+ .map(|n| engine::spaces::store::create(library, &format!("Espace {n}")).unwrap().id)
.collect();
let folder_ids = folders(library, &space_ids);
let note_ids = notes(library, size, &space_ids, &folder_ids);
@@ -330,15 +306,10 @@ fn http(library: &mut Library) {
},
};
let name = draft.name.clone();
- request_ids.push(
- engine::http::store::create_request(library, &draft, &name, now())
- .unwrap()
- .id,
- );
+ request_ids.push(engine::http::store::create_request(library, &draft, &name, now()).unwrap().id);
}
for n in 0..ENVIRONMENTS {
- engine::http::environments::store::create(library, &format!("Environnement {n}"), now())
- .unwrap();
+ engine::http::environments::store::create(library, &format!("Environnement {n}"), now()).unwrap();
}
for n in 0..HISTORY {
let summary = serde_json::from_value(serde_json::json!({
diff --git a/crates/engine/benches/reference_profile.rs b/crates/engine/benches/reference_profile.rs
index 1b31eb68b..3bf7f5cef 100644
--- a/crates/engine/benches/reference_profile.rs
+++ b/crates/engine/benches/reference_profile.rs
@@ -31,11 +31,7 @@ fn main() {
std::fs::create_dir_all(&profile).unwrap();
let runtime = tokio::runtime::Runtime::new().unwrap();
let paths = Paths { profile };
- let engine = Arc::new(Engine::new(
- paths,
- Arc::new(RecordingSink::default()),
- runtime.handle().clone(),
- ));
+ let engine = Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone()));
run_here(&engine, |e| create_vault(e, secret(PASSPHRASE.to_owned()))).unwrap();
let (_, note_ids) = run_here(&engine, |e| {
let mut library = e.db().lock().unwrap();
diff --git a/crates/engine/build.rs b/crates/engine/build.rs
index 9c350d6c4..639443b0e 100644
--- a/crates/engine/build.rs
+++ b/crates/engine/build.rs
@@ -13,8 +13,8 @@ fn export_metadata() {
println!("cargo:rerun-if-changed=Cargo.toml");
let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo");
- let text = fs::read_to_string(Path::new(&manifest_dir).join("Cargo.toml"))
- .expect("Cargo.toml is readable");
+ let text =
+ fs::read_to_string(Path::new(&manifest_dir).join("Cargo.toml")).expect("Cargo.toml is readable");
let manifest: toml::Table = toml::from_str(&text).expect("Cargo.toml is valid TOML");
let metadata = manifest
@@ -38,10 +38,7 @@ fn export_metadata() {
let author = authors.split(';').next().unwrap_or_default();
println!("cargo:rustc-env=DEVNOTES_AUTHOR={author}");
- println!(
- "cargo:rustc-env=DEVNOTES_RUST_VERSION={}",
- pinned_toolchain(&manifest_dir)
- );
+ println!("cargo:rustc-env=DEVNOTES_RUST_VERSION={}", pinned_toolchain(&manifest_dir));
}
/// Every page of `docs/content`, by language and name, for `docs.rs` to embed: a page added there
@@ -59,11 +56,7 @@ fn list_the_documentation() {
let path = file.expect("docs/content is readable").path();
if path.extension().is_some_and(|extension| extension == "md") {
let id = path.file_stem().and_then(|stem| stem.to_str());
- pages.push((
- language,
- id.expect("a page's name is text").to_owned(),
- path,
- ));
+ pages.push((language, id.expect("a page's name is text").to_owned(), path));
}
}
}
@@ -72,8 +65,7 @@ fn list_the_documentation() {
let mut out = String::from("const SOURCES: &[(&str, &str, &str)] = &[\n");
for (language, id, path) in pages {
let path = path.to_str().expect("the repository is at a path of text");
- writeln!(out, " ({language:?}, {id:?}, include_str!({path:?})),")
- .expect("a string grows");
+ writeln!(out, " ({language:?}, {id:?}, include_str!({path:?})),").expect("a string grows");
}
out.push_str("];\n");
let target = Path::new(&env::var("OUT_DIR").expect("cargo sets OUT_DIR")).join("docs.rs");
diff --git a/crates/engine/src/attachments.rs b/crates/engine/src/attachments.rs
index 774f11918..b33e99d29 100644
--- a/crates/engine/src/attachments.rs
+++ b/crates/engine/src/attachments.rs
@@ -34,10 +34,7 @@ pub async fn attach_file(
crate::db::run(engine, move |engine| {
engine.write(|db| {
let answer = store_new(note_id, file_name, &bytes, db)?;
- let changed = Changed {
- attachments: true,
- ..Changed::default()
- };
+ let changed = Changed { attachments: true, ..Changed::default() };
Ok((answer, changed))
})
})
@@ -97,10 +94,7 @@ pub fn attach_image(
let png = model::encode_png(width, height, rgba)?;
model::validate_size(png.len() as u64, &model::png_name(file_name))?;
let answer = store_new(note_id, model::png_name(file_name), &png, db)?;
- let changed = Changed {
- attachments: true,
- ..Changed::default()
- };
+ let changed = Changed { attachments: true, ..Changed::default() };
Ok((answer, changed))
})
}
@@ -108,10 +102,7 @@ pub fn attach_image(
pub fn delete_attachment(engine: &Engine, id: &str) -> Result<(), AppError> {
engine.write(|db| {
delete(db, id)?;
- let changed = Changed {
- attachments: true,
- ..Changed::default()
- };
+ let changed = Changed { attachments: true, ..Changed::default() };
Ok(((), changed))
})
}
@@ -130,29 +121,3 @@ fn delete(db: &Db, id: &str) -> Result<(), StorageError> {
Ok(())
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use files::tests::{a_library_with_a_note, attachments_of};
-
- #[test]
- fn deleting_an_attachment_takes_its_file_with_it() {
- let (_scratch, db, note_id) = a_library_with_a_note();
- let directory = attachments_of(&db);
- let stored = store_new(note_id.clone(), "capture.png".to_string(), b"png", &db).unwrap();
-
- delete(&db, &stored.id).unwrap();
-
- assert!(!directory.join(stored.stored_name()).exists());
- assert!(
- store::list(&mut lock(&db).unwrap(), ¬e_id)
- .unwrap()
- .is_empty()
- );
- assert!(matches!(
- delete(&db, &stored.id),
- Err(StorageError::AttachmentNotFound(_))
- ));
- }
-}
diff --git a/crates/engine/src/attachments/files.rs b/crates/engine/src/attachments/files.rs
index b0da4be63..7d4b1f12a 100644
--- a/crates/engine/src/attachments/files.rs
+++ b/crates/engine/src/attachments/files.rs
@@ -66,8 +66,8 @@ pub(crate) fn store_new(
let destination = directory.join(attachment.stored_name());
let (db, vault) = connection.split();
- let stored = sealed::write_sealed(vault, &destination, bytes)
- .and_then(|_| store::create(db, vault, &attachment));
+ let stored =
+ sealed::write_sealed(vault, &destination, bytes).and_then(|_| store::create(db, vault, &attachment));
if stored.is_err() {
remove_files(&directory, &[attachment.stored_name()]);
}
@@ -114,12 +114,9 @@ pub(crate) fn write_plain(path: &str, bytes: &[u8]) -> Result<(), StorageError>
std::fs::write(path, bytes).context(path)
}
-fn locate(
- library: &mut Library,
- id: &str,
-) -> Result<(Attachment, PathBuf, Arc), StorageError> {
- let attachment = store::find(library, id)?
- .ok_or_else(|| StorageError::AttachmentNotFound(id.to_string()))?;
+fn locate(library: &mut Library, id: &str) -> Result<(Attachment, PathBuf, Arc), StorageError> {
+ let attachment =
+ store::find(library, id)?.ok_or_else(|| StorageError::AttachmentNotFound(id.to_string()))?;
let path = directory(library).join(attachment.stored_name());
Ok((attachment, path, library.shared_vault()))
@@ -129,10 +126,7 @@ fn locate(
pub fn sweep_orphan_files(db: &Db) -> Result {
let (directory, known) = {
let mut connection = lock(db)?;
- (
- directory(&connection),
- store::all_stored_names(&mut connection)?,
- )
+ (directory(&connection), store::all_stored_names(&mut connection)?)
};
let entries = std::fs::read_dir(&directory).context("attachments sweep")?;
@@ -152,174 +146,154 @@ pub fn sweep_orphan_files(db: &Db) -> Result {
pub(crate) mod tests {
use super::*;
+ /// A library on disk, its attachments directory made, holding one note: answered with the
+ /// scratch directory that must outlive it, and the note's id.
pub(crate) fn a_library_with_a_note() -> (tempfile::TempDir, Db, String) {
- use crate::notes::model::NoteDraft;
-
let scratch = tempfile::tempdir().unwrap();
let mut library = crate::db::open_in_memory()
.unwrap()
.with_directory(scratch.path().to_path_buf());
- let space = crate::spaces::store::create(&mut library, "Personal").unwrap();
- let note = crate::notes::store::create(
- &mut library,
- NoteDraft {
- space_id: space.id,
- folder_id: None,
- title: "T".to_string(),
- language: crate::notes::language::Language::Txt,
- content: String::new(),
- source: String::new(),
- tags: Vec::new(),
- pinned: false,
- lifecycle: crate::notes::model::NoteLifecycle::Permanent,
- kind: crate::notes::kind::NoteKind::Snippet,
- priority: crate::notes::priority::Priority::None,
- items: Vec::new(),
- },
- Utc::now(),
- )
- .unwrap();
+ let space = crate::spaces::store::create(&mut library, "Work").unwrap();
+ let draft = crate::notes::model::NoteDraft {
+ folder_id: None,
+ title: "T".to_string(),
+ language: crate::notes::language::Language::Txt,
+ content: String::new(),
+ source: String::new(),
+ tags: Vec::new(),
+ pinned: false,
+ lifecycle: crate::notes::model::NoteLifecycle::Permanent,
+ kind: crate::notes::kind::NoteKind::Snippet,
+ priority: crate::notes::priority::Priority::None,
+ items: Vec::new(),
+ space_id: space.id,
+ };
+ let note = crate::notes::store::create(&mut library, draft, Utc::now()).unwrap();
+ std::fs::create_dir_all(directory(&library)).unwrap();
(scratch, std::sync::Mutex::new(Some(library)), note.id)
}
pub(crate) fn attachments_of(db: &Db) -> PathBuf {
- let directory = directory(&lock(db).unwrap());
- std::fs::create_dir_all(&directory).unwrap();
+ directory(&lock(db).unwrap())
+ }
- directory
+ fn listed(db: &Db, note_id: &str) -> Vec {
+ store::list(&mut lock(db).unwrap(), note_id).unwrap()
}
#[test]
- fn a_new_attachment_is_sealed_beside_the_library_then_recorded() {
- let (_scratch, db, note_id) = a_library_with_a_note();
- let directory = attachments_of(&db);
- let attachment =
- store_new(note_id.clone(), "capture.png".to_string(), b"png", &db).unwrap();
+ fn attachments_live_in_the_library_s_own_directory() {
+ let (scratch, db, _) = a_library_with_a_note();
- let written = std::fs::read(directory.join(attachment.stored_name())).unwrap();
- assert_ne!(written, b"png");
- let listed = store::list(&mut lock(&db).unwrap(), ¬e_id).unwrap();
- assert_eq!(listed[0].mime_type, "image/png");
+ assert_eq!(attachments_of(&db), scratch.path().join(crate::layout::ATTACHMENTS));
}
- /// A file without a record would sit there until the next launch's sweep.
+ /// Sealed like the rows beside it: the plain bytes are nowhere on disk.
#[test]
- fn an_attachment_that_cannot_be_recorded_leaves_no_file_behind() {
- let (_scratch, db, _) = a_library_with_a_note();
- let directory = attachments_of(&db);
- let refused = store_new("ghost".to_string(), "capture.png".to_string(), b"png", &db);
+ fn a_new_attachment_is_sealed_on_disk_and_recorded_with_its_plain_size_and_type() {
+ let (_scratch, db, note_id) = a_library_with_a_note();
+ let bytes = b"a credentials page";
+
+ let stored = store_new(note_id.clone(), "capture.png".to_string(), bytes, &db).unwrap();
- assert!(matches!(refused, Err(StorageError::NoteNotFound(_))));
- assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 0);
+ let on_disk = std::fs::read(attachments_of(&db).join(stored.stored_name())).unwrap();
+ assert!(!on_disk.windows(bytes.len()).any(|window| window == bytes));
+ assert_eq!((stored.byte_size, stored.mime_type.as_str()), (18, "image/png"));
+ assert_eq!(listed(&db, ¬e_id)[0].id, stored.id);
}
+ /// A file without a record would only be swept later; none is left behind.
#[test]
- fn an_attachment_reads_back_as_the_bytes_it_was_given() {
- let (_scratch, db, note_id) = a_library_with_a_note();
- attachments_of(&db);
- let stored = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap();
+ fn an_attachment_of_a_note_not_there_leaves_no_file() {
+ let (_scratch, db, _) = a_library_with_a_note();
- let (attachment, bytes) = read_plain(&mut lock(&db).unwrap(), &stored.id).unwrap();
+ let refused = store_new("missing".to_string(), "capture.png".to_string(), b"png", &db);
- assert_eq!(attachment.id, stored.id);
- assert_eq!(bytes, b"png");
+ assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == "missing"));
+ assert_eq!(std::fs::read_dir(attachments_of(&db)).unwrap().count(), 0);
}
- /// The read commands' path: the same bytes, and the lock free again once they are in hand.
#[test]
- fn an_attachment_read_outside_the_lock_leaves_it_free() {
+ fn an_attachment_is_read_back_opened_with_its_record() {
let (_scratch, db, note_id) = a_library_with_a_note();
- attachments_of(&db);
- let stored = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap();
-
- let (attachment, bytes) = read_outside_lock(&db, &stored.id).unwrap();
-
- assert_eq!(
- (attachment.id, bytes.as_slice()),
- (stored.id, b"png".as_slice())
- );
- assert!(db.try_lock().is_ok());
- assert!(matches!(
- read_outside_lock(&db, "unknown"),
- Err(StorageError::AttachmentNotFound(_))
- ));
+ let stored = store_new(note_id, "notes.txt".to_string(), b"plain", &db).unwrap();
+
+ let (record, bytes) = read_plain(&mut lock(&db).unwrap(), &stored.id).unwrap();
+ let (_, outside) = read_outside_lock(&db, &stored.id).unwrap();
+
+ assert_eq!((record.file_name.as_str(), bytes.as_slice()), ("notes.txt", &b"plain"[..]));
+ assert_eq!(outside, b"plain");
+ assert!(db.try_lock().is_ok(), "the lock is free once the bytes are in hand");
}
+ /// Opening a file nothing refers to would read outside what the library knows.
#[test]
- fn two_decrypted_copies_of_the_same_name_do_not_overwrite_each_other() {
- let (scratch, db, note_id) = a_library_with_a_note();
- attachments_of(&db);
- let first = store_new(note_id.clone(), "capture.png".to_string(), b"1", &db).unwrap();
- let second = store_new(note_id, "capture.png".to_string(), b"2", &db).unwrap();
- let open = scratch.path().join("open");
-
- let one = write_plaintext_copy(&open, &first, b"1").unwrap();
- let two = write_plaintext_copy(&open, &second, b"2").unwrap();
+ fn a_file_no_record_names_is_never_read() {
+ let (_scratch, db, _) = a_library_with_a_note();
+ std::fs::write(attachments_of(&db).join("stray"), b"stray").unwrap();
- assert_ne!(one, two);
- assert_eq!(one.file_name().unwrap(), "capture.png");
- assert_eq!(std::fs::read(one).unwrap(), b"1");
- assert_eq!(std::fs::read(two).unwrap(), b"2");
+ for id in ["stray", "missing"] {
+ assert!(matches!(read_outside_lock(&db, id), Err(StorageError::AttachmentNotFound(_))));
+ }
}
+ /// One byte past the limit is enough to refuse: a growing file cannot outrun the read.
#[test]
- fn an_attachment_nobody_recorded_is_not_read() {
- let (_scratch, db, _) = a_library_with_a_note();
+ fn a_source_is_read_one_byte_past_the_limit_at_most() {
+ let scratch = tempfile::tempdir().unwrap();
+ let source = scratch.path().join("big.bin");
+ let too_long = usize::try_from(model::MAX_BYTES).unwrap() + 10;
+ std::fs::write(&source, vec![0u8; too_long]).unwrap();
- let refused = read_plain(&mut lock(&db).unwrap(), "../vault");
+ let read = read_within_limit(&source.to_string_lossy()).unwrap();
- assert!(matches!(refused, Err(StorageError::AttachmentNotFound(_))));
+ assert_eq!(read.len() as u64, model::MAX_BYTES + 1);
+ let missing = scratch.path().join("missing.bin");
+ assert!(matches!(read_within_limit(&missing.to_string_lossy()), Err(StorageError::File(_))));
}
+ /// Two copies of one name do not overwrite each other.
#[test]
- fn the_sweep_removes_the_files_no_record_claims_and_only_those() {
+ fn an_opened_copy_is_written_in_the_clear_in_a_folder_of_its_own() {
let (_scratch, db, note_id) = a_library_with_a_note();
- let directory = attachments_of(&db);
- let kept = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap();
- std::fs::write(directory.join("orphan.png"), b"left behind").unwrap();
+ let copies = tempfile::tempdir().unwrap();
+ let first = store_new(note_id.clone(), "capture.png".to_string(), b"one", &db).unwrap();
+ let second = store_new(note_id, "capture.png".to_string(), b"two", &db).unwrap();
- assert_eq!(sweep_orphan_files(&db).unwrap(), 1);
+ let one = write_plaintext_copy(copies.path(), &first, b"one").unwrap();
+ let two = write_plaintext_copy(copies.path(), &second, b"two").unwrap();
- assert!(directory.join(kept.stored_name()).exists());
- assert!(!directory.join("orphan.png").exists());
+ assert_eq!(one, copies.path().join(first.opened_copy()));
+ assert_ne!(one, two);
+ assert_eq!(std::fs::read(&one).unwrap(), b"one");
+ assert_eq!(std::fs::read(&two).unwrap(), b"two");
}
+ /// That is what "save as" means.
#[test]
- fn a_file_within_the_limit_is_read_whole() {
+ fn a_saved_attachment_is_written_in_the_clear_where_asked() {
let scratch = tempfile::tempdir().unwrap();
- let directory = scratch.path().to_path_buf();
- let source = directory.join("capture.png");
- std::fs::write(&source, vec![7u8; 2048]).unwrap();
+ let path = scratch.path().join("saved.txt");
- let bytes = read_within_limit(&source.to_string_lossy()).unwrap();
+ write_plain(&path.to_string_lossy(), b"plain").unwrap();
- assert_eq!(bytes, vec![7u8; 2048]);
+ assert_eq!(std::fs::read(&path).unwrap(), b"plain");
}
- /// A file that grew past the limit is still refused, and no more than one byte past it is
- /// ever held.
+ /// An interrupted copy or a purge cut short leaves one; a file already gone is no error.
#[test]
- fn a_file_over_the_limit_is_read_one_byte_past_it_and_refused() {
- let scratch = tempfile::tempdir().unwrap();
- let directory = scratch.path().to_path_buf();
- let source = directory.join("huge.bin");
- let limit = usize::try_from(model::MAX_BYTES).unwrap();
- std::fs::write(&source, vec![0u8; limit + 10]).unwrap();
-
- let bytes = read_within_limit(&source.to_string_lossy()).unwrap();
-
- assert_eq!(bytes.len(), limit + 1);
- assert!(matches!(
- model::validate_size(bytes.len() as u64, "huge.bin"),
- Err(StorageError::TooLarge { .. })
- ));
- }
+ fn the_sweep_removes_the_files_no_record_claims_and_keeps_the_others() {
+ let (_scratch, db, note_id) = a_library_with_a_note();
+ let directory = attachments_of(&db);
+ let kept = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap();
+ std::fs::write(directory.join("orphan.png"), b"orphan").unwrap();
- #[test]
- fn a_missing_source_is_reported_rather_than_panicking() {
- let error = read_within_limit("no-such-file.png").unwrap_err();
+ let swept = sweep_orphan_files(&db).unwrap();
- assert!(matches!(error, StorageError::File(_)), "{error}");
+ assert_eq!(swept, 1);
+ assert!(!directory.join("orphan.png").exists());
+ assert!(directory.join(kept.stored_name()).exists());
+ remove_files(&directory, &["orphan.png".to_string()]);
}
}
diff --git a/crates/engine/src/attachments/model.rs b/crates/engine/src/attachments/model.rs
index 62ea23f90..635af260c 100644
--- a/crates/engine/src/attachments/model.rs
+++ b/crates/engine/src/attachments/model.rs
@@ -54,21 +54,13 @@ fn copy_name(id: &str, file_name: &str) -> String {
}
})
.collect();
- let mut name = replaced
- .trim_end_matches(['.', ' '])
- .trim_start()
- .to_string();
+ let mut name = replaced.trim_end_matches(['.', ' ']).trim_start().to_string();
if name.chars().count() > COPY_NAME_CHARS {
let extension = extension_of(&name).map(|extension| format!(".{extension}"));
let kept = COPY_NAME_CHARS - extension.as_ref().map_or(0, String::len);
name = name.chars().take(kept).collect::() + extension.as_deref().unwrap_or("");
}
- let stem = name
- .split('.')
- .next()
- .unwrap_or_default()
- .trim_end()
- .to_ascii_uppercase();
+ let stem = name.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
&& stem.len() == 4
@@ -100,10 +92,7 @@ fn contained(id: &str) -> String {
/// Lowercase and alphanumeric: separators, `..` or colons would escape the directory.
fn extension_of(file_name: &str) -> Option {
let candidate = file_name.rsplit_once('.')?.1;
- if candidate.is_empty()
- || candidate.len() > 8
- || !candidate.chars().all(|c| c.is_ascii_alphanumeric())
- {
+ if candidate.is_empty() || candidate.len() > 8 || !candidate.chars().all(|c| c.is_ascii_alphanumeric()) {
return None;
}
@@ -141,12 +130,7 @@ pub fn mime_of(file_name: &str) -> String {
/// Stripped of any path: an import must not show `../../secrets/key.pem` as a note's own.
pub fn display_name(path: &str) -> Result {
- let trimmed = path
- .rsplit(['/', '\\'])
- .next()
- .unwrap_or_default()
- .trim()
- .to_string();
+ let trimmed = path.rsplit(['/', '\\']).next().unwrap_or_default().trim().to_string();
if trimmed.is_empty() || trimmed == "." || trimmed == ".." {
return Err(ValidationError::new("fileName", "unreadable file name"));
@@ -159,24 +143,14 @@ pub fn display_name(path: &str) -> Result {
/// `mime_of` answers `application/octet-stream` and skips the preview.
pub fn png_name(base: &str) -> String {
let trimmed = base.trim();
- let stem = if trimmed.is_empty() {
- "capture"
- } else {
- trimmed
- };
+ let stem = if trimmed.is_empty() { "capture" } else { trimmed };
- if stem.to_ascii_lowercase().ends_with(".png") {
- stem.to_string()
- } else {
- format!("{stem}.png")
- }
+ if stem.to_ascii_lowercase().ends_with(".png") { stem.to_string() } else { format!("{stem}.png") }
}
/// Encodes raw RGBA — what the system clipboard hands over — into PNG.
pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, StorageError> {
- let expected = (width as usize)
- .saturating_mul(height as usize)
- .saturating_mul(4);
+ let expected = (width as usize).saturating_mul(height as usize).saturating_mul(4);
if width == 0 || height == 0 || rgba.len() < expected {
return Err(StorageError::File(format!(
"clipboard image of {width}×{height} carries {} bytes, {expected} expected",
@@ -190,9 +164,7 @@ pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, Stora
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().context("png header")?;
- writer
- .write_image_data(&rgba[..expected])
- .context("png data")?;
+ writer.write_image_data(&rgba[..expected]).context("png data")?;
}
Ok(png)
@@ -205,10 +177,7 @@ const _: () = assert!(MAX_BYTES == MAX_MEGABYTES as u64 * 1024 * 1024);
pub fn validate_size(byte_size: u64, name: &str) -> Result {
if byte_size > MAX_BYTES {
- return Err(StorageError::TooLarge {
- name: name.to_string(),
- limit_mb: MAX_MEGABYTES,
- });
+ return Err(StorageError::TooLarge { name: name.to_string(), limit_mb: MAX_MEGABYTES });
}
Ok(saturating_u32(byte_size))
@@ -216,63 +185,39 @@ pub fn validate_size(byte_size: u64, name: &str) -> Result {
#[cfg(test)]
mod tests {
- use std::path::Path;
-
use super::*;
- #[test]
- fn the_stored_name_comes_from_the_identifier_not_from_the_user() {
- assert_eq!(stored_name("a-1", "capture.png"), "a-1.png");
- assert_eq!(stored_name("a-2", "capture.png"), "a-2.png");
- }
-
- fn opened(id: &str, file_name: &str) -> PathBuf {
+ fn attachment(id: &str, file_name: &str) -> Attachment {
Attachment {
id: id.to_string(),
- note_id: "n".to_string(),
+ note_id: "n-1".to_string(),
file_name: file_name.to_string(),
mime_type: mime_of(file_name),
- byte_size: 1,
- created_at: Utc::now(),
+ byte_size: 3,
+ created_at: DateTime::::UNIX_EPOCH,
}
- .opened_copy()
}
#[test]
- fn an_opened_copy_keeps_its_own_name_in_a_folder_of_its_own() {
- assert_eq!(
- opened("7d44d90f", "image-test.png"),
- Path::new("7d44d90f").join("image-test.png")
- );
- assert_eq!(opened("../x", "a:b?.png"), Path::new("x").join("a_b_.png"));
- assert_eq!(opened("a", "notes. "), Path::new("a").join("notes"));
- }
-
- #[test]
- fn a_name_windows_will_not_write_falls_back_on_the_stored_one() {
- assert_eq!(opened("a", "CON.txt"), Path::new("a").join("a.txt"));
- assert_eq!(opened("a", "lpt1"), Path::new("a").join("a"));
- assert_eq!(opened("a", "..."), Path::new("a").join("a"));
- let long = format!("{}.png", "x".repeat(300));
- let cut = opened("a", &long);
- let name = cut.file_name().unwrap().to_string_lossy();
- assert_eq!(name.chars().count(), 100);
- assert!(name.ends_with(".png"));
- }
-
- #[test]
- fn a_hostile_extension_is_dropped_rather_than_written() {
- for name in ["x.../../evil", "x.p g", "x.", "x.verylongextension"] {
- assert_eq!(stored_name("a-1", name), "a-1");
+ fn a_stored_name_is_the_id_and_the_extension_lowercased() {
+ let cases = [
+ ("a-1", "Capture.PNG", "a-1.png"),
+ ("a-1", "archive.tar.gz", "a-1.gz"),
+ ("a-1", "notes", "a-1"),
+ ("3f2504e0-4f89-41d3-9a0c-0305e82c3301", "x.png", "3f2504e0-4f89-41d3-9a0c-0305e82c3301.png"),
+ ];
+
+ for (id, file_name, stored) in cases {
+ assert_eq!(stored_name(id, file_name), stored, "{file_name}");
}
}
/// An import decides the id: a record claiming `../vault` must not reach the key file.
#[test]
- fn a_hostile_identifier_cannot_leave_the_directory() {
+ fn a_stored_name_is_one_plain_component_whatever_id_it_is_given() {
use std::path::{Component, Path};
- for id in [
+ let hostile = [
"../vault",
"..\\vault",
"../../../../Users/me/Startup/run",
@@ -282,81 +227,160 @@ mod tests {
".",
"",
"a/b",
- ] {
+ ];
+
+ for id in hostile {
for file_name in ["capture.png", "no-extension"] {
let name = stored_name(id, file_name);
- let components: Vec> = Path::new(&name).components().collect();
-
- assert_eq!(
- components.len(),
- 1,
- "{id:?} + {file_name:?} gave {name:?}, which is not one component"
- );
+ let parts: Vec> = Path::new(&name).components().collect();
assert!(
- matches!(components[0], Component::Normal(_)),
+ matches!(parts.as_slice(), [Component::Normal(_)]),
"{id:?} + {file_name:?} gave {name:?}"
);
}
}
+ assert_eq!(stored_name("../../etc", "x.png"), "etc.png");
+ assert_eq!(stored_name("", "x.png"), "attachment.png");
+ }
+
+ #[test]
+ fn a_stored_name_drops_an_extension_that_is_not_plain_letters_and_digits() {
+ let cases = [
+ ("a-1", "x.p/ng", "a-1"),
+ ("a-1", "x.ph:p", "a-1"),
+ ("a-1", "x.abcdefghi", "a-1"),
+ ("a-1", "x.", "a-1"),
+ ];
+
+ for (id, file_name, stored) in cases {
+ assert_eq!(stored_name(id, file_name), stored, "{id:?} {file_name:?}");
+ }
}
+ /// An unknown type stays attachable; it is only not previewed.
#[test]
- fn the_identifiers_the_application_generates_pass_through_untouched() {
- let id = "3f2504e0-4f89-41d3-9a0c-0305e82c3301";
+ fn a_type_is_read_from_the_extension() {
+ let cases = [
+ ("a.PNG", "image/png"),
+ ("a.jpeg", "image/jpeg"),
+ ("a.jpg", "image/jpeg"),
+ ("a.svg", "image/svg+xml"),
+ ("a.pdf", "application/pdf"),
+ ("a.log", "text/plain"),
+ ("a.csv", "text/csv"),
+ ("a.exe", "application/octet-stream"),
+ ("a", "application/octet-stream"),
+ ];
+
+ for (file_name, mime) in cases {
+ assert_eq!(mime_of(file_name), mime, "{file_name}");
+ }
+ }
- assert_eq!(stored_name(id, "capture.png"), format!("{id}.png"));
+ #[test]
+ fn a_displayed_name_is_the_file_s_own_without_any_path() {
+ let cases = [
+ ("../../secrets/key.pem", "key.pem"),
+ ("C:\\Users\\me\\report.pdf", "report.pdf"),
+ (" spaced.txt ", "spaced.txt"),
+ ];
+
+ for (path, shown) in cases {
+ assert_eq!(display_name(path), Ok(shown.to_string()), "{path}");
+ }
+ for unreadable in ["", "folder/", ".", "..", " "] {
+ assert_eq!(display_name(unreadable).unwrap_err().field, "fileName", "{unreadable:?}");
+ }
}
+ /// Without its extension a pasted image would not be previewed.
#[test]
- fn the_extension_decides_the_type_case_insensitively() {
- assert_eq!(mime_of("Capture.PNG"), "image/png");
- assert_eq!(mime_of("dump.unknown"), "application/octet-stream");
+ fn a_pasted_image_is_named_as_a_png() {
+ let cases = [
+ ("", "capture.png"),
+ (" shot ", "shot.png"),
+ ("Screen.PNG", "Screen.PNG"),
+ ("photo.jpg", "photo.jpg.png"),
+ ];
+
+ for (base, named) in cases {
+ assert_eq!(png_name(base), named, "{base:?}");
+ }
}
+ /// What the clipboard hands over is raw RGBA; bytes past the image are not read.
#[test]
- fn only_the_last_segment_of_a_path_is_displayed() {
- assert_eq!(
- display_name(r"C:\Users\me\capture.png").unwrap(),
- "capture.png"
- );
- assert_eq!(display_name("/home/me/capture.png").unwrap(), "capture.png");
+ fn raw_pixels_are_encoded_as_a_png() {
+ let red = [255, 0, 0, 255];
+
+ let png = encode_png(1, 1, &red).unwrap();
+
+ assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
+ assert_eq!(encode_png(1, 1, &[red, red].concat()).unwrap(), png);
}
#[test]
- fn a_path_with_no_file_name_is_refused_with_its_field() {
- assert_eq!(display_name(" ").unwrap_err().field, "fileName");
- assert_eq!(display_name("/tmp/..").unwrap_err().field, "fileName");
+ fn an_image_without_pixels_or_short_of_them_is_refused() {
+ for (width, height, bytes) in [(0, 1, 4), (1, 0, 4), (2, 2, 15)] {
+ let rgba = vec![0; bytes];
+
+ assert!(
+ matches!(encode_png(width, height, &rgba), Err(StorageError::File(_))),
+ "{width}×{height} with {bytes} bytes"
+ );
+ }
}
#[test]
- fn a_file_over_the_limit_is_refused_before_being_copied() {
- assert!(validate_size(MAX_BYTES, "capture.png").is_ok());
+ fn a_file_is_attached_up_to_ten_megabytes_and_refused_past_them() {
+ assert_eq!(validate_size(MAX_BYTES, "big.bin").unwrap(), 10 * 1024 * 1024);
assert!(matches!(
- validate_size(MAX_BYTES + 1, "capture.mov"),
- Err(StorageError::TooLarge { name, limit_mb: 10 }) if name == "capture.mov"
+ validate_size(MAX_BYTES + 1, "big.bin"),
+ Err(StorageError::TooLarge { name, limit_mb: 10 }) if name == "big.bin"
));
}
+ /// Two copies of one name must not meet: each sits in a folder of its own.
#[test]
- fn a_pasted_image_always_ends_up_with_its_extension() {
- assert_eq!(png_name("capture-2026"), "capture-2026.png");
- assert_eq!(png_name("capture.PNG"), "capture.PNG");
- assert_eq!(png_name(" "), "capture.png");
+ fn an_opened_copy_sits_in_a_folder_of_its_own_under_its_own_name() {
+ assert_eq!(attachment("a-1", "Rapport.pdf").opened_copy(), PathBuf::from("a-1").join("Rapport.pdf"));
+ assert_eq!(attachment("../a-1", "x.pdf").opened_copy(), PathBuf::from("a-1").join("x.pdf"));
}
+ /// What Windows forbids is replaced; a device name or nothing left falls back on the
+ /// stored name.
#[test]
- fn raw_clipboard_pixels_become_a_readable_png() {
- let rgba = vec![255u8; 2 * 2 * 4];
-
- let png = encode_png(2, 2, &rgba).unwrap();
-
- assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
- assert_eq!(mime_of(&png_name("capture")), "image/png");
+ fn an_opened_copy_is_named_as_windows_accepts_a_file() {
+ let cases = [
+ ("a:c?.txt", "a_b__c_.txt"),
+ ("tab\tname.txt", "tab_name.txt"),
+ ("name. . ", "name"),
+ (" lead.txt", "lead.txt"),
+ ("CON.txt", "a-1.txt"),
+ ("nul", "a-1"),
+ ("com1.log", "a-1.log"),
+ ("LPT9", "a-1"),
+ ("COM10.txt", "COM10.txt"),
+ ("console.txt", "console.txt"),
+ ("...", "a-1"),
+ ];
+
+ for (file_name, copy) in cases {
+ let opened = attachment("a-1", file_name).opened_copy();
+ assert_eq!(opened, PathBuf::from("a-1").join(copy), "{file_name:?}");
+ }
}
+ /// The profile's path comes first: a long name is cut, its extension kept.
#[test]
- fn a_truncated_clipboard_image_is_refused_rather_than_written() {
- assert!(encode_png(2, 2, &[0u8; 4]).is_err());
- assert!(encode_png(0, 0, &[]).is_err());
+ fn a_long_opened_copy_name_is_cut_before_its_extension() {
+ let long = "a".repeat(150);
+
+ let with_extension = attachment("a-1", &format!("{long}.pdf")).opened_copy();
+ let without = attachment("a-1", &long).opened_copy();
+
+ let name = |path: &std::path::Path| path.file_name().unwrap().to_string_lossy().to_string();
+ assert_eq!(name(&with_extension), format!("{}.pdf", "a".repeat(96)));
+ assert_eq!(name(&without), "a".repeat(100));
}
}
diff --git a/crates/engine/src/attachments/sealed.rs b/crates/engine/src/attachments/sealed.rs
index 645334a67..bb7619857 100644
--- a/crates/engine/src/attachments/sealed.rs
+++ b/crates/engine/src/attachments/sealed.rs
@@ -38,10 +38,7 @@ pub fn sweep_plaintext(paths: &Paths) {
if let Err(error) = std::fs::remove_dir_all(&directory)
&& error.kind() != std::io::ErrorKind::NotFound
{
- log::warn!(
- "Decrypted copies not swept from {}: {error}",
- directory.display()
- );
+ log::warn!("Decrypted copies not swept from {}: {error}", directory.display());
}
}
@@ -58,14 +55,9 @@ mod tests {
#[test]
fn the_decrypted_copies_live_under_the_profile_and_go_in_one_sweep() {
let profile = tempfile::tempdir().unwrap();
- let paths = Paths {
- profile: profile.path().to_path_buf(),
- };
+ let paths = Paths { profile: profile.path().to_path_buf() };
let directory = plaintext_directory(&paths);
- assert_eq!(
- directory,
- profile.path().join(crate::layout::PLAINTEXT_COPIES)
- );
+ assert_eq!(directory, profile.path().join(crate::layout::PLAINTEXT_COPIES));
sweep_plaintext(&paths);
std::fs::create_dir_all(&directory).unwrap();
@@ -75,17 +67,6 @@ mod tests {
assert!(!directory.exists());
}
- /// The property the name has to have, asserted without waiting for a coincidence.
- #[test]
- fn two_scratch_directories_are_never_the_same_one() {
- let scratch = tempfile::tempdir().unwrap();
- let first = scratch.path().to_path_buf();
- let scratch = tempfile::tempdir().unwrap();
- let second = scratch.path().to_path_buf();
-
- assert_ne!(first, second);
- }
-
#[test]
fn a_sealed_file_reads_back_byte_for_byte() {
let scratch = tempfile::tempdir().unwrap();
@@ -132,8 +113,7 @@ mod tests {
let target = directory.join("capture.png");
write_sealed(&vault(), &target, b"bytes").unwrap();
- let other =
- Vault::derive("another passphrase", b"0123456789abcdef", Cost::FOR_TESTS).unwrap();
+ let other = Vault::derive("another passphrase", b"0123456789abcdef", Cost::FOR_TESTS).unwrap();
assert!(read_sealed(&other, &target).is_err());
}
diff --git a/crates/engine/src/attachments/store.rs b/crates/engine/src/attachments/store.rs
index 87c1fa8a6..4d5210cbf 100644
--- a/crates/engine/src/attachments/store.rs
+++ b/crates/engine/src/attachments/store.rs
@@ -26,10 +26,8 @@ struct AttachmentRow {
/// `{id}.{extension}`, so the type is already public. Sealing it would be theatre.
impl AttachmentRow {
fn open(row: Self, vault: &Vault) -> Result {
- let created_at = iso8601::parse(&row.created_at).map_err(|_| StorageError::CorruptRow {
- id: row.id.clone(),
- field: "createdAt",
- })?;
+ let created_at = iso8601::parse(&row.created_at)
+ .map_err(|_| StorageError::CorruptRow { id: row.id.clone(), field: "createdAt" })?;
Ok(Attachment {
byte_size: saturating_u32(row.byte_size),
@@ -116,10 +114,7 @@ pub fn delete(connection: &mut SqliteConnection, id: &str) -> Result<(), Storage
/// The records an export carries. The bytes are not here: the caller reads them from the
/// attachments directory by [`model::stored_name`].
-pub fn for_notes(
- connection: &mut Library,
- note_ids: &[String],
-) -> Result, StorageError> {
+pub fn for_notes(connection: &mut Library, note_ids: &[String]) -> Result, StorageError> {
if note_ids.is_empty() {
return Ok(Vec::new());
}
@@ -137,10 +132,7 @@ pub fn for_notes(
}
/// ⚠️ Collected before a purge: the cascade takes the records, never the files.
-pub fn stored_names_of(
- connection: &mut Library,
- note_ids: &[String],
-) -> Result, StorageError> {
+pub fn stored_names_of(connection: &mut Library, note_ids: &[String]) -> Result, StorageError> {
if note_ids.is_empty() {
return Ok(Vec::new());
}
@@ -182,89 +174,189 @@ pub fn counts(connection: &mut SqliteConnection) -> Result,
#[cfg(test)]
mod tests {
- use chrono::Utc;
+ use chrono::{DateTime, Utc};
use super::*;
use crate::db::open_in_memory;
- use crate::notes::kind::NoteKind;
- use crate::notes::language::Language;
- use crate::notes::model::{NoteDraft, NoteLifecycle};
- use crate::notes::priority::Priority;
-
- fn note(connection: &mut Library) -> String {
- let space = crate::spaces::store::create(connection, "Personal").unwrap();
- crate::notes::store::create(
- connection,
- NoteDraft {
- space_id: space.id,
- folder_id: None,
- title: "T".to_string(),
- language: Language::Txt,
- content: String::new(),
- source: String::new(),
- tags: Vec::new(),
- pinned: false,
- lifecycle: NoteLifecycle::Permanent,
- kind: NoteKind::Snippet,
- priority: Priority::None,
- items: Vec::new(),
- },
- Utc::now(),
- )
- .unwrap()
- .id
+ use crate::notes::fixtures::at;
+
+ fn note_in(library: &mut Library) -> String {
+ let space = crate::spaces::store::create(library, &uuid::Uuid::new_v4().to_string())
+ .unwrap()
+ .id;
+ let draft = crate::notes::model::NoteDraft {
+ space_id: space,
+ folder_id: None,
+ title: "T".to_string(),
+ language: crate::notes::language::Language::Txt,
+ content: String::new(),
+ source: String::new(),
+ tags: Vec::new(),
+ pinned: false,
+ lifecycle: crate::notes::model::NoteLifecycle::Permanent,
+ kind: crate::notes::kind::NoteKind::Snippet,
+ priority: crate::notes::priority::Priority::None,
+ items: Vec::new(),
+ };
+ crate::notes::store::create(library, draft, at("2026-07-25T09:00:00.000Z"))
+ .unwrap()
+ .id
}
- /// The tests hold a library; `create` takes the pair, as an import does.
- fn create_here(connection: &mut Library, attachment: &Attachment) -> Result<(), StorageError> {
- let (db, vault) = connection.split();
- create(db, vault, attachment)
- }
-
- fn sample(id: &str, note_id: &str) -> Attachment {
+ fn attachment(id: &str, note_id: &str, file_name: &str, created_at: DateTime) -> Attachment {
Attachment {
id: id.to_string(),
note_id: note_id.to_string(),
- file_name: "capture.png".to_string(),
- mime_type: "image/png".to_string(),
- byte_size: 12,
- created_at: Utc::now(),
+ file_name: file_name.to_string(),
+ mime_type: model::mime_of(file_name),
+ byte_size: 3,
+ created_at,
+ }
+ }
+
+ fn record(library: &mut Library, attachment: &Attachment) {
+ let (db, vault) = library.split();
+ create(db, vault, attachment).unwrap();
+ }
+
+ fn ids(attachments: &[Attachment]) -> Vec<&str> {
+ attachments.iter().map(|attachment| attachment.id.as_str()).collect()
+ }
+
+ /// The foreign key would refuse it too, in words the screen cannot translate.
+ #[test]
+ fn an_attachment_is_recorded_only_for_a_live_note() {
+ let mut library = open_in_memory().unwrap();
+ let trashed = note_in(&mut library);
+ crate::notes::fixtures::trash(&mut library, &trashed, Utc::now());
+ let (db, vault) = library.split();
+
+ for note_id in ["missing", trashed.as_str()] {
+ let refused = create(db, vault, &attachment("a-1", note_id, "x.png", Utc::now()));
+
+ assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == note_id), "{note_id}");
}
}
#[test]
- fn an_attachment_is_read_back_whole() {
- let mut connection = open_in_memory().unwrap();
- let note_id = note(&mut connection);
+ fn a_note_s_attachments_are_listed_in_the_order_they_came() {
+ let mut library = open_in_memory().unwrap();
+ let note = note_in(&mut library);
+ let other = note_in(&mut library);
+ record(&mut library, &attachment("late", ¬e, "b.png", at("2026-07-25T11:00:00.000Z")));
+ record(&mut library, &attachment("early", ¬e, "a.png", at("2026-07-25T10:00:00.000Z")));
+ record(&mut library, &attachment("else", &other, "c.png", at("2026-07-25T10:00:00.000Z")));
+
+ assert_eq!(ids(&list(&mut library, ¬e).unwrap()), ["early", "late"]);
+ }
+
+ /// The type stays in the clear: the file on disk already says it by its extension.
+ #[test]
+ fn a_record_s_name_is_sealed_and_read_back_whole() {
+ let mut library = open_in_memory().unwrap();
+ let note = note_in(&mut library);
+ let made = attachment("a-1", ¬e, "secret plan.png", at("2026-07-25T10:00:00.000Z"));
+ record(&mut library, &made);
+
+ let (name, mime): (String, String) = attachments::table
+ .select((attachments::file_name, attachments::mime_type))
+ .first(library.db())
+ .unwrap();
+ let found = find(&mut library, "a-1").unwrap().unwrap();
+
+ assert!(!name.contains("secret"));
+ assert_eq!(mime, "image/png");
+ assert_eq!(
+ (found.file_name, found.byte_size, found.created_at),
+ (made.file_name, 3, made.created_at)
+ );
+ assert!(find(&mut library, "missing").unwrap().is_none());
+ }
+
+ #[test]
+ fn an_unreadable_instant_is_answered_as_a_corrupt_row() {
+ let mut library = open_in_memory().unwrap();
+ let note = note_in(&mut library);
+ record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now()));
+ diesel::update(attachments::table.find("a-1"))
+ .set(attachments::created_at.eq("yesterday"))
+ .execute(library.db())
+ .unwrap();
+
+ assert!(matches!(
+ find(&mut library, "a-1"),
+ Err(StorageError::CorruptRow { id, field: "createdAt" }) if id == "a-1"
+ ));
+ }
- create_here(&mut connection, &sample("a-1", ¬e_id)).unwrap();
- let listed = list(&mut connection, ¬e_id).unwrap();
+ #[test]
+ fn a_record_is_deleted_once_and_a_second_time_is_not_found() {
+ let mut library = open_in_memory().unwrap();
+ let note = note_in(&mut library);
+ record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now()));
+
+ delete(library.db(), "a-1").unwrap();
+
+ assert!(list(&mut library, ¬e).unwrap().is_empty());
+ assert!(matches!(
+ delete(library.db(), "a-1"),
+ Err(StorageError::AttachmentNotFound(id)) if id == "a-1"
+ ));
+ }
- assert_eq!(listed.len(), 1);
- assert_eq!(listed[0].file_name, "capture.png");
- assert_eq!(listed[0].byte_size, 12);
+ /// What an export carries, and the names its files are read under.
+ #[test]
+ fn the_records_of_some_notes_come_with_the_names_their_files_are_stored_under() {
+ let mut library = open_in_memory().unwrap();
+ let first = note_in(&mut library);
+ let second = note_in(&mut library);
+ let left = note_in(&mut library);
+ record(&mut library, &attachment("a-1", &first, "Shot.PNG", at("2026-07-25T10:00:00.000Z")));
+ record(&mut library, &attachment("a-2", &second, "notes", at("2026-07-25T11:00:00.000Z")));
+ record(&mut library, &attachment("a-3", &left, "x.pdf", at("2026-07-25T12:00:00.000Z")));
+ let chosen = [first, second];
+
+ let records = for_notes(&mut library, &chosen).unwrap();
+ let mut names = stored_names_of(&mut library, &chosen).unwrap();
+ names.sort();
+ let mut every = all_stored_names(&mut library).unwrap();
+ every.sort();
+
+ assert_eq!(ids(&records), ["a-1", "a-2"]);
+ assert_eq!(names, ["a-1.png", "a-2"]);
+ assert_eq!(every, ["a-1.png", "a-2", "a-3.pdf"]);
+ assert!(for_notes(&mut library, &[]).unwrap().is_empty());
+ assert!(stored_names_of(&mut library, &[]).unwrap().is_empty());
}
+ /// The cascade takes the records, never the files: their names are read before a purge.
#[test]
- fn attaching_to_an_unknown_note_is_refused() {
- let mut connection = open_in_memory().unwrap();
+ fn a_purged_note_s_records_go_with_it() {
+ let mut library = open_in_memory().unwrap();
+ let note = note_in(&mut library);
+ record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now()));
+ let names = stored_names_of(&mut library, std::slice::from_ref(¬e)).unwrap();
- let error = create_here(&mut connection, &sample("a-1", "ghost")).unwrap_err();
+ crate::notes::fixtures::trash(&mut library, ¬e, Utc::now());
+ crate::notes::store::trash::purge(&mut library, std::slice::from_ref(¬e)).unwrap();
- assert!(matches!(error, StorageError::NoteNotFound(_)));
+ assert_eq!(names, ["a-1.png"]);
+ assert!(list(&mut library, ¬e).unwrap().is_empty());
}
#[test]
- fn purging_a_note_takes_its_attachment_rows_with_it() {
- let mut connection = open_in_memory().unwrap();
- let note_id = note(&mut connection);
- create_here(&mut connection, &sample("a-1", ¬e_id)).unwrap();
+ fn each_note_is_counted_its_attachments_in_one_read() {
+ let mut library = open_in_memory().unwrap();
+ let note = note_in(&mut library);
+ let other = note_in(&mut library);
+ let bare = note_in(&mut library);
+ for (id, owner) in [("a-1", ¬e), ("a-2", ¬e), ("a-3", &other)] {
+ record(&mut library, &attachment(id, owner, "x.png", Utc::now()));
+ }
- let files = stored_names_of(&mut connection, std::slice::from_ref(¬e_id)).unwrap();
- crate::notes::store::trash::trash(&mut connection, ¬e_id, Utc::now()).unwrap();
- crate::notes::store::trash::purge(&mut connection, std::slice::from_ref(¬e_id)).unwrap();
+ let counted = counts(library.db()).unwrap();
- assert_eq!(files, ["a-1.png"]);
- assert!(list(&mut connection, ¬e_id).unwrap().is_empty());
+ assert_eq!(counted, HashMap::from([(note, 2), (other, 1)]));
+ assert!(!counted.contains_key(&bare));
}
}
diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs
index b5211a1f4..9bf299018 100644
--- a/crates/engine/src/backup.rs
+++ b/crates/engine/src/backup.rs
@@ -7,7 +7,6 @@
pub mod copies;
use std::path::PathBuf;
-use std::sync::Mutex;
use chrono::{DateTime, Utc};
@@ -16,23 +15,6 @@ use crate::db::{Db, lock};
use crate::error::{AppError, StorageError};
use copies::{Backup, list, replace, rotate};
-/// Where the library the last restore replaced went, kept for the page the restore reloads:
-/// nothing in the page survives the reload on every platform.
-#[derive(Default)]
-pub struct Restored(Mutex