Repository Public License
1import AppKit2import CoreText3import Foundation4import PrismCore5import SwiftUI67public struct IconError: Error, LocalizedError, Sendable, Equatable {8 public let message: String9 public init(_ message: String) { self.message = message }10 public var errorDescription: String? { message }11}1213/// Draws an `IconSpec` as a macOS app icon: continuous-corner body, soft drop shadow, layered artwork, finish.14public enum IconRenderer {15 /// The master size; smaller sizes are downsampled from it so every size shows the same drawing.16 public static let master = 10241718 public static func image(_ spec: JSONValue, pixels: Int = master) throws -> CGImage {19 let problems = IconSpec.problems(spec)20 guard problems.isEmpty else { throw IconError(problems.joined(separator: " ")) }21 let full = try draw(spec)22 guard pixels != master else { return full }23 guard let ctx = bitmap(pixels) else { throw IconError("The icon could not be drawn.") }24 ctx.interpolationQuality = .high25 ctx.draw(full, in: CGRect(x: 0, y: 0, width: pixels, height: pixels))26 guard let out = ctx.makeImage() else { throw IconError("The icon could not be drawn.") }27 return out28 }2930 public static func png(_ spec: JSONValue, pixels: Int) throws -> Data {31 let rep = NSBitmapImageRep(cgImage: try image(spec, pixels: pixels))32 guard let data = rep.representation(using: .png, properties: [:]) else { throw IconError("The icon could not be encoded.") }33 return data34 }3536 public static func nsImage(_ spec: JSONValue, pixels: Int = 256) -> NSImage? {37 guard let cg = try? image(spec, pixels: pixels) else { return nil }38 return NSImage(cgImage: cg, size: NSSize(width: pixels / 2, height: pixels / 2))39 }4041 /// Writes a complete `.icns` (16 to 1024 px) with `iconutil`.42 public static func writeICNS(_ spec: JSONValue, to url: URL) throws {43 let fm = FileManager.default44 let iconset = fm.temporaryDirectory.appendingPathComponent("prism-\(UUID().uuidString).iconset", isDirectory: true)45 try fm.createDirectory(at: iconset, withIntermediateDirectories: true)46 defer { try? fm.removeItem(at: iconset) }47 for (points, scale) in [(16, 1), (16, 2), (32, 1), (32, 2), (128, 1), (128, 2), (256, 1), (256, 2), (512, 1), (512, 2)] {48 try png(spec, pixels: points * scale).write(to: iconset.appendingPathComponent("icon_\(points)x\(points)\(scale == 2 ? "@2x" : "").png"))49 }50 let p = Process()51 p.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil")52 p.arguments = ["--convert", "icns", "--output", url.path, iconset.path]53 let pipe = Pipe()54 p.standardOutput = pipe; p.standardError = pipe55 try p.run()56 let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)57 p.waitUntilExit()58 guard p.terminationStatus == 0 else { throw IconError("iconutil failed: \(output)") }59 }6061 // MARK: Drawing6263 private static func bitmap(_ pixels: Int) -> CGContext? {64 CGContext(data: nil, width: pixels, height: pixels, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!,65 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)66 }6768 /// A context whose coordinates are the 100 × 100 artwork canvas (y down), mapped onto the icon body.69 private static func canvas(body: CGRect) -> CGContext? {70 guard let ctx = bitmap(master) else { return nil }71 ctx.translateBy(x: body.minX, y: body.maxY)72 ctx.scaleBy(x: body.width / 100, y: -body.height / 100)73 ctx.setShouldAntialias(true)74 ctx.interpolationQuality = .high75 return ctx76 }7778 private static func draw(_ spec: JSONValue) throws -> CGImage {79 let size = CGFloat(master)80 // Apple's macOS icon grid: an 824 pt body on a 1024 pt canvas.81 let body = CGRect(x: 100, y: 100, width: 824, height: 824)82 let squircle = RoundedRectangle(cornerRadius: 824 * 0.225, style: .continuous).path(in: body).cgPath83 guard let out = bitmap(master) else { throw IconError("The icon could not be drawn.") }84 let finish = spec["finish"]?.stringValue ?? "glass"8586 // Drop shadow under the body.87 out.saveGState()88 out.setShadow(offset: CGSize(width: 0, height: -12), blur: 24, color: CGColor(gray: 0, alpha: 0.32))89 out.addPath(squircle)90 out.setFillColor(RGBA(hex: spec["background"]?["colors"]?.arrayValue?.last?.stringValue ?? "#000000")?.cgColor ?? CGColor(gray: 0, alpha: 1))91 out.fillPath()92 out.restoreGState()9394 out.saveGState()95 out.addPath(squircle)96 out.clip()97 if let bg = canvas(body: body) {98 drawBackground(spec["background"] ?? .null, in: bg)99 if let image = bg.makeImage() { out.draw(image, in: CGRect(x: 0, y: 0, width: size, height: size)) }100 }101 for layer in (spec["layers"]?.arrayValue ?? []).prefix(IconSpec.maxLayers) {102 guard let ctx = canvas(body: body) else { continue }103 drawLayer(layer, in: ctx)104 guard let image = ctx.makeImage() else { continue }105 out.saveGState()106 out.setAlpha(CGFloat(min(max(layer["opacity"]?.doubleValue ?? 1, 0), 1)))107 out.setBlendMode(blend(layer["blend"]?.stringValue))108 if let shadow = layer["shadow"], shadow.boolValue != false {109 let blur = CGFloat(shadow["blur"]?.doubleValue ?? 4) * 8.24, y = CGFloat(shadow["y"]?.doubleValue ?? 2) * 8.24110 out.setShadow(offset: CGSize(width: 0, height: -y), blur: blur, color: CGColor(gray: 0, alpha: CGFloat(min(max(shadow["opacity"]?.doubleValue ?? 0.3, 0), 1))))111 }112 out.draw(image, in: CGRect(x: 0, y: 0, width: size, height: size))113 out.restoreGState()114 }115 let space = CGColorSpace(name: CGColorSpace.sRGB)!116 if finish == "glass" {117 // A soft light from above, as on system icons.118 let sheen = CGGradient(colorsSpace: space, colors: [CGColor(gray: 1, alpha: 0.30), CGColor(gray: 1, alpha: 0.04), CGColor(gray: 1, alpha: 0)] as CFArray, locations: [0, 0.45, 0.6])!119 out.drawLinearGradient(sheen, start: CGPoint(x: 0, y: body.maxY), end: CGPoint(x: 0, y: body.minY), options: [])120 let shade = CGGradient(colorsSpace: space, colors: [CGColor(gray: 0, alpha: 0), CGColor(gray: 0, alpha: 0.16)] as CFArray, locations: [0.55, 1])!121 out.drawLinearGradient(shade, start: CGPoint(x: 0, y: body.maxY), end: CGPoint(x: 0, y: body.minY), options: [])122 }123 out.restoreGState()124 if finish != "flat" {125 // A rim: light on the top edge, dark on the bottom edge.126 out.saveGState()127 out.addPath(squircle)128 out.clip()129 let rim = CGGradient(colorsSpace: space, colors: [CGColor(gray: 1, alpha: finish == "glass" ? 0.5 : 0.25), CGColor(gray: 1, alpha: 0), CGColor(gray: 0, alpha: 0.22)] as CFArray, locations: [0, 0.5, 1])!130 out.addPath(squircle.copy(strokingWithWidth: 7, lineCap: .butt, lineJoin: .round, miterLimit: 4))131 out.clip()132 out.drawLinearGradient(rim, start: CGPoint(x: 0, y: body.maxY), end: CGPoint(x: 0, y: body.minY), options: [])133 out.restoreGState()134 }135 guard let image = out.makeImage() else { throw IconError("The icon could not be drawn.") }136 return image137 }138139 private static func blend(_ name: String?) -> CGBlendMode {140 switch name {141 case "overlay": .overlay142 case "softLight": .softLight143 case "screen": .screen144 case "multiply": .multiply145 case "plusLighter": .plusLighter146 default: .normal147 }148 }149150 private static func gradient(_ colors: [RGBA]) -> CGGradient? {151 let list = colors.count == 1 ? colors + colors : colors152 return CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB)!, colors: list.map(\.cgColor) as CFArray, locations: nil)153 }154155 /// Fills the current clip of `rect` along `angle` (0 = left to right, 90 = top to bottom).156 private static func fillLinear(_ colors: [RGBA], angle: Double, rect: CGRect, in ctx: CGContext) {157 guard let g = gradient(colors) else { return }158 let a = CGFloat(angle) * .pi / 180, dx = cos(a), dy = sin(a)159 let half = (abs(dx) * rect.width + abs(dy) * rect.height) / 2160 let c = CGPoint(x: rect.midX, y: rect.midY)161 ctx.drawLinearGradient(g, start: CGPoint(x: c.x - dx * half, y: c.y - dy * half), end: CGPoint(x: c.x + dx * half, y: c.y + dy * half),162 options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])163 }164165 private static func drawBackground(_ bg: JSONValue, in ctx: CGContext) {166 let colors = (bg["colors"]?.arrayValue ?? []).compactMap { RGBA(hex: $0.stringValue ?? "") }167 guard let first = colors.first else { return }168 let rect = CGRect(x: 0, y: 0, width: 100, height: 100)169 let style = bg["style"]?.stringValue ?? (colors.count > 1 ? "linear" : "solid")170 let space = CGColorSpace(name: CGColorSpace.sRGB)!171 switch style {172 case "radial":173 if let g = gradient(colors) { ctx.drawRadialGradient(g, startCenter: CGPoint(x: 50, y: 38), startRadius: 0, endCenter: CGPoint(x: 50, y: 50), endRadius: 78, options: [.drawsAfterEndLocation]) }174 case "mesh":175 // A base color with soft blobs of the other colors: reads as a mesh gradient at icon sizes.176 ctx.setFillColor(first.cgColor); ctx.fill(rect)177 let centers = [CGPoint(x: 82, y: 86), CGPoint(x: 8, y: 92), CGPoint(x: 92, y: 10)]178 for (i, c) in colors.dropFirst().enumerated() {179 var clear = c; clear.a = 0180 guard let g = CGGradient(colorsSpace: space, colors: [c.cgColor, clear.cgColor] as CFArray, locations: nil) else { continue }181 ctx.drawRadialGradient(g, startCenter: centers[i % 3], startRadius: 0, endCenter: centers[i % 3], endRadius: 95, options: [])182 }183 case "solid":184 ctx.setFillColor(first.cgColor); ctx.fill(rect)185 default:186 fillLinear(colors, angle: bg["angle"]?.doubleValue ?? 90, rect: rect, in: ctx)187 }188 // Patterns are deliberately faint: texture, not artwork.189 ctx.setStrokeColor(CGColor(gray: 1, alpha: 0.10)); ctx.setFillColor(CGColor(gray: 1, alpha: 0.12)); ctx.setLineWidth(0.5)190 switch bg["pattern"]?.stringValue {191 case "dots":192 for x in stride(from: 6.0, through: 96, by: 9) { for y in stride(from: 6.0, through: 96, by: 9) { ctx.fillEllipse(in: CGRect(x: x - 0.8, y: y - 0.8, width: 1.6, height: 1.6)) } }193 case "grid":194 for v in stride(from: 10.0, to: 100, by: 10) { ctx.move(to: CGPoint(x: v, y: 0)); ctx.addLine(to: CGPoint(x: v, y: 100)); ctx.move(to: CGPoint(x: 0, y: v)); ctx.addLine(to: CGPoint(x: 100, y: v)) }195 ctx.strokePath()196 case "rays":197 for i in 0..<12 {198 let a = CGFloat(i) * .pi / 6, b = a + .pi / 12199 ctx.move(to: CGPoint(x: 50, y: 50)); ctx.addLine(to: CGPoint(x: 50 + cos(a) * 120, y: 50 + sin(a) * 120)); ctx.addLine(to: CGPoint(x: 50 + cos(b) * 120, y: 50 + sin(b) * 120)); ctx.closePath()200 }201 ctx.setFillColor(CGColor(gray: 1, alpha: 0.06)); ctx.fillPath()202 case "rings":203 for r in stride(from: 14.0, through: 90, by: 12) { ctx.strokeEllipse(in: CGRect(x: 50 - r, y: 50 - r, width: 2 * r, height: 2 * r)) }204 default: break205 }206 }207208 private static func fillColors(_ layer: JSONValue) -> ([RGBA], Double) {209 if let s = layer["fill"]?.stringValue, let c = RGBA(hex: s) { return ([c], 90) }210 let list = (layer["fill"]?["colors"]?.arrayValue ?? []).compactMap { RGBA(hex: $0.stringValue ?? "") }211 return (list.isEmpty ? [RGBA(hex: "#FFFFFF")!] : list, layer["fill"]?["angle"]?.doubleValue ?? 90)212 }213214 private static func drawLayer(_ layer: JSONValue, in ctx: CGContext) {215 let x = CGFloat(layer["x"]?.doubleValue ?? 50), y = CGFloat(layer["y"]?.doubleValue ?? 50)216 let rotation = CGFloat(layer["rotation"]?.doubleValue ?? 0) * .pi / 180217 let (colors, angle) = fillColors(layer)218 var path: CGPath?219 var bounds = CGRect.zero220221 if let d = layer["path"]?.stringValue, let parsed = try? SVGPath.parse(d) {222 // A path is already in canvas coordinates; x/y move its centre, scale and rotation apply about the canvas centre.223 let scale = CGFloat(layer["scale"]?.doubleValue ?? 1)224 var t = CGAffineTransform(translationX: x, y: y).rotated(by: rotation).scaledBy(x: scale, y: scale).translatedBy(x: -50, y: -50)225 path = parsed.copy(using: &t)226 } else if let shape = layer["shape"]?.stringValue {227 let w = CGFloat(layer["width"]?.doubleValue ?? layer["size"]?.doubleValue ?? 50), h = CGFloat(layer["height"]?.doubleValue ?? layer["size"]?.doubleValue ?? Double(w))228 let r = CGRect(x: -w / 2, y: -h / 2, width: w, height: h)229 let p = CGMutablePath()230 switch shape {231 case "circle": p.addEllipse(in: r)232 case "ring":233 let rw = CGFloat(layer["ringWidth"]?.doubleValue ?? Double(min(w, h)) * 0.14)234 p.addEllipse(in: r); p.addEllipse(in: r.insetBy(dx: rw, dy: rw))235 case "capsule": p.addRoundedRect(in: r, cornerWidth: min(w, h) / 2, cornerHeight: min(w, h) / 2)236 case "diamond": p.addLines(between: [CGPoint(x: 0, y: r.minY), CGPoint(x: r.maxX, y: 0), CGPoint(x: 0, y: r.maxY), CGPoint(x: r.minX, y: 0)]); p.closeSubpath()237 case "star", "hexagon":238 let n = shape == "hexagon" ? 6 : max(3, min(Int(layer["points"]?.doubleValue ?? 5), 24))239 let count = shape == "hexagon" ? n : n * 2240 let pts = (0..<count).map { i -> CGPoint in241 let radius: CGFloat = shape == "star" && i % 2 == 1 ? 0.42 : 1, a = CGFloat(i) * 2 * .pi / CGFloat(count) - .pi / 2242 return CGPoint(x: cos(a) * w / 2 * radius, y: sin(a) * h / 2 * radius)243 }244 p.addLines(between: pts); p.closeSubpath()245 default:246 let radius = min(CGFloat(layer["radius"]?.doubleValue ?? Double(min(w, h)) * 0.22), min(w, h) / 2)247 p.addRoundedRect(in: r, cornerWidth: radius, cornerHeight: radius)248 }249 var t = CGAffineTransform(translationX: x, y: y).rotated(by: rotation)250 path = p.copy(using: &t)251 }252253 if let path {254 bounds = path.boundingBoxOfPath255 if layer["fill"] != nil || layer["stroke"] == nil {256 ctx.saveGState()257 ctx.addPath(path); ctx.clip(using: .evenOdd)258 fillLinear(colors, angle: angle, rect: bounds, in: ctx)259 ctx.restoreGState()260 }261 if let stroke = RGBA(hex: layer["stroke"]?.stringValue ?? "") {262 ctx.addPath(path); ctx.setStrokeColor(stroke.cgColor); ctx.setLineWidth(CGFloat(layer["strokeWidth"]?.doubleValue ?? 2))263 ctx.setLineJoin(.round); ctx.setLineCap(.round); ctx.strokePath()264 }265 return266 }267268 // Symbols and text are drawn as a mask, then filled with the layer's colors.269 var mask: CGImage?270 var maskSize = CGSize.zero271 let size = CGFloat(layer["size"]?.doubleValue ?? 56)272 if let name = layer["symbol"]?.stringValue {273 let weight = nsWeight(layer["weight"]?.stringValue ?? "semibold")274 guard let symbol = NSImage(systemSymbolName: name, accessibilityDescription: nil)?.withSymbolConfiguration(.init(pointSize: 420, weight: weight)) else { return }275 var proposed = CGRect(origin: .zero, size: symbol.size)276 mask = symbol.cgImage(forProposedRect: &proposed, context: nil, hints: nil)277 let ratio = symbol.size.height / max(symbol.size.width, 1)278 // `size` is the larger dimension, so tall and wide symbols take the same visual room.279 maskSize = ratio > 1 ? CGSize(width: size / ratio, height: size) : CGSize(width: size, height: size * ratio)280 } else if let text = layer["text"]?.stringValue {281 let design: NSFontDescriptor.SystemDesign = switch layer["font"]?.stringValue { case "rounded": .rounded; case "serif": .serif; case "monospaced": .monospaced; default: .default }282 var font = NSFont.systemFont(ofSize: 400, weight: nsWeight(layer["weight"]?.stringValue ?? "bold"))283 if let d = font.fontDescriptor.withDesign(design), let f = NSFont(descriptor: d, size: 400) { font = f }284 let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font, .foregroundColor: NSColor.black]))285 let ink = CTLineGetBoundsWithOptions(line, .useGlyphPathBounds).insetBy(dx: -4, dy: -4)286 guard ink.width > 0, ink.height > 0, let m = CGContext(data: nil, width: Int(ink.width.rounded(.up)), height: Int(ink.height.rounded(.up)), bitsPerComponent: 8, bytesPerRow: 0,287 space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return }288 m.textPosition = CGPoint(x: -ink.minX, y: -ink.minY)289 CTLineDraw(line, m)290 mask = m.makeImage()291 maskSize = CGSize(width: size * ink.width / 400, height: size * ink.height / 400)292 }293 guard let mask else { return }294 let rect = CGRect(x: -maskSize.width / 2, y: -maskSize.height / 2, width: maskSize.width, height: maskSize.height)295 ctx.saveGState()296 ctx.translateBy(x: x, y: y); ctx.rotate(by: rotation)297 // Images are stored bottom-up; flip locally because the canvas points down.298 ctx.saveGState(); ctx.scaleBy(x: 1, y: -1); ctx.draw(mask, in: rect); ctx.restoreGState()299 ctx.setBlendMode(.sourceIn)300 fillLinear(colors, angle: angle, rect: rect.insetBy(dx: -1, dy: -1), in: ctx)301 ctx.restoreGState()302 }303304 private static func nsWeight(_ name: String) -> NSFont.Weight {305 switch name {306 case "light": .light307 case "regular": .regular308 case "medium": .medium309 case "semibold": .semibold310 case "heavy": .heavy311 case "black": .black312 default: .bold313 }314 }315}316