scripts/make-icon.swift

90be8b71598bc6efbd9a25b85145d5460cd32616
orgstar/scripts/make-icon.swift

212 lines · 11474 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
 38enum Look { case light, dark, tinted }
 39
 40/// The macOS icon grid: an 824-point rounded square in a 1024 canvas; `fullBleed` fills the
 41/// canvas, as iOS wants. Dark and tinted leave the background clear (dark) or black (tinted)
 42/// for the system to fill.
 43func draw(_ v: Variant, _ size: CGFloat, look: Look = .light, fullBleed: Bool = false) -> NSBitmapImageRep {
 44    let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size), pixelsHigh: Int(size), bitsPerSample: 8,
 45                               samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
 46    NSGraphicsContext.saveGraphicsState()
 47    NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
 48    let s = size / 1024
 49    if fullBleed {
 50        let transform = NSAffineTransform()
 51        transform.scale(by: 1024 / 824)
 52        transform.translateX(by: -100 * s, yBy: -100 * s)
 53        transform.concat()
 54    }
 55    let square = NSRect(x: 100 * s, y: 100 * s, width: 824 * s, height: 824 * s)
 56    let shape = fullBleed ? NSBezierPath(rect: square) : NSBezierPath(roundedRect: square, xRadius: 185 * s, yRadius: 185 * s)
 57    switch look {
 58    case .light where v.id == "rainbow":
 59        NSGraphicsContext.saveGraphicsState()
 60        shape.addClip()
 61        let stripes = [0xe40303, 0xff8c00, 0xffed00, 0x008026, 0x004dff, 0x750787].map(rgb)
 62        let band = square.height / CGFloat(stripes.count)
 63        for (i, color) in stripes.enumerated() {
 64            color.setFill()
 65            NSRect(x: square.minX, y: square.maxY - band * CGFloat(i + 1), width: square.width, height: band).fill()
 66        }
 67        NSGraphicsContext.restoreGraphicsState()
 68    case .light: NSGradient(colors: [v.top, v.bottom])!.draw(in: shape, angle: -60)
 69    case .dark: break
 70    case .tinted: NSColor.black.setFill(); shape.fill()
 71    }
 72    let glyph = look == .tinted ? NSColor(white: 0.95, alpha: 1) : v.glyph
 73    let bars = look == .tinted ? NSColor(white: 0.75, alpha: 1) : v.bars
 74    switch v.style {
 75    case .filled: drawOutline(s, glyph: glyph, bars: bars, filled: true)
 76    case .outline: drawOutline(s, glyph: glyph, bars: bars, filled: false)
 77    case .unicorn: drawUnicorn(s, glyph: glyph, head: bars)
 78    }
 79    NSGraphicsContext.restoreGraphicsState()
 80    return rep
 81}
 82
 83/// The heading star over three outline lines, indented like a heading's children.
 84func drawOutline(_ s: CGFloat, glyph: NSColor, bars: NSColor, filled: Bool) {
 85    let star = NSAttributedString(string: "✱", attributes: [
 86        .font: NSFont.systemFont(ofSize: 330 * s, weight: filled ? .heavy : .light), .foregroundColor: glyph,
 87    ])
 88    star.draw(at: NSPoint(x: 190 * s, y: 520 * s))
 89    for (i, (x, width)) in [(470.0, 330.0), (300.0, 500.0), (380.0, 420.0)].enumerated() {
 90        let y = (650 - Double(i) * 150) * s
 91        let line = NSRect(x: x * s, y: y, width: width * s, height: (i == 0 ? 70 : 56) * s)
 92        let path = NSBezierPath(roundedRect: line, xRadius: 28 * s, yRadius: 28 * s)
 93        if filled {
 94            bars.setFill(); path.fill()
 95        } else {
 96            bars.setStroke(); path.lineWidth = 10 * s; path.stroke()
 97        }
 98    }
 99}
100
101/// A unicorn's head in profile, facing left, with a mane; its horn ends in the heading star.
102func drawUnicorn(_ s: CGFloat, glyph: NSColor, head: NSColor) {
103    func p(_ x: CGFloat, _ y: CGFloat) -> NSPoint { NSPoint(x: x * s, y: y * s) }
104    let face = NSBezierPath()
105    face.move(to: p(640, 200))                                                    // neck, back
106    face.curve(to: p(600, 560), controlPoint1: p(700, 330), controlPoint2: p(690, 480))
107    face.curve(to: p(470, 640), controlPoint1: p(560, 610), controlPoint2: p(520, 640))  // crown
108    face.line(to: p(440, 690))                                                    // ear
109    face.line(to: p(410, 620))
110    face.curve(to: p(250, 470), controlPoint1: p(340, 590), controlPoint2: p(270, 530))  // brow to nose
111    face.curve(to: p(290, 400), controlPoint1: p(235, 430), controlPoint2: p(250, 400))  // muzzle
112    face.curve(to: p(430, 430), controlPoint1: p(340, 400), controlPoint2: p(390, 410))  // jaw
113    face.curve(to: p(450, 200), controlPoint1: p(470, 360), controlPoint2: p(440, 280))  // throat
114    face.close()
115    head.setFill()
116    face.fill()
117
118    let mane = NSBezierPath()
119    mane.move(to: p(600, 560))
120    mane.curve(to: p(760, 220), controlPoint1: p(720, 520), controlPoint2: p(800, 360))
121    mane.line(to: p(690, 210))
122    mane.curve(to: p(600, 520), controlPoint1: p(730, 330), controlPoint2: p(680, 470))
123    mane.close()
124    glyph.withAlphaComponent(0.85).setFill()
125    mane.fill()
126
127    let horn = NSBezierPath()
128    horn.move(to: p(440, 640))
129    horn.line(to: p(300, 790))
130    horn.line(to: p(475, 660))
131    horn.close()
132    head.blended(withFraction: 0.25, of: glyph)?.setFill()
133    horn.fill()
134
135    let eye = NSBezierPath(ovalIn: NSRect(x: 360 * s, y: 520 * s, width: 28 * s, height: 28 * s))
136    NSColor(white: 0.15, alpha: 1).setFill()
137    eye.fill()
138
139    let star = NSAttributedString(string: "✱", attributes: [.font: NSFont.systemFont(ofSize: 190 * s, weight: .heavy), .foregroundColor: glyph])
140    star.draw(at: p(205, 700))
141}
142
143func png(_ rep: NSBitmapImageRep) -> Data { rep.representation(using: .png, properties: [:])! }
144
145/// Without an alpha channel, as the App Store requires for the light icon.
146func opaque(_ rep: NSBitmapImageRep) -> NSBitmapImageRep {
147    let size = rep.pixelsWide
148    let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: 0,
149                            space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
150    context.draw(rep.cgImage!, in: CGRect(x: 0, y: 0, width: size, height: size))
151    return NSBitmapImageRep(cgImage: context.makeImage()!)
152}
153
154func write(_ data: Data, _ path: String) throws {
155    let url = URL(fileURLWithPath: path)
156    try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
157    try data.write(to: url)
158}
159
160func json(_ object: Any, _ path: String) throws {
161    try write(JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]), path)
162}
163
164let info = ["author": "xcode", "version": 1] as [String: Any]
165let appearances: [(Look, String, [[String: String]])] = [
166    (.light, "", []),
167    (.dark, "-dark", [["appearance": "luminosity", "value": "dark"]]),
168    (.tinted, "-tinted", [["appearance": "luminosity", "value": "tinted"]]),
169]
170
171for v in variants {
172    // iOS: one set per icon, named AppIcon for the default and AppIcon-<Id> for the others.
173    let setName = v.id == "default" ? "AppIcon" : "AppIcon-" + v.id.split(separator: "-").map(\.capitalized).joined()
174    let set = "ios/Orgstar/Assets.xcassets/\(setName).appiconset"
175    var images: [[String: Any]] = []
176    for (look, suffix, appearance) in appearances {
177        let rep = draw(v, 1024, look: look, fullBleed: true)
178        try write(png(look == .light ? opaque(rep) : rep), "\(set)/AppIcon\(suffix).png")
179        var image: [String: Any] = ["filename": "AppIcon\(suffix).png", "idiom": "universal", "platform": "ios", "size": "1024x1024"]
180        if !appearance.isEmpty { image["appearances"] = appearance }
181        images.append(image)
182    }
183    try json(["images": images, "info": info], "\(set)/Contents.json")
184
185    // Previews for the iOS picker, light and dark.
186    let preview = "ios/Orgstar/Assets.xcassets/IconPreview-\(v.id).imageset"
187    try write(png(draw(v, 256, fullBleed: true)), "\(preview)/light.png")
188    try write(png(draw(v, 256, look: .dark, fullBleed: true)), "\(preview)/dark.png")
189    try json(["images": [
190        ["filename": "light.png", "idiom": "universal"],
191        ["filename": "dark.png", "idiom": "universal", "appearances": [["appearance": "luminosity", "value": "dark"]]],
192    ], "info": info], "\(preview)/Contents.json")
193
194    // The Mac's Dock icons and picker previews.
195    try write(png(draw(v, 512)), "packaging/IconPreviews/\(v.id)-light.png")
196    try write(png(draw(v, 512, look: .dark)), "packaging/IconPreviews/\(v.id)-dark.png")
197}
198
199// The Mac's bundle icon: the default variant at the Mac's sizes. actool drops dark and
200// tinted renditions from a macOS app icon set, so macOS derives those styles itself.
201let mac = "packaging/AppIcons.xcassets/AppIcon.appiconset"
202try? FileManager.default.removeItem(atPath: mac)
203var macImages: [[String: Any]] = []
204for base in [16, 32, 128, 256, 512] {
205    for scale in [1, 2] {
206        let name = "icon_\(base)x\(base)\(scale == 2 ? "@2x" : "").png"
207        try write(png(draw(variants[0], CGFloat(base * scale))), "\(mac)/\(name)")
208        macImages.append(["filename": name, "idiom": "mac", "scale": "\(scale)x", "size": "\(base)x\(base)"])
209    }
210}
211try json(["images": macImages, "info": info], "\(mac)/Contents.json")
212try 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