SPB Git

Repository Public License

SVGPath.swift 8.8 KB 173 lines swift

1import CoreGraphics2import Foundation34/// Parses SVG path data (`M L H V C S Q T A Z`, absolute and relative) into a `CGPath`.5/// Used for icon artwork drawn by the builder; input is untrusted, so every limit is explicit.6public enum SVGPath {7    public struct ParseError: Error, LocalizedError, Sendable, Equatable {8        public let message: String9        public var errorDescription: String? { message }10    }1112    public static let maxLength = 600013    public static let maxSegments = 8001415    public static func parse(_ d: String) throws -> CGPath {16        guard d.utf8.count <= maxLength else { throw ParseError(message: "The path is longer than \(maxLength) characters.") }17        var scanner = Tokens(d)18        let path = CGMutablePath()19        var current = CGPoint.zero, start = CGPoint.zero20        var lastControl: CGPoint?, lastCommand: Character = " "21        var command: Character = " "22        var segments = 02324        func number() throws -> CGFloat {25            guard let v = scanner.number() else { throw ParseError(message: "Expected a number after `\(command)`.") }26            guard v.isFinite, abs(v) < 100_000 else { throw ParseError(message: "A coordinate is out of range.") }27            return CGFloat(v)28        }29        func point(relative: Bool) throws -> CGPoint {30            let x = try number(), y = try number()31            return relative ? CGPoint(x: current.x + x, y: current.y + y) : CGPoint(x: x, y: y)32        }3334        while true {35            scanner.skipSeparators()36            if scanner.atEnd { break }37            if let c = scanner.command() { command = c } else if command == " " {38                throw ParseError(message: "The path must start with a command such as `M`.")39            } else if command == "M" { command = "L" } else if command == "m" { command = "l" }40            else if command == "Z" || command == "z" { throw ParseError(message: "Unexpected number after `Z`.") }41            segments += 142            guard segments <= maxSegments else { throw ParseError(message: "The path has more than \(maxSegments) segments.") }43            let rel = command.isLowercase44            if path.isEmpty, !"Mm".contains(command) { throw ParseError(message: "The path must start with `M`.") }45            switch command {46            case "M", "m":47                current = try point(relative: rel); start = current48                path.move(to: current)49            case "L", "l":50                current = try point(relative: rel); path.addLine(to: current)51            case "H", "h":52                let x = try number(); current.x = rel ? current.x + x : x; path.addLine(to: current)53            case "V", "v":54                let y = try number(); current.y = rel ? current.y + y : y; path.addLine(to: current)55            case "C", "c":56                let c1 = try point(relative: rel), c2 = try point(relative: rel), end = try point(relative: rel)57                path.addCurve(to: end, control1: c1, control2: c2); lastControl = c2; current = end58            case "S", "s":59                let c1 = "CcSs".contains(lastCommand) ? reflect(lastControl, around: current) : current60                let c2 = try point(relative: rel), end = try point(relative: rel)61                path.addCurve(to: end, control1: c1, control2: c2); lastControl = c2; current = end62            case "Q", "q":63                let c = try point(relative: rel), end = try point(relative: rel)64                path.addQuadCurve(to: end, control: c); lastControl = c; current = end65            case "T", "t":66                let c = "QqTt".contains(lastCommand) ? reflect(lastControl, around: current) : current67                let end = try point(relative: rel)68                path.addQuadCurve(to: end, control: c); lastControl = c; current = end69            case "A", "a":70                let rx = try number(), ry = try number(), rotation = try number()71                guard let large = scanner.flag(), let sweep = scanner.flag() else { throw ParseError(message: "An arc needs two 0/1 flags.") }72                let end = try point(relative: rel)73                addArc(to: path, from: current, to: end, rx: rx, ry: ry, rotation: rotation, large: large, sweep: sweep)74                current = end75            case "Z", "z":76                path.closeSubpath(); current = start77            default:78                throw ParseError(message: "Unknown path command `\(command)`.")79            }80            lastCommand = command81        }82        guard !path.isEmpty else { throw ParseError(message: "The path is empty.") }83        return path84    }8586    private static func reflect(_ p: CGPoint?, around c: CGPoint) -> CGPoint {87        guard let p else { return c }88        return CGPoint(x: 2 * c.x - p.x, y: 2 * c.y - p.y)89    }9091    /// Endpoint arc → centre parameterisation (SVG 1.1 implementation notes F.6.5), emitted as cubic curves.92    private static func addArc(to path: CGMutablePath, from p0: CGPoint, to p1: CGPoint, rx: CGFloat, ry: CGFloat, rotation: CGFloat, large: Bool, sweep: Bool) {93        var rx = abs(rx), ry = abs(ry)94        guard rx > 0.0001, ry > 0.0001, p0 != p1 else { path.addLine(to: p1); return }95        let phi = rotation * .pi / 180, cosP = cos(phi), sinP = sin(phi)96        let dx = (p0.x - p1.x) / 2, dy = (p0.y - p1.y) / 297        let x1 = cosP * dx + sinP * dy, y1 = -sinP * dx + cosP * dy98        let lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry)99        if lambda > 1 { rx *= sqrt(lambda); ry *= sqrt(lambda) }100        let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1101        let den = rx * rx * y1 * y1 + ry * ry * x1 * x1102        var k = den == 0 ? 0 : sqrt(max(0, num / den))103        if large == sweep { k = -k }104        let cx1 = k * rx * y1 / ry, cy1 = -k * ry * x1 / rx105        let cx = cosP * cx1 - sinP * cy1 + (p0.x + p1.x) / 2, cy = sinP * cx1 + cosP * cy1 + (p0.y + p1.y) / 2106        func angle(_ ux: CGFloat, _ uy: CGFloat, _ vx: CGFloat, _ vy: CGFloat) -> CGFloat { atan2(ux * vy - uy * vx, ux * vx + uy * vy) }107        let theta = angle(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry)108        var delta = angle((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry)109        if !sweep, delta > 0 { delta -= 2 * .pi } else if sweep, delta < 0 { delta += 2 * .pi }110        let pieces = max(1, Int(ceil(abs(delta) / (.pi / 2))))111        let step = delta / CGFloat(pieces), t = 4 / 3 * tan(step / 4)112        func at(_ a: CGFloat) -> (CGPoint, CGPoint) { // point and derivative on the ellipse113            let ca = cos(a), sa = sin(a)114            return (CGPoint(x: cx + rx * ca * cosP - ry * sa * sinP, y: cy + rx * ca * sinP + ry * sa * cosP),115                    CGPoint(x: -rx * sa * cosP - ry * ca * sinP, y: -rx * sa * sinP + ry * ca * cosP))116        }117        var a = theta118        for _ in 0..<pieces {119            let (s, ds) = at(a), (e, de) = at(a + step)120            path.addCurve(to: e, control1: CGPoint(x: s.x + t * ds.x, y: s.y + t * ds.y), control2: CGPoint(x: e.x - t * de.x, y: e.y - t * de.y))121            a += step122        }123    }124125    private struct Tokens {126        let chars: [UInt8]127        var i = 0128        init(_ s: String) { chars = Array(s.utf8) }129        var atEnd: Bool { i >= chars.count }130131        mutating func skipSeparators() {132            while i < chars.count, chars[i] == 0x20 || chars[i] == 0x2C || chars[i] == 0x0A || chars[i] == 0x09 || chars[i] == 0x0D { i += 1 }133        }134135        mutating func command() -> Character? {136            guard i < chars.count else { return nil }137            let c = Character(UnicodeScalar(chars[i]))138            guard c.isLetter, c != "e", c != "E" else { return nil }139            i += 1140            return c141        }142143        mutating func flag() -> Bool? {144            skipSeparators()145            guard i < chars.count, chars[i] == 0x30 || chars[i] == 0x31 else { return nil }146            defer { i += 1 }147            return chars[i] == 0x31148        }149150        mutating func number() -> Double? {151            skipSeparators()152            let begin = i153            if i < chars.count, chars[i] == 0x2B || chars[i] == 0x2D { i += 1 }154            var digits = 0, seenDot = false155            while i < chars.count {156                let c = chars[i]157                if c >= 0x30, c <= 0x39 { digits += 1; i += 1 }158                else if c == 0x2E, !seenDot { seenDot = true; i += 1 }159                else { break }160            }161            guard digits > 0 else { i = begin; return nil }162            if i < chars.count, chars[i] == 0x65 || chars[i] == 0x45 {163                var j = i + 1164                if j < chars.count, chars[j] == 0x2B || chars[j] == 0x2D { j += 1 }165                let expStart = j166                while j < chars.count, chars[j] >= 0x30, chars[j] <= 0x39 { j += 1 }167                if j > expStart { i = j }168            }169            return Double(String(decoding: chars[begin..<i], as: UTF8.self))170        }171    }172}173
Files main
Menu

Theme