SPB Git

Repository Public

InkTests.swift 14.5 KB 243 lines swift

1// SP Notes Core2// File: Tests/SPNotesDocumentTests/InkTests.swift3// Description: The spn-ink-1 model (lossless round trip, colours, simplification, geometry) and the CoreGraphics4//              renderer (pixels, PNG, determinism).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreGraphics10import ImageIO11import Testing12@testable import SPNotesDocument1314@Suite struct InkTests {15    static let sample = """16    {"format":"spn-ink-1","width":400,"height":300.5,"future":{"layers":[1,2.5,"a"]},"strokes":[17      {"tool":"pen","color":"#112233ff","width":4,"points":[[10,10,0.5],[20,12,0.75],[30.25,40,1]],"seed":42,"meta":null},18      {"tool":"marker","color":"#FF0000","width":8.5,"points":[[0,0],[100,100]]},19      {"tool":"spray","color":"not-a-colour","width":2,"points":[]}20    ]}21    """2223    @Test func roundTripIsLossless() throws {24        let source = try JSONValue(jsonString: Self.sample)25        let doc = try InkDocument(data: Data(Self.sample.utf8))26        let again = try JSONValue(data: doc.jsonData())27        #expect(again.semanticallyEquals(source))28        #expect(try InkDocument(data: doc.jsonData()) == doc)29        let reread = try InkDocument(data: doc.jsonData())30        #expect(doc.jsonData() == reread.jsonData())31        // Codable goes through the same representation.32        let coded = try JSONDecoder().decode(InkDocument.self, from: JSONEncoder().encode(doc))33        #expect(coded == doc)34    }3536    @Test func typedAccess() throws {37        var doc = try InkDocument(data: Data(Self.sample.utf8))38        #expect(doc.width == 400 && doc.height == 300.5 && doc.strokes.count == 3)39        #expect(doc["future"]?["layers"]?.arrayValue?.count == 3)40        let pen = doc.strokes[0]41        #expect(pen.tool == .pen && pen.color == InkColor(red: UInt8(0x11), green: 0x22, blue: 0x33) && pen.width == 4)42        #expect(pen.points == [InkPoint(x: 10, y: 10, pressure: 0.5), InkPoint(x: 20, y: 12, pressure: 0.75), InkPoint(x: 30.25, y: 40)])43        #expect(pen["seed"] == 42 && pen["meta"] == .null)44        #expect(doc.strokes[1].color == InkColor(red: UInt8(255), green: 0, blue: 0, alpha: 255))45        #expect(doc.strokes[1].points[1].pressure == 1)46        #expect(doc.strokes[2].tool == InkTool(rawValue: "spray") && !doc.strokes[2].tool.isKnown)47        #expect(doc.strokes[2].color == .black)48        #expect(doc.pointCount == 5 && !doc.isEmpty)4950        doc.strokes[1].color = InkColor(red: UInt8(1), green: 2, blue: 3, alpha: 4)51        doc.strokes[1].points[0].pressure = 0.2552        doc.width = 51253        let out = try JSONValue(data: doc.jsonData())54        #expect(out["width"] == 512)55        #expect(out["strokes"]?.arrayValue?[1]["color"] == "#01020304")56        #expect(out["strokes"]?.arrayValue?[1]["points"] == [[0, 0, 0.25], [100, 100]])57        #expect(out["strokes"]?.arrayValue?[2]["color"] == "not-a-colour")58    }5960    @Test func builtDocumentHasTheSpecShape() throws {61        let doc = InkDocument(width: 100, height: 50, strokes: [62            InkStroke(tool: .highlighter, color: InkColor(red: UInt8(255), green: 255, blue: 0, alpha: 128), width: 12,63                      points: [InkPoint(x: 1, y: 2, pressure: 0.5), InkPoint(x: 3.5, y: 4)]),64        ])65        #expect(String(decoding: doc.jsonData(), as: UTF8.self) ==66            ##"{"format":"spn-ink-1","height":50,"strokes":[{"color":"#ffff0080","points":[[1,2,0.5],[3.5,4,1]],"tool":"highlighter","width":12}],"width":100}"##)67    }6869    @Test func rejectsWhatIsNotInk() {70        #expect(throws: InkError.unsupportedFormat("spn-ink-2")) { try InkDocument(data: Data(#"{"format":"spn-ink-2","width":1,"height":1,"strokes":[]}"#.utf8)) }71        #expect(throws: InkError.unsupportedFormat(nil)) { try InkDocument(data: Data(#"{"strokes":[]}"#.utf8)) }72        #expect(throws: InkError.self) { try InkDocument(data: Data(#"{"format":"spn-ink-1","strokes":{}}"#.utf8)) }73        #expect(throws: InkError.self) { try InkDocument(data: Data(#"{"format":"spn-ink-1"}"#.utf8)) }74        #expect(throws: InkError.self) { try InkDocument(data: Data(#"{"format":"spn-ink-1","strokes":[{"points":[[1]]}]}"#.utf8)) }75        #expect(throws: InkError.self) { try InkDocument(data: Data(#"{"format":"spn-ink-1","strokes":[{"points":[[1,2,"x"]]}]}"#.utf8)) }76        #expect(throws: InkError.self) { try InkDocument(data: Data("[]".utf8)) }77        #expect(throws: DocumentError.self) { try InkDocument(data: Data("{".utf8)) }78    }7980    @Test func colours() {81        #expect(InkColor(hex: "#11223344") == InkColor(red: UInt8(0x11), green: 0x22, blue: 0x33, alpha: 0x44))82        #expect(InkColor(hex: "#AbCdEf")?.hex == "#abcdefff")83        for bad in ["", "#", "112233", "#12345", "#1234567", "#gg0000", "#1122334455", "#é12233"] { #expect(InkColor(hex: bad) == nil, "\(bad)") }84        #expect(InkColor(red: 1.0, green: 0.5, blue: -3, alpha: 2).hex == "#ff8000ff")85        #expect(InkColor(red: UInt8(0), green: 0, blue: 0, alpha: 51).opacity == 0.2)86    }8788    @Test func simplificationKeepsShapeAndPressure() {89        // A straight line of 101 points with one bump and one pressure dip.90        var points = (0...100).map { InkPoint(x: Double($0), y: 0, pressure: 0.5) }91        points[40].y = 1092        points[70].pressure = 0.993        let stroke = InkStroke(width: 2, points: points)94        let s = stroke.simplified(tolerance: 1)95        #expect(s.points.count < 12)96        #expect(s.points.first == points.first && s.points.last == points.last)97        #expect(s.points.contains(points[40]) && s.points.contains(points[70]))98        // Every dropped point stays within the tolerance of the simplified line.99        for p in points { #expect(s.distance(to: p.cgPoint) <= 1.0001) }100        // Without the pressure rule the dip goes.101        #expect(!stroke.simplified(tolerance: 1, pressureTolerance: 0).points.contains(points[70]))102        #expect(stroke.simplified(tolerance: 0) == stroke)103        #expect(stroke.simplified(tolerance: 1).simplified(tolerance: 1) == s)104        #expect(InkStroke(points: [InkPoint(x: 1, y: 1)]).simplified(tolerance: 5).points.count == 1)105        #expect(s.tool == stroke.tool && s.color == stroke.color && s.width == stroke.width)106107        var doc = InkDocument(width: 200, height: 20, strokes: [stroke, InkStroke(points: [])])108        doc["k"] = 1109        let d = doc.simplified(tolerance: 1)110        #expect(d.strokes.count == 1 && d.strokes[0] == s && d["k"] == 1 && d.width == 200)111    }112113    @Test func boundingBoxAndHitTesting() {114        let a = InkStroke(width: 4, points: [InkPoint(x: 10, y: 20), InkPoint(x: 50, y: 20)])115        let b = InkStroke(width: 2, points: [InkPoint(x: 100, y: 100)])116        #expect(a.boundingBox == CGRect(x: 8, y: 18, width: 44, height: 4))117        #expect(b.boundingBox == CGRect(x: 99, y: 99, width: 2, height: 2))118        #expect(InkStroke(points: []).boundingBox.isNull)119        let doc = InkDocument(width: 200, height: 200, strokes: [a, b])120        #expect(doc.boundingBox == CGRect(x: 8, y: 18, width: 93, height: 83))121        #expect(InkDocument(width: 10, height: 10).boundingBox.isNull && InkDocument(width: 10, height: 10).isEmpty)122        #expect(a.distance(to: CGPoint(x: 30, y: 25)) == 5 && a.distance(to: CGPoint(x: 0, y: 20)) == 10)123        #expect(InkStroke(points: []).distance(to: .zero) == .infinity)124        #expect(a.hit(CGPoint(x: 30, y: 22)) && !a.hit(CGPoint(x: 30, y: 23)) && a.hit(CGPoint(x: 30, y: 23), radius: 1))125        #expect(doc.strokeIndices(near: CGPoint(x: 99, y: 99), radius: 3) == [1])126        #expect(doc.strokeIndices(near: CGPoint(x: 150, y: 10), radius: 3).isEmpty)127        #expect(doc.strokeIndices(intersecting: CGRect(x: 0, y: 0, width: 60, height: 60)) == [0])128        #expect(doc.strokeIndices(intersecting: CGRect(x: 0, y: 0, width: 300, height: 300)) == [0, 1])129    }130131    // MARK: Renderer132133    /// RGBA of a pixel, row 0 at the top.134    func pixel(_ image: CGImage, _ x: Int, _ y: Int) throws -> [UInt8] {135        let data = try #require(image.dataProvider?.data as Data?)136        let o = y * image.bytesPerRow + x * 4137        return Array(data[o..<o + 4])138    }139140    /// A horizontal red marker line near the top-left of a 100 × 60 canvas.141    var line: InkDocument {142        InkDocument(width: 100, height: 60, strokes: [143            InkStroke(tool: .marker, color: InkColor(red: UInt8(255), green: 0, blue: 0), width: 6, points: [InkPoint(x: 10, y: 10), InkPoint(x: 60, y: 10)]),144        ])145    }146147    @Test func rendersInkWithTheOriginAtTheTopLeft() throws {148        let image = try #require(InkRenderer.image(line, scale: 2))149        #expect(image.width == 200 && image.height == 120)150        #expect(try pixel(image, 70, 20) == [255, 0, 0, 255])      // on the line (canvas 35, 10)151        #expect(try pixel(image, 70, 100) == [0, 0, 0, 0])         // mirrored position: must be empty152        #expect(try pixel(image, 199, 119) == [0, 0, 0, 0])        // far corner: transparent153        #expect(try pixel(image, 70, 40) == [0, 0, 0, 0])          // below the line154155        let white = try #require(InkRenderer.image(line, scale: 1, background: .white))156        #expect(white.width == 100 && white.height == 60)157        #expect(try pixel(white, 35, 10) == [255, 0, 0, 255])158        #expect(try pixel(white, 99, 59) == [255, 255, 255, 255])159        let tinted = try #require(InkRenderer.image(line, scale: 1, background: InkBackground(attr: "#0000ff")))160        #expect(try pixel(tinted, 99, 59) == [0, 0, 255, 255])161        #expect(InkBackground(attr: "none") == .none && InkBackground(attr: nil) == .none && InkBackground(attr: "white") == .white)162        #expect(InkBackground(attr: "paper") == .none)163    }164165    @Test func toolsDifferAndPressureThinsThePen() throws {166        func doc(_ tool: InkTool, alpha: UInt8 = 255, pressure: Double = 1) -> InkDocument {167            InkDocument(width: 100, height: 40, strokes: [168                InkStroke(tool: tool, color: InkColor(red: UInt8(0), green: 0, blue: 255, alpha: alpha), width: 10,169                          points: [InkPoint(x: 10, y: 20, pressure: pressure), InkPoint(x: 50, y: 20, pressure: pressure), InkPoint(x: 90, y: 20, pressure: pressure)]),170            ])171        }172        // A highlighter with an opaque colour is drawn translucent; a marker is not.173        let hl = try #require(InkRenderer.image(doc(.highlighter), scale: 1))174        let a = try pixel(hl, 50, 20)[3]175        #expect(a > 80 && a < 125)176        let marker = try #require(InkRenderer.image(doc(.marker), scale: 1))177        #expect(try pixel(marker, 50, 20) == [0, 0, 255, 255])178        // The stroke's own alpha is honoured, once (no darker joints).179        let half = try #require(InkRenderer.image(doc(.pen, alpha: 128), scale: 1))180        let h1 = Int(try pixel(half, 30, 20)[3]), h2 = Int(try pixel(half, 50, 20)[3])181        #expect(abs(h1 - 128) <= 2 && abs(h2 - 128) <= 2)182        // Full pressure covers 4 units off the axis, low pressure does not.183        let full = try #require(InkRenderer.image(doc(.pen), scale: 1))184        let light = try #require(InkRenderer.image(doc(.pen, pressure: 0), scale: 1))185        #expect(try pixel(full, 50, 16)[3] == 255)186        #expect(try pixel(light, 50, 16)[3] == 0)187        #expect(try pixel(light, 50, 20)[3] == 255)188        // An unknown tool is drawn like a pen; a single point is a dot.189        let brush = try #require(InkRenderer.image(doc(InkTool(rawValue: "brush")), scale: 1))190        #expect(try pixel(brush, 50, 20)[3] == 255)191        let dot = InkDocument(width: 20, height: 20, strokes: [InkStroke(tool: .pen, width: 8, points: [InkPoint(x: 10, y: 10)])])192        let dotImage = try #require(InkRenderer.image(dot, scale: 1))193        #expect(try pixel(dotImage, 10, 10) == [0, 0, 0, 255])194        #expect(try pixel(dotImage, 1, 1) == [0, 0, 0, 0])195    }196197    @Test func pngIsValidAndDeterministic() throws {198        let png = try #require(InkRenderer.pngData(line, scale: 2))199        #expect(Array(png.prefix(8)) == [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])200        let source = try #require(CGImageSourceCreateWithData(png as CFData, nil))201        let decoded = try #require(CGImageSourceCreateImageAtIndex(source, 0, nil))202        #expect(decoded.width == 200 && decoded.height == 120)203        #expect(InkRenderer.pngData(line, scale: 2) == png)204        let a = try #require(InkRenderer.image(line)), b = try #require(InkRenderer.image(line))205        #expect((a.dataProvider?.data as Data?) == (b.dataProvider?.data as Data?))206        // The round trip through JSON renders the same pixels.207        let reread = try InkDocument(data: line.jsonData())208        #expect(InkRenderer.pngData(reread, scale: 2) == png)209    }210211    @Test func emptyAndDegenerateDocuments() throws {212        let empty = try #require(InkRenderer.image(InkDocument(width: 30, height: 20), scale: 3))213        #expect(empty.width == 90 && empty.height == 60)214        let bytes = try #require(empty.dataProvider?.data as Data?)215        #expect(bytes.allSatisfy { $0 == 0 })216        #expect(InkRenderer.image(InkDocument(width: 0, height: 0)) == nil)217        #expect(InkRenderer.image(InkDocument(width: 10, height: 0)) == nil)218        #expect(InkRenderer.pngData(InkDocument(width: 0, height: 10)) == nil)219        #expect(InkRenderer.image(line, scale: 0) == nil)220        #expect(InkRenderer.image(InkDocument(width: 30, height: 20), crop: .content(padding: 4)) == nil)221        // Non-finite points and zero widths are skipped, not crashed on.222        var odd = line223        odd.strokes.append(InkStroke(width: 0, points: [InkPoint(x: 1, y: 1), InkPoint(x: 2, y: 2)]))224        odd.strokes.append(InkStroke(width: 3, points: [InkPoint(x: .nan, y: 1), InkPoint(x: .infinity, y: 2)]))225        #expect(InkRenderer.pngData(odd, scale: 2) == InkRenderer.pngData(line, scale: 2))226        // Huge canvases are scaled down to the pixel cap.227        let huge = try #require(InkRenderer.image(InkDocument(width: 100_000, height: 50_000), scale: 2))228        #expect(huge.width == InkRenderer.maxPixels && huge.height == InkRenderer.maxPixels / 2)229    }230231    @Test func cropsToContent() throws {232        let image = try #require(InkRenderer.image(line, scale: 1, crop: .content(padding: 2)))233        // Box of the line: x 7…63, y 7…13 → 56 × 6, plus 2 of padding on each side.234        #expect(image.width == 60 && image.height == 10)235        #expect(try pixel(image, 30, 5) == [255, 0, 0, 255])236        #expect(try pixel(image, 0, 0) == [0, 0, 0, 0])237        #expect(InkRenderer.frame(of: line, crop: .content(padding: 2)) == CGRect(x: 5, y: 5, width: 60, height: 10))238        let part = try #require(InkRenderer.image(line, scale: 1, crop: .rect(CGRect(x: 20, y: 5, width: 10, height: 10))))239        #expect(part.width == 10 && part.height == 10)240        #expect(try pixel(part, 5, 5) == [255, 0, 0, 255])241    }242}243
Files main
Menu

Theme