scripts/make-icon.swift

199 lines · 11422 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, star }
  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: .star),
 34    Variant(id: "unicorn-night", top: rgb(0x2b2a6b), bottom: rgb(0x14133a), glyph: rgb(0xd8dde6), bars: rgb(0xeae8ff), style: .star),
 35    Variant(id: "unicorn-pastel", top: rgb(0xffc6dd), bottom: rgb(0xc7b8ff), glyph: rgb(0xffc74d), bars: .white, style: .star),
 36]
 37
 38/// `dark`: the icon's background darkened, so each icon keeps its color in the system's Dark
 39/// icon style and the Mac's dark Dock; `tinted`: a grayscale glyph on black for the system to tint.
 40enum Look { case light, dark, tinted }
 41
 42/// The macOS icon grid: an 824-point rounded square in a 1024 canvas; `fullBleed` fills the
 43/// canvas, as iOS wants.
 44func draw(_ v: Variant, _ size: CGFloat, look: Look = .light, fullBleed: Bool = false) -> NSBitmapImageRep {
 45    let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size), pixelsHigh: Int(size), bitsPerSample: 8,
 46                               samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
 47    NSGraphicsContext.saveGraphicsState()
 48    NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
 49    let s = size / 1024
 50    if fullBleed {
 51        let transform = NSAffineTransform()
 52        transform.scale(by: 1024 / 824)
 53        transform.translateX(by: -100 * s, yBy: -100 * s)
 54        transform.concat()
 55    }
 56    let square = NSRect(x: 100 * s, y: 100 * s, width: 824 * s, height: 824 * s)
 57    let shape = fullBleed ? NSBezierPath(rect: square) : NSBezierPath(roundedRect: square, xRadius: 185 * s, yRadius: 185 * s)
 58    // The dark look's background: the light one's colors most of the way to black, light
 59    // ones (Paper, Outline, Pastel) further, so every tile ends up about as dark.
 60    func shade(_ color: NSColor) -> NSColor {
 61        guard look == .dark, let c = color.usingColorSpace(.sRGB) else { return color }
 62        let luminance = 0.2126 * c.redComponent + 0.7152 * c.greenComponent + 0.0722 * c.blueComponent
 63        return c.blended(withFraction: luminance > 0.6 ? 0.8 : 0.7, of: .black)!
 64    }
 65    switch look {
 66    case .light where v.id == "rainbow", .dark where v.id == "rainbow":
 67        NSGraphicsContext.saveGraphicsState()
 68        shape.addClip()
 69        let stripes = [0xe40303, 0xff8c00, 0xffed00, 0x008026, 0x004dff, 0x750787].map(rgb)
 70        let band = square.height / CGFloat(stripes.count)
 71        for (i, color) in stripes.enumerated() {
 72            shade(color).setFill()
 73            NSRect(x: square.minX, y: square.maxY - band * CGFloat(i + 1), width: square.width, height: band).fill()
 74        }
 75        NSGraphicsContext.restoreGraphicsState()
 76    case .light, .dark: NSGradient(colors: [shade(v.top), shade(v.bottom)])!.draw(in: shape, angle: -60)
 77    case .tinted: NSColor.black.setFill(); shape.fill()
 78    }
 79    // On a dark background a dark or mid-tone glyph (Paper, Outline) is drawn light.
 80    func lifted(_ color: NSColor, _ light: CGFloat) -> NSColor {
 81        guard look == .dark, let c = color.usingColorSpace(.sRGB),
 82              0.2126 * c.redComponent + 0.7152 * c.greenComponent + 0.0722 * c.blueComponent < 0.5 else { return color }
 83        return NSColor(white: light, alpha: 1)
 84    }
 85    let glyph = look == .tinted ? NSColor(white: 0.95, alpha: 1) : lifted(v.glyph, 0.95)
 86    let bars = look == .tinted ? NSColor(white: 0.75, alpha: 1) : lifted(v.bars, 0.8)
 87    switch v.style {
 88    case .filled: drawOutline(s, glyph: glyph, bars: bars, filled: true)
 89    case .outline: drawOutline(s, glyph: glyph, bars: bars, filled: false)
 90    case .star: drawStar(s, glyph: glyph)
 91    }
 92    NSGraphicsContext.restoreGraphicsState()
 93    return rep
 94}
 95
 96/// The heading star over three outline lines, indented like a heading's children.
 97func drawOutline(_ s: CGFloat, glyph: NSColor, bars: NSColor, filled: Bool) {
 98    let star = NSAttributedString(string: "✱", attributes: [
 99        .font: NSFont.systemFont(ofSize: 330 * s, weight: filled ? .heavy : .light), .foregroundColor: glyph,
100    ])
101    star.draw(at: NSPoint(x: 190 * s, y: 520 * s))
102    for (i, (x, width)) in [(470.0, 330.0), (300.0, 500.0), (380.0, 420.0)].enumerated() {
103        let y = (650 - Double(i) * 150) * s
104        let line = NSRect(x: x * s, y: y, width: width * s, height: (i == 0 ? 70 : 56) * s)
105        let path = NSBezierPath(roundedRect: line, xRadius: 28 * s, yRadius: 28 * s)
106        if filled {
107            bars.setFill(); path.fill()
108        } else {
109            bars.setStroke(); path.lineWidth = 10 * s; path.stroke()
110        }
111    }
112}
113
114/// The heading star alone, filling the tile: the glyph's outline, centred and scaled to fit.
115func drawStar(_ s: CGFloat, glyph: NSColor) {
116    // The font the system draws ✱ in; the system font itself has no such glyph.
117    let font = CTFontCreateForString(NSFont.systemFont(ofSize: 100, weight: .heavy) as CTFont, "✱" as CFString, CFRange(location: 0, length: 1))
118    var character: UniChar = 0x2731
119    var glyphID: CGGlyph = 0
120    CTFontGetGlyphsForCharacters(font, &character, &glyphID, 1)
121    guard let outline = CTFontCreatePathForGlyph(font, glyphID, nil) else { return }
122    let bounds = outline.boundingBoxOfPath
123    let scale = 560 * s / max(bounds.width, bounds.height)
124    var transform = CGAffineTransform(translationX: 512 * s, y: 512 * s)
125        .scaledBy(x: scale, y: scale)
126        .translatedBy(x: -bounds.midX, y: -bounds.midY)
127    guard let placed = outline.copy(using: &transform), let context = NSGraphicsContext.current?.cgContext else { return }
128    context.addPath(placed)
129    context.setFillColor(glyph.cgColor)
130    context.fillPath()
131}
132
133func png(_ rep: NSBitmapImageRep) -> Data { rep.representation(using: .png, properties: [:])! }
134
135/// Without an alpha channel, as the App Store requires for the light icon.
136func opaque(_ rep: NSBitmapImageRep) -> NSBitmapImageRep {
137    let size = rep.pixelsWide
138    let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: 0,
139                            space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
140    context.draw(rep.cgImage!, in: CGRect(x: 0, y: 0, width: size, height: size))
141    return NSBitmapImageRep(cgImage: context.makeImage()!)
142}
143
144func write(_ data: Data, _ path: String) throws {
145    let url = URL(fileURLWithPath: path)
146    try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
147    try data.write(to: url)
148}
149
150func json(_ object: Any, _ path: String) throws {
151    try write(JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]), path)
152}
153
154let info = ["author": "xcode", "version": 1] as [String: Any]
155let appearances: [(Look, String, [[String: String]])] = [
156    (.light, "", []),
157    (.dark, "-dark", [["appearance": "luminosity", "value": "dark"]]),
158    (.tinted, "-tinted", [["appearance": "luminosity", "value": "tinted"]]),
159]
160
161for v in variants {
162    // iOS: one set per icon, named AppIcon for the default and AppIcon-<Id> for the others.
163    let setName = v.id == "default" ? "AppIcon" : "AppIcon-" + v.id.split(separator: "-").map(\.capitalized).joined()
164    let set = "ios/Orgstar/Assets.xcassets/\(setName).appiconset"
165    var images: [[String: Any]] = []
166    for (look, suffix, appearance) in appearances {
167        let rep = draw(v, 1024, look: look, fullBleed: true)
168        try write(png(look == .light ? opaque(rep) : rep), "\(set)/AppIcon\(suffix).png")
169        var image: [String: Any] = ["filename": "AppIcon\(suffix).png", "idiom": "universal", "platform": "ios", "size": "1024x1024"]
170        if !appearance.isEmpty { image["appearances"] = appearance }
171        images.append(image)
172    }
173    try json(["images": images, "info": info], "\(set)/Contents.json")
174
175    // The iOS picker's preview: the icon in color in both appearances, so each can be told apart.
176    let preview = "ios/Orgstar/Assets.xcassets/IconPreview-\(v.id).imageset"
177    try? FileManager.default.removeItem(atPath: preview)
178    try write(png(draw(v, 256, fullBleed: true)), "\(preview)/light.png")
179    try json(["images": [["filename": "light.png", "idiom": "universal"]], "info": info], "\(preview)/Contents.json")
180
181    // The Mac's Dock icons and picker previews.
182    try write(png(draw(v, 512)), "packaging/IconPreviews/\(v.id)-light.png")
183    try write(png(draw(v, 512, look: .dark)), "packaging/IconPreviews/\(v.id)-dark.png")
184}
185
186// The Mac's bundle icon: the default variant at the Mac's sizes. actool drops dark and
187// tinted renditions from a macOS app icon set, so macOS derives those styles itself.
188let mac = "packaging/AppIcons.xcassets/AppIcon.appiconset"
189try? FileManager.default.removeItem(atPath: mac)
190var macImages: [[String: Any]] = []
191for base in [16, 32, 128, 256, 512] {
192    for scale in [1, 2] {
193        let name = "icon_\(base)x\(base)\(scale == 2 ? "@2x" : "").png"
194        try write(png(draw(variants[0], CGFloat(base * scale))), "\(mac)/\(name)")
195        macImages.append(["filename": name, "idiom": "mac", "scale": "\(scale)x", "size": "\(base)x\(base)"])
196    }
197}
198try json(["images": macImages, "info": info], "\(mac)/Contents.json")
199try json(["info": info], "packaging/AppIcons.xcassets/Contents.json")