Repository Public License
1import AppKit2import Foundation3import PrismCore45/// A declarative app icon: a background, up to twelve artwork layers and a finish.6/// The builder designs it (`design.setIcon`); PRISM draws it. Artwork uses a 100 × 100 canvas, y pointing down.7///8/// ```9/// {"background": {"colors": ["#0B1E3F", "#1F6FEB"], "style": "linear|radial|mesh|solid", "angle": 90, "pattern": "none|dots|grid|rays|rings"},10/// "layers": [{"symbol": "leaf.fill", "size": 56, "fill": {"colors": ["#fff", "#cde"], "angle": 90}, "shadow": true},11/// {"path": "M20 70 L50 20 L80 70 Z", "fill": "#FFFFFF", "stroke": "#000000", "strokeWidth": 2},12/// {"shape": "circle|ring|roundedRect|capsule|diamond|star|hexagon", "width": 40, "height": 40},13/// {"text": "A", "size": 50, "font": "rounded", "weight": "heavy"}],14/// "finish": "glass|matte|flat"}15/// ```16public enum IconSpec {17 public static let maxLayers = 1218 public static let styles = ["linear", "radial", "mesh", "solid"]19 public static let patterns = ["none", "dots", "grid", "rays", "rings"]20 public static let finishes = ["glass", "matte", "flat"]21 public static let shapes = ["circle", "ring", "roundedRect", "capsule", "diamond", "star", "hexagon"]22 public static let blends = ["normal", "overlay", "softLight", "screen", "multiply", "plusLighter"]23 public static let fonts = ["default", "rounded", "serif", "monospaced"]24 public static let weights = ["light", "regular", "medium", "semibold", "bold", "heavy", "black"]2526 private static let backgroundKeys: Set<String> = ["colors", "style", "angle", "pattern"]27 private static let layerKeys: Set<String> = [28 "symbol", "path", "shape", "text", "fill", "stroke", "strokeWidth", "opacity", "shadow", "blend", "x", "y", "size", "width", "height",29 "radius", "ringWidth", "rotation", "scale", "font", "weight", "points",30 ]3132 /// Every problem with a spec, phrased so the builder can fix it. Empty means drawable.33 public static func problems(_ spec: JSONValue) -> [String] {34 guard let o = spec.objectValue else { return ["The icon must be an object with `background`, `layers` and `finish`."] }35 var out: [String] = []36 for k in o.keys.sorted() where !["background", "layers", "finish"].contains(k) { out.append("Unknown icon field `\(k)`.") }37 if let f = o["finish"], f.stringValue.map(finishes.contains) != true { out.append("`finish` must be one of \(finishes.joined(separator: ", ")).") }38 if let b = o["background"] {39 guard let bo = b.objectValue else { return out + ["`background` must be an object."] }40 for k in bo.keys.sorted() where !backgroundKeys.contains(k) { out.append("Unknown background field `\(k)`.") }41 let colors = bo["colors"]?.arrayValue ?? []42 if colors.isEmpty || colors.count > 4 { out.append("`background.colors` needs 1 to 4 hex colors.") }43 for c in colors where RGBA(hex: c.stringValue ?? "") == nil { out.append("`\(c.canonicalString())` is not a hex color like #1F6FEB.") }44 if let s = bo["style"], s.stringValue.map(styles.contains) != true { out.append("`background.style` must be one of \(styles.joined(separator: ", ")).") }45 if let p = bo["pattern"], p.stringValue.map(patterns.contains) != true { out.append("`background.pattern` must be one of \(patterns.joined(separator: ", ")).") }46 if let a = bo["angle"], a.doubleValue == nil { out.append("`background.angle` must be a number of degrees.") }47 } else { out.append("The icon needs a `background`.") }48 guard let layers = o["layers"]?.arrayValue, !layers.isEmpty else { return out + ["The icon needs at least one entry in `layers`."] }49 if layers.count > maxLayers { out.append("At most \(maxLayers) layers.") }50 for (i, layer) in layers.prefix(maxLayers).enumerated() {51 let at = "layers[\(i)]"52 guard let l = layer.objectValue else { out.append("\(at) must be an object."); continue }53 for k in l.keys.sorted() where !layerKeys.contains(k) { out.append("\(at): unknown field `\(k)`.") }54 let kinds = ["symbol", "path", "shape", "text"].filter { l[$0] != nil }55 guard kinds.count == 1 else { out.append("\(at) needs exactly one of `symbol`, `path`, `shape`, `text`."); continue }56 switch kinds[0] {57 case "symbol":58 let name = l["symbol"]?.stringValue ?? ""59 if NSImage(systemSymbolName: name, accessibilityDescription: nil) == nil { out.append("\(at): `\(name)` is not an SF Symbol on this Mac. Pick another symbol or draw a `path`.") }60 case "path":61 do { _ = try SVGPath.parse(l["path"]?.stringValue ?? "") } catch { out.append("\(at): \(error.localizedDescription)") }62 case "shape":63 if l["shape"]?.stringValue.map(shapes.contains) != true { out.append("\(at): `shape` must be one of \(shapes.joined(separator: ", ")).") }64 default:65 let t = l["text"]?.stringValue ?? ""66 if t.isEmpty || t.count > 4 { out.append("\(at): `text` must be 1 to 4 characters.") }67 }68 for key in ["fill", "stroke"] {69 guard let v = l[key] else { continue }70 if let s = v.stringValue { if RGBA(hex: s) == nil { out.append("\(at): `\(key)` `\(s)` is not a hex color.") } }71 else if key == "fill", let colors = v["colors"]?.arrayValue, (1...4).contains(colors.count) {72 for c in colors where RGBA(hex: c.stringValue ?? "") == nil { out.append("\(at): `\(c.canonicalString())` is not a hex color.") }73 } else { out.append("\(at): `\(key)` must be a hex color\(key == "fill" ? " or {colors: [...], angle}" : "").") }74 }75 for key in ["x", "y", "size", "width", "height", "radius", "ringWidth", "rotation", "scale", "strokeWidth", "opacity", "points"] {76 guard let v = l[key] else { continue }77 guard let n = v.doubleValue, n.isFinite, abs(n) <= 1000 else { out.append("\(at): `\(key)` must be a number."); continue }78 if ["size", "width", "height", "scale"].contains(key), n <= 0 { out.append("\(at): `\(key)` must be greater than 0.") }79 }80 if let b = l["blend"], b.stringValue.map(blends.contains) != true { out.append("\(at): `blend` must be one of \(blends.joined(separator: ", ")).") }81 if let f = l["font"], f.stringValue.map(fonts.contains) != true { out.append("\(at): `font` must be one of \(fonts.joined(separator: ", ")).") }82 if let w = l["weight"], w.stringValue.map(weights.contains) != true { out.append("\(at): `weight` must be one of \(weights.joined(separator: ", ")).") }83 if let s = l["shadow"], s.boolValue == nil, s.objectValue == nil { out.append("\(at): `shadow` must be true/false or {blur, y, opacity}.") }84 }85 return out86 }8788 /// The icon used when the builder has not designed one: the app's initials on a color derived from its identity.89 public static func automatic(name: String, seed: String) -> JSONValue {90 let hash = seed.unicodeScalars.reduce(UInt32(7)) { ($0 &* 31) &+ $1.value }91 let hue = Double(hash % 360) / 36092 func hex(_ h: Double, _ s: Double, _ b: Double) -> JSONValue {93 let c = NSColor(hue: h.truncatingRemainder(dividingBy: 1), saturation: s, brightness: b, alpha: 1).usingColorSpace(.sRGB) ?? .gray94 return .string(String(format: "#%02X%02X%02X", Int(c.redComponent * 255), Int(c.greenComponent * 255), Int(c.blueComponent * 255)))95 }96 let words = name.split(whereSeparator: { !$0.isLetter && !$0.isNumber })97 let initials = String(words.prefix(2).compactMap(\.first)).uppercased()98 return [99 "background": ["colors": [hex(hue, 0.55, 0.98), hex(hue + 0.06, 0.82, 0.72), hex(hue + 0.92, 0.7, 0.5)], "style": "mesh", "pattern": "rings"],100 "layers": [["text": .string(initials.isEmpty ? "P" : initials), "size": .double(initials.count > 1 ? 44 : 56), "font": "rounded", "weight": "heavy", "fill": ["colors": ["#FFFFFF", "#FFFFFFD0"], "angle": 90], "shadow": true]],101 "finish": "glass",102 ]103 }104}105106/// An sRGB color parsed from `#RGB`, `#RRGGBB` or `#RRGGBBAA`.107public struct RGBA: Sendable, Equatable {108 public var r, g, b, a: Double109110 public init?(hex: String) {111 var s = hex.trimmingCharacters(in: .whitespaces)112 guard s.hasPrefix("#") else { return nil }113 s.removeFirst()114 if s.count == 3 { s = s.map { "\($0)\($0)" }.joined() }115 guard s.count == 6 || s.count == 8, let v = UInt64(s, radix: 16) else { return nil }116 if s.count == 6 { r = Double((v >> 16) & 0xFF) / 255; g = Double((v >> 8) & 0xFF) / 255; b = Double(v & 0xFF) / 255; a = 1 }117 else { r = Double((v >> 24) & 0xFF) / 255; g = Double((v >> 16) & 0xFF) / 255; b = Double((v >> 8) & 0xFF) / 255; a = Double(v & 0xFF) / 255 }118 }119120 public var cgColor: CGColor { CGColor(srgbRed: r, green: g, blue: b, alpha: a) }121122 /// WCAG relative luminance.123 public var luminance: Double {124 func lin(_ c: Double) -> Double { c <= 0.03928 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4) }125 return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)126 }127128 /// WCAG contrast ratio, 1 (none) to 21.129 public func contrast(with other: RGBA) -> Double {130 let a = luminance, b = other.luminance131 return (max(a, b) + 0.05) / (min(a, b) + 0.05)132 }133}134