scripts/make-icon.swift

9cdca8a9038566b0fa3d938ef84193a033449b76
orgstar/scripts/make-icon.swift

198 lines · 11181 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/// `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 .star: drawStar(s, glyph: glyph)
 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/// The heading star alone, filling the tile: the glyph's outline, centred and scaled to fit.
111func drawStar(_ s: CGFloat, glyph: NSColor) {
112    // The font the system draws ✱ in; the system font itself has no such glyph.
113    let font = CTFontCreateForString(NSFont.systemFont(ofSize: 100, weight: .heavy) as CTFont, "✱" as CFString, CFRange(location: 0, length: 1))
114    var character: UniChar = 0x2731
115    var glyphID: CGGlyph = 0
116    CTFontGetGlyphsForCharacters(font, &character, &glyphID, 1)
117    guard let outline = CTFontCreatePathForGlyph(font, glyphID, nil) else { return }
118    let bounds = outline.boundingBoxOfPath
119    let scale = 560 * s / max(bounds.width, bounds.height)
120    var transform = CGAffineTransform(translationX: 512 * s, y: 512 * s)
121        .scaledBy(x: scale, y: scale)
122        .translatedBy(x: -bounds.midX, y: -bounds.midY)
123    guard let placed = outline.copy(using: &transform), let context = NSGraphicsContext.current?.cgContext else { return }
124    context.addPath(placed)
125    context.setFillColor(glyph.cgColor)
126    context.fillPath()
127}
128
129func png(_ rep: NSBitmapImageRep) -> Data { rep.representation(using: .png, properties: [:])! }
130
131/// Without an alpha channel, as the App Store requires for the light icon.
132func opaque(_ rep: NSBitmapImageRep) -> NSBitmapImageRep {
133    let size = rep.pixelsWide
134    let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: 0,
135                            space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
136    context.draw(rep.cgImage!, in: CGRect(x: 0, y: 0, width: size, height: size))
137    return NSBitmapImageRep(cgImage: context.makeImage()!)
138}
139
140func write(_ data: Data, _ path: String) throws {
141    let url = URL(fileURLWithPath: path)
142    try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
143    try data.write(to: url)
144}
145
146func json(_ object: Any, _ path: String) throws {
147    try write(JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]), path)
148}
149
150let info = ["author": "xcode", "version": 1] as [String: Any]
151let appearances: [(Look, String, [[String: String]])] = [
152    (.light, "", []),
153    (.dark, "-dark", [["appearance": "luminosity", "value": "dark"]]),
154    (.tinted, "-tinted", [["appearance": "luminosity", "value": "tinted"]]),
155]
156
157for v in variants {
158    // iOS: one set per icon, named AppIcon for the default and AppIcon-<Id> for the others.
159    let setName = v.id == "default" ? "AppIcon" : "AppIcon-" + v.id.split(separator: "-").map(\.capitalized).joined()
160    let set = "ios/Orgstar/Assets.xcassets/\(setName).appiconset"
161    var images: [[String: Any]] = []
162    for (look, suffix, appearance) in appearances {
163        let rep = draw(v, 1024, look: look, fullBleed: true)
164        try write(png(look == .light ? opaque(rep) : rep), "\(set)/AppIcon\(suffix).png")
165        var image: [String: Any] = ["filename": "AppIcon\(suffix).png", "idiom": "universal", "platform": "ios", "size": "1024x1024"]
166        if !appearance.isEmpty { image["appearances"] = appearance }
167        images.append(image)
168    }
169    try json(["images": images, "info": info], "\(set)/Contents.json")
170
171    // Previews for the iOS picker, light and dark.
172    let preview = "ios/Orgstar/Assets.xcassets/IconPreview-\(v.id).imageset"
173    try write(png(draw(v, 256, fullBleed: true)), "\(preview)/light.png")
174    try write(png(draw(v, 256, look: .dark, fullBleed: true)), "\(preview)/dark.png")
175    try json(["images": [
176        ["filename": "light.png", "idiom": "universal"],
177        ["filename": "dark.png", "idiom": "universal", "appearances": [["appearance": "luminosity", "value": "dark"]]],
178    ], "info": info], "\(preview)/Contents.json")
179
180    // The Mac's Dock icons and picker previews.
181    try write(png(draw(v, 512)), "packaging/IconPreviews/\(v.id)-light.png")
182    try write(png(draw(v, 512, look: .darkTile)), "packaging/IconPreviews/\(v.id)-dark.png")
183}
184
185// The Mac's bundle icon: the default variant at the Mac's sizes. actool drops dark and
186// tinted renditions from a macOS app icon set, so macOS derives those styles itself.
187let mac = "packaging/AppIcons.xcassets/AppIcon.appiconset"
188try? FileManager.default.removeItem(atPath: mac)
189var macImages: [[String: Any]] = []
190for base in [16, 32, 128, 256, 512] {
191    for scale in [1, 2] {
192        let name = "icon_\(base)x\(base)\(scale == 2 ? "@2x" : "").png"
193        try write(png(draw(variants[0], CGFloat(base * scale))), "\(mac)/\(name)")
194        macImages.append(["filename": name, "idiom": "mac", "scale": "\(scale)x", "size": "\(base)x\(base)"])
195    }
196}
197try json(["images": macImages, "info": info], "\(mac)/Contents.json")
198try json(["info": info], "packaging/AppIcons.xcassets/Contents.json")
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form