public import AppKit import ParcelAnimation public import ParcelConfig public struct MiniMapTile: Equatable, Sendable { public let id: UInt64 public var frame: CGRect public let isFocused: Bool } public enum MenuIcon: Equatable, Sendable { case tiles([MiniMapTile]) case logo(count: Int?) public init(snapshot: LayoutSnapshot, style: ConfigMenuBarIcon) { guard style == .minimap, !snapshot.tiles.isEmpty, snapshot.tiles.count <= 6 else { self = .logo(count: snapshot.tiles.count > 6 ? snapshot.tiles.count : nil) return } let scale = min(14 / snapshot.bounds.width, 14 / snapshot.bounds.height) let offsetX = (18 - snapshot.bounds.width * scale) / 2 let offsetY = (18 - snapshot.bounds.height * scale) / 2 self = .tiles( snapshot.tiles.compactMap { tile in let clipped = tile.frame.intersection(snapshot.bounds) guard !clipped.isNull, !clipped.isEmpty else { return nil } let frame = CGRect( x: offsetX + (clipped.minX - snapshot.bounds.minX) * scale, y: offsetY + (clipped.minY - snapshot.bounds.minY) * scale, width: clipped.width * scale, height: clipped.height * scale ) let inset = min(0.5, frame.width / 4, frame.height / 4) return MiniMapTile(id: tile.id, frame: frame.insetBy(dx: inset, dy: inset), isFocused: tile.isFocused) }) } } public struct MiniMapMorph: Sendable { public private(set) var current: MenuIcon public private(set) var target: MenuIcon public private(set) var remainingFrames = 0 public private(set) var frameInterval = 0.0 private var frameCount = 0 private var spring = MotionToken.glance.spec().spring private var velocities: [UInt64: [Double]] = [:] public init(icon: MenuIcon) { current = icon target = icon } @discardableResult public mutating func retarget( _ icon: MenuIcon, configuration: MotionConfiguration, reduceMotion: Bool, visible: Bool ) -> Bool { let policy = MotionPolicy(enabled: configuration.enabled, reduceMotion: reduceMotion) let animate = visible && policy.behavior(for: .miniMap) == .animate if icon == target && (animate || remainingFrames == 0) { return false } target = icon guard animate, current != icon, case .tiles(let previous) = current, case .tiles(let next) = icon, !previous.isEmpty, !next.isEmpty else { current = icon remainingFrames = 0 velocities = [:] return true } let spec = MotionToken.glance.spec(settings: configuration.uiMotionSettings) remainingFrames = min(10, spec.maximumRedraws ?? 10) frameCount = remainingFrames frameInterval = spec.duration / Double(remainingFrames) spring = spec.spring let old = Dictionary(uniqueKeysWithValues: previous.map { ($0.id, $0) }) current = .tiles( next.map { tile in MiniMapTile(id: tile.id, frame: old[tile.id]?.frame ?? tile.frame, isFocused: tile.isFocused) }) velocities = velocities.filter { id, _ in next.contains { $0.id == id } } return true } public mutating func finish() { current = target remainingFrames = 0 velocities = [:] } @discardableResult public mutating func sample(at elapsed: Double) -> MenuIcon { precondition(elapsed.isFinite && elapsed >= 0) guard remainingFrames > 0 else { return current } let due = Int(min(Double(frameCount), elapsed / frameInterval)) while frameCount - remainingFrames < due { advance() } return current } @discardableResult public mutating func advance() -> MenuIcon { guard remainingFrames > 0, case .tiles(let previous) = current, case .tiles(let next) = target else { return current } remainingFrames -= 1 guard remainingFrames > 0 else { current = target velocities = [:] return current } current = .tiles( zip(previous, next).map { old, destination in let start = [old.frame.minX, old.frame.minY, old.frame.width, old.frame.height] let end = [ destination.frame.minX, destination.frame.minY, destination.frame.width, destination.frame.height, ] let speed = velocities[old.id] ?? [0, 0, 0, 0] let values = start.indices.map { index in SpringState(value: start[index], velocity: speed[index]) .advanced(to: end[index], by: frameInterval, using: spring) } velocities[old.id] = values.map(\.velocity) return MiniMapTile( id: destination.id, frame: CGRect( x: values[0].value, y: values[1].value, width: max(0.1, values[2].value), height: max(0.1, values[3].value)), isFocused: destination.isFocused ) }) return current } } extension MotionConfiguration { var uiMotionSettings: MotionSettings { let whimsy: WhimsyLevel switch level { case .calm: whimsy = .calm case .playful: whimsy = .playful case .extra: whimsy = .extra } return MotionSettings(level: whimsy, speedMultiplier: speed) } } @MainActor public enum BrandAssets { public static func keystone() throws -> NSImage { try load("Keystone") } public static func split() throws -> NSImage { let image = try load("Split") image.isTemplate = true return image } private static func load(_ name: String) throws -> NSImage { guard let url = Bundle.module.url(forResource: name, withExtension: "svg"), let image = NSImage(contentsOf: url) else { throw UIResourceError.missingBrand(name) } return image } } public enum UIResourceError: LocalizedError { case missingBrand(String) case renderingFailed public var errorDescription: String? { switch self { case .missingBrand(let name): String(format: UIStrings.text("The %@ artwork could not be loaded."), name) case .renderingFailed: UIStrings.text("The menu icon could not be rendered.") } } } @MainActor public final class MenuIconRenderer { private struct Tile: Hashable, Sendable { let x: CGFloat let y: CGFloat let width: CGFloat let height: CGFloat let isFocused: Bool init(_ tile: MiniMapTile) { x = tile.frame.origin.x y = tile.frame.origin.y width = tile.frame.size.width height = tile.frame.size.height isFocused = tile.isFocused } var frame: CGRect { CGRect(x: x, y: y, width: width, height: height) } } private enum Content: Hashable, Sendable { case tiles([Tile]) case logo(String?) init(_ icon: MenuIcon, locale: Locale) { switch icon { case .tiles(let tiles): self = .tiles(tiles.map(Tile.init)) case .logo(let count): self = .logo(count.map { $0 > 99 ? UIStrings.text("99+") : $0.formatted(.number.locale(locale)) }) } } } private struct Key: Hashable { let content: Content let increaseContrast: Bool let cleanSpace: Bool let updateReady: Bool let appearance: NSAppearance.Name let pixels: Int } private struct Raster { let image: NSImage let bitmap: NSBitmapImageRep } private let logo: NSImage private let cacheCapacity: Int private var cache: [Key: Raster] = [:] private var insertionOrder: [Key] = [] public convenience init() throws { try self.init(cacheCapacity: 128) } init(cacheCapacity: Int) throws { precondition(cacheCapacity > 0) self.cacheCapacity = cacheCapacity logo = try BrandAssets.split() } public func image( for icon: MenuIcon, increaseContrast: Bool = false, appearance: NSAppearance? = nil, scale: CGFloat = 1, locale: Locale = .current, cleanSpace: Bool = false, updateReady: Bool = false ) -> NSImage { do { return try raster( for: icon, increaseContrast: increaseContrast, appearance: appearance, scale: scale, locale: locale, cleanSpace: cleanSpace, updateReady: updateReady ).image } catch { preconditionFailure("The menu icon could not be rendered: \(error)") } } func invalidate() { cache.removeAll(keepingCapacity: true) insertionOrder.removeAll(keepingCapacity: true) } public func png(for icon: MenuIcon, scale: Int = 2, increaseContrast: Bool = false) throws -> Data { let raster = try raster( for: icon, increaseContrast: increaseContrast, appearance: nil, scale: CGFloat(scale), locale: .current, cleanSpace: false, updateReady: false) guard let data = raster.bitmap.representation(using: .png, properties: [:]) else { throw UIResourceError.renderingFailed } return data } private func raster( for icon: MenuIcon, increaseContrast: Bool, appearance: NSAppearance?, scale: CGFloat, locale: Locale, cleanSpace: Bool, updateReady: Bool ) throws -> Raster { precondition(scale.isFinite && (1...4).contains(scale)) let appearance = appearance ?? NSAppearance.currentDrawing() let key = Key( content: Content(icon, locale: locale), increaseContrast: increaseContrast, cleanSpace: cleanSpace, updateReady: updateReady, appearance: appearance.name, pixels: Int(ceil(18 * scale))) if let raster = cache[key] { return raster } let raster = try render(key, appearance: appearance) if insertionOrder.count == cacheCapacity { cache.removeValue(forKey: insertionOrder.removeFirst()) } insertionOrder.append(key) cache[key] = raster return raster } private func render(_ key: Key, appearance: NSAppearance) throws -> Raster { guard let bitmap = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: key.pixels, pixelsHigh: key.pixels, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0 ), let context = NSGraphicsContext(bitmapImageRep: bitmap) else { throw UIResourceError.renderingFailed } NSGraphicsContext.saveGraphicsState() defer { NSGraphicsContext.restoreGraphicsState() } let scale = CGFloat(key.pixels) / 18 context.cgContext.translateBy(x: 0, y: CGFloat(key.pixels)) context.cgContext.scaleBy(x: scale, y: -scale) NSGraphicsContext.current = NSGraphicsContext(cgContext: context.cgContext, flipped: true) appearance.performAsCurrentDrawingAppearance { NSColor.black.set() let marked = key.cleanSpace || key.updateReady context.cgContext.saveGState() if marked { context.cgContext.translateBy(x: 2, y: 0) context.cgContext.scaleBy(x: 0.78, y: 0.78) } switch key.content { case .tiles(let tiles): for tile in tiles { let path = NSBezierPath(roundedRect: tile.frame, xRadius: 0.8, yRadius: 0.8) if tile.isFocused { path.fill() } else { path.lineWidth = key.increaseContrast ? 1.3 : 0.85 path.stroke() } } case .logo(let label): if let label { logo.draw(in: CGRect(x: 0, y: 0, width: 12, height: 12)) let attributes: [NSAttributedString.Key: NSObject] = [ .font: NSFont.monospacedDigitSystemFont(ofSize: 7, weight: .bold), .foregroundColor: NSColor.black, ] let text = NSAttributedString(string: label, attributes: attributes) text.draw(at: CGPoint(x: max(0, 18 - text.size().width), y: 10)) } else { logo.draw(in: CGRect(x: 0, y: 0, width: 18, height: 18)) } } context.cgContext.restoreGState() if key.cleanSpace { let mark = NSBezierPath( roundedRect: CGRect(x: 3, y: 14.5, width: 3, height: 3), xRadius: 0.5, yRadius: 0.5) mark.lineWidth = key.increaseContrast ? 1.2 : 0.9 mark.stroke() } if key.updateReady { NSBezierPath(ovalIn: CGRect(x: 12, y: 14.5, width: 3, height: 3)).fill() } } bitmap.size = NSSize(width: 18, height: 18) let image = NSImage(size: bitmap.size) image.addRepresentation(bitmap) image.isTemplate = true return Raster(image: image, bitmap: bitmap) } }