scripts/make-icon.swift

221 lines · 12168 bytes

  1// Draws orgstar's app icons from the variant table below into the committed asset catalogs:
  2// ios/Orgstar/Assets.xcassets (iOS app icons and their previews), packaging/AppIcons.xcassets
  3// (the Mac's icon) and packaging/IconPreviews (the Mac's Dock icons).
  4// Usage: swift scripts/make-icon.swift
  5import AppKit
  6
  7struct Variant {
  8    enum Style { case filled, outline, unicorn }
  9    let id: String
 10    /// The gradient, top-left to bottom-right.
 11    let top: NSColor, bottom: NSColor
 12    let glyph: NSColor
 13    let bars: NSColor
 14    var style: Style = .filled
 15}
 16
 17func rgb(_ hex: UInt32) -> NSColor {
 18    NSColor(srgbRed: CGFloat(hex >> 16 & 0xFF) / 255, green: CGFloat(hex >> 8 & 0xFF) / 255, blue: CGFloat(hex & 0xFF) / 255, alpha: 1)
 19}
 20
 21let variants: [Variant] = [
 22    Variant(id: "default", top: NSColor(srgbRed: 0.13, green: 0.20, blue: 0.55, alpha: 1), bottom: NSColor(srgbRed: 0.40, green: 0.22, blue: 0.70, alpha: 1),
 23            glyph: NSColor(srgbRed: 1, green: 0.78, blue: 0.30, alpha: 1), bars: NSColor(white: 1, alpha: 0.92)),
 24    Variant(id: "midnight", top: rgb(0x1a1d24), bottom: rgb(0x0b0c10), glyph: rgb(0xffc74d), bars: NSColor(white: 1, alpha: 0.85)),
 25    Variant(id: "paper", top: rgb(0xfbf8f1), bottom: rgb(0xece4d2), glyph: rgb(0x3b3428), bars: rgb(0x7d7262)),
 26    Variant(id: "org", top: rgb(0x77aa99), bottom: rgb(0x3e7a6a), glyph: rgb(0xffc74d), bars: NSColor(white: 1, alpha: 0.92)),
 27    Variant(id: "sunset", top: rgb(0xff9a3c), bottom: rgb(0xe23e7a), glyph: .white, bars: NSColor(white: 1, alpha: 0.85)),
 28    Variant(id: "forest", top: rgb(0x2f5d3a), bottom: rgb(0x173322), glyph: rgb(0xf4ecd0), bars: NSColor(white: 1, alpha: 0.8)),
 29    Variant(id: "mono", top: rgb(0x5a5d63), bottom: rgb(0x2c2e33), glyph: .white, bars: NSColor(white: 1, alpha: 0.8)),
 30    Variant(id: "rainbow", top: rgb(0xe40303), bottom: rgb(0x732982), glyph: .white, bars: NSColor(white: 1, alpha: 0.9)),
 31    Variant(id: "outline", top: .white, bottom: rgb(0xf2f2f2), glyph: rgb(0x2f5486), bars: rgb(0x2f5486), style: .outline),
 32    Variant(id: "terminal", top: rgb(0x0a0f0a), bottom: .black, glyph: rgb(0x39ff6a), bars: rgb(0x2bcc55)),
 33    Variant(id: "unicorn", top: rgb(0x77aa99), bottom: rgb(0x3e7a6a), glyph: rgb(0xffc74d), bars: .white, style: .unicorn),
 34    Variant(id: "unicorn-night", top: rgb(0x2b2a6b), bottom: rgb(0x14133a), glyph: rgb(0xd8dde6), bars: rgb(0xeae8ff), style: .unicorn),
 35    Variant(id: "unicorn-pastel", top: rgb(0xffc6dd), bottom: rgb(0xc7b8ff), glyph: rgb(0xffc74d), bars: .white, style: .unicorn),
 36]
 37
 38/// `darkTile`: the dark look on a near-black tile, for the Mac's Dock, which draws nothing
 39/// behind an icon set with `NSApp.applicationIconImage`.
 40enum Look { case light, dark, darkTile, tinted }
 41
 42/// The macOS icon grid: an 824-point rounded square in a 1024 canvas; `fullBleed` fills the
 43/// canvas, as iOS wants. Dark and tinted leave the background clear (dark) or black (tinted)
 44/// for the system to fill.
 45func draw(_ v: Variant, _ size: CGFloat, look: Look = .light, fullBleed: Bool = false) -> NSBitmapImageRep {
 46    let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size), pixelsHigh: Int(size), bitsPerSample: 8,
 47                               samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
 48    NSGraphicsContext.saveGraphicsState()
 49    NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
 50    let s = size / 1024
 51    if fullBleed {
 52        let transform = NSAffineTransform()
 53        transform.scale(by: 1024 / 824)
 54        transform.translateX(by: -100 * s, yBy: -100 * s)
 55        transform.concat()
 56    }
 57    let square = NSRect(x: 100 * s, y: 100 * s, width: 824 * s, height: 824 * s)
 58    let shape = fullBleed ? NSBezierPath(rect: square) : NSBezierPath(roundedRect: square, xRadius: 185 * s, yRadius: 185 * s)
 59    switch look {
 60    case .light where v.id == "rainbow":
 61        NSGraphicsContext.saveGraphicsState()
 62        shape.addClip()
 63        let stripes = [0xe40303, 0xff8c00, 0xffed00, 0x008026, 0x004dff, 0x750787].map(rgb)
 64        let band = square.height / CGFloat(stripes.count)
 65        for (i, color) in stripes.enumerated() {
 66            color.setFill()
 67            NSRect(x: square.minX, y: square.maxY - band * CGFloat(i + 1), width: square.width, height: band).fill()
 68        }
 69        NSGraphicsContext.restoreGraphicsState()
 70    case .light: NSGradient(colors: [v.top, v.bottom])!.draw(in: shape, angle: -60)
 71    case .dark: break
 72    case .darkTile: NSColor(srgbRed: 0.11, green: 0.11, blue: 0.12, alpha: 1).setFill(); shape.fill()
 73    case .tinted: NSColor.black.setFill(); shape.fill()
 74    }
 75    // On a dark background a dark glyph (Paper, Outline) is drawn light.
 76    func lifted(_ color: NSColor, _ light: CGFloat) -> NSColor {
 77        guard look == .dark || look == .darkTile, let c = color.usingColorSpace(.sRGB),
 78              0.2126 * c.redComponent + 0.7152 * c.greenComponent + 0.0722 * c.blueComponent < 0.4 else { return color }
 79        return NSColor(white: light, alpha: 1)
 80    }
 81    let glyph = look == .tinted ? NSColor(white: 0.95, alpha: 1) : lifted(v.glyph, 0.95)
 82    let bars = look == .tinted ? NSColor(white: 0.75, alpha: 1) : lifted(v.bars, 0.8)
 83    switch v.style {
 84    case .filled: drawOutline(s, glyph: glyph, bars: bars, filled: true)
 85    case .outline: drawOutline(s, glyph: glyph, bars: bars, filled: false)
 86    case .unicorn: drawUnicorn(s, glyph: glyph, head: bars)
 87    }
 88    NSGraphicsContext.restoreGraphicsState()
 89    return rep
 90}
 91
 92/// The heading star over three outline lines, indented like a heading's children.
 93func drawOutline(_ s: CGFloat, glyph: NSColor, bars: NSColor, filled: Bool) {
 94    let star = NSAttributedString(string: "✱", attributes: [
 95        .font: NSFont.systemFont(ofSize: 330 * s, weight: filled ? .heavy : .light), .foregroundColor: glyph,
 96    ])
 97    star.draw(at: NSPoint(x: 190 * s, y: 520 * s))
 98    for (i, (x, width)) in [(470.0, 330.0), (300.0, 500.0), (380.0, 420.0)].enumerated() {
 99        let y = (650 - Double(i) * 150) * s
100        let line = NSRect(x: x * s, y: y, width: width * s, height: (i == 0 ? 70 : 56) * s)
101        let path = NSBezierPath(roundedRect: line, xRadius: 28 * s, yRadius: 28 * s)
102        if filled {
103            bars.setFill(); path.fill()
104        } else {
105            bars.setStroke(); path.lineWidth = 10 * s; path.stroke()
106        }
107    }
108}
109
110/// A unicorn's head in profile, facing left, with a mane; its horn ends in the heading star.
111func drawUnicorn(_ s: CGFloat, glyph: NSColor, head: NSColor) {
112    func p(_ x: CGFloat, _ y: CGFloat) -> NSPoint { NSPoint(x: x * s, y: y * s) }
113    let face = NSBezierPath()
114    face.move(to: p(640, 200))                                                    // neck, back
115    face.curve(to: p(600, 560), controlPoint1: p(700, 330), controlPoint2: p(690, 480))
116    face.curve(to: p(470, 640), controlPoint1: p(560, 610), controlPoint2: p(520, 640))  // crown
117    face.line(to: p(440, 690))                                                    // ear
118    face.line(to: p(410, 620))
119    face.curve(to: p(250, 470), controlPoint1: p(340, 590), controlPoint2: p(270, 530))  // brow to nose
120    face.curve(to: p(290, 400), controlPoint1: p(235, 430), controlPoint2: p(250, 400))  // muzzle
121    face.curve(to: p(430, 430), controlPoint1: p(340, 400), controlPoint2: p(390, 410))  // jaw
122    face.curve(to: p(450, 200), controlPoint1: p(470, 360), controlPoint2: p(440, 280))  // throat
123    face.close()
124    head.setFill()
125    face.fill()
126
127    let mane = NSBezierPath()
128    mane.move(to: p(600, 560))
129    mane.curve(to: p(760, 220), controlPoint1: p(720, 520), controlPoint2: p(800, 360))
130    mane.line(to: p(690, 210))
131    mane.curve(to: p(600, 520), controlPoint1: p(730, 330), controlPoint2: p(680, 470))
132    mane.close()
133    glyph.withAlphaComponent(0.85).setFill()
134    mane.fill()
135
136    let horn = NSBezierPath()
137    horn.move(to: p(440, 640))
138    horn.line(to: p(300, 790))
139    horn.line(to: p(475, 660))
140    horn.close()
141    head.blended(withFraction: 0.25, of: glyph)?.setFill()
142    horn.fill()
143
144    let eye = NSBezierPath(ovalIn: NSRect(x: 360 * s, y: 520 * s, width: 28 * s, height: 28 * s))
145    NSColor(white: 0.15, alpha: 1).setFill()
146    eye.fill()
147
148    let star = NSAttributedString(string: "✱", attributes: [.font: NSFont.systemFont(ofSize: 190 * s, weight: .heavy), .foregroundColor: glyph])
149    star.draw(at: p(205, 700))
150}
151
152func png(_ rep: NSBitmapImageRep) -> Data { rep.representation(using: .png, properties: [:])! }
153
154/// Without an alpha channel, as the App Store requires for the light icon.
155func opaque(_ rep: NSBitmapImageRep) -> NSBitmapImageRep {
156    let size = rep.pixelsWide
157    let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: 0,
158                            space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
159    context.draw(rep.cgImage!, in: CGRect(x: 0, y: 0, width: size, height: size))
160    return NSBitmapImageRep(cgImage: context.makeImage()!)
161}
162
163func write(_ data: Data, _ path: String) throws {
164    let url = URL(fileURLWithPath: path)
165    try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
166    try data.write(to: url)
167}
168
169func json(_ object: Any, _ path: String) throws {
170    try write(JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]), path)
171}
172
173let info = ["author": "xcode", "version": 1] as [String: Any]
174let appearances: [(Look, String, [[String: String]])] = [
175    (.light, "", []),
176    (.dark, "-dark", [["appearance": "luminosity", "value": "dark"]]),
177    (.tinted, "-tinted", [["appearance": "luminosity", "value": "tinted"]]),
178]
179
180for v in variants {
181    // iOS: one set per icon, named AppIcon for the default and AppIcon-<Id> for the others.
182    let setName = v.id == "default" ? "AppIcon" : "AppIcon-" + v.id.split(separator: "-").map(\.capitalized).joined()
183    let set = "ios/Orgstar/Assets.xcassets/\(setName).appiconset"
184    var images: [[String: Any]] = []
185    for (look, suffix, appearance) in appearances {
186        let rep = draw(v, 1024, look: look, fullBleed: true)
187        try write(png(look == .light ? opaque(rep) : rep), "\(set)/AppIcon\(suffix).png")
188        var image: [String: Any] = ["filename": "AppIcon\(suffix).png", "idiom": "universal", "platform": "ios", "size": "1024x1024"]
189        if !appearance.isEmpty { image["appearances"] = appearance }
190        images.append(image)
191    }
192    try json(["images": images, "info": info], "\(set)/Contents.json")
193
194    // Previews for the iOS picker, light and dark.
195    let preview = "ios/Orgstar/Assets.xcassets/IconPreview-\(v.id).imageset"
196    try write(png(draw(v, 256, fullBleed: true)), "\(preview)/light.png")
197    try write(png(draw(v, 256, look: .dark, fullBleed: true)), "\(preview)/dark.png")
198    try json(["images": [
199        ["filename": "light.png", "idiom": "universal"],
200        ["filename": "dark.png", "idiom": "universal", "appearances": [["appearance": "luminosity", "value": "dark"]]],
201    ], "info": info], "\(preview)/Contents.json")
202
203    // The Mac's Dock icons and picker previews.
204    try write(png(draw(v, 512)), "packaging/IconPreviews/\(v.id)-light.png")
205    try write(png(draw(v, 512, look: .darkTile)), "packaging/IconPreviews/\(v.id)-dark.png")
206}
207
208// The Mac's bundle icon: the default variant at the Mac's sizes. actool drops dark and
209// tinted renditions from a macOS app icon set, so macOS derives those styles itself.
210let mac = "packaging/AppIcons.xcassets/AppIcon.appiconset"
211try? FileManager.default.removeItem(atPath: mac)
212var macImages: [[String: Any]] = []
213for base in [16, 32, 128, 256, 512] {
214    for scale in [1, 2] {
215        let name = "icon_\(base)x\(base)\(scale == 2 ? "@2x" : "").png"
216        try write(png(draw(variants[0], CGFloat(base * scale))), "\(mac)/\(name)")
217        macImages.append(["filename": name, "idiom": "mac", "scale": "\(scale)x", "size": "\(base)x\(base)"])
218    }
219}
220try json(["images": macImages, "info": info], "\(mac)/Contents.json")
221try json(["info": info], "packaging/AppIcons.xcassets/Contents.json")