|
| 1 | +import AppKit |
| 2 | +import CoreGraphics |
| 3 | +import SwiftUI |
| 4 | + |
| 5 | +/// Extracts dominant colors from images for UI accent backgrounds. |
| 6 | +enum ColorExtractor { |
| 7 | + /// Represents a weighted color sample for averaging. |
| 8 | + private struct WeightedColor { |
| 9 | + let red: CGFloat |
| 10 | + let green: CGFloat |
| 11 | + let blue: CGFloat |
| 12 | + let weight: CGFloat |
| 13 | + } |
| 14 | + |
| 15 | + /// Represents extracted color palette from an image. |
| 16 | + struct ColorPalette: Equatable, Sendable { |
| 17 | + let primary: Color |
| 18 | + let secondary: Color |
| 19 | + |
| 20 | + /// Default dark palette when no image is available. |
| 21 | + static let `default` = ColorPalette( |
| 22 | + primary: Color(nsColor: NSColor(white: 0.1, alpha: 1)), |
| 23 | + secondary: Color(nsColor: NSColor(white: 0.05, alpha: 1)) |
| 24 | + ) |
| 25 | + } |
| 26 | + |
| 27 | + /// Extracts a color palette from an NSImage. |
| 28 | + /// Uses k-means clustering on downsampled image for performance. |
| 29 | + /// - Parameter image: The source image. |
| 30 | + /// - Returns: A ColorPalette with primary and secondary colors. |
| 31 | + static func extractPalette(from image: NSImage) -> ColorPalette { |
| 32 | + guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { |
| 33 | + return .default |
| 34 | + } |
| 35 | + |
| 36 | + // Downsample for performance (8x8 is enough for dominant color) |
| 37 | + let sampleSize = 8 |
| 38 | + guard let context = createBitmapContext(width: sampleSize, height: sampleSize) else { |
| 39 | + return .default |
| 40 | + } |
| 41 | + |
| 42 | + context.interpolationQuality = .medium |
| 43 | + context.draw(cgImage, in: CGRect(x: 0, y: 0, width: sampleSize, height: sampleSize)) |
| 44 | + |
| 45 | + guard let data = context.data else { |
| 46 | + return .default |
| 47 | + } |
| 48 | + |
| 49 | + let pointer = data.bindMemory(to: UInt8.self, capacity: sampleSize * sampleSize * 4) |
| 50 | + var colors: [WeightedColor] = [] |
| 51 | + |
| 52 | + // Sample pixels |
| 53 | + for yCoord in 0..<sampleSize { |
| 54 | + for xCoord in 0..<sampleSize { |
| 55 | + let offset = (yCoord * sampleSize + xCoord) * 4 |
| 56 | + let red = CGFloat(pointer[offset]) / 255.0 |
| 57 | + let green = CGFloat(pointer[offset + 1]) / 255.0 |
| 58 | + let blue = CGFloat(pointer[offset + 2]) / 255.0 |
| 59 | + |
| 60 | + // Weight by saturation and avoid near-black/white pixels |
| 61 | + let maxC = max(red, green, blue) |
| 62 | + let minC = min(red, green, blue) |
| 63 | + let saturation = maxC > 0 ? (maxC - minC) / maxC : 0 |
| 64 | + let brightness = maxC |
| 65 | + |
| 66 | + // Skip very dark or very light pixels |
| 67 | + if brightness > 0.1 && brightness < 0.95 { |
| 68 | + let weight = saturation * 0.7 + 0.3 |
| 69 | + colors.append(WeightedColor(red: red, green: green, blue: blue, weight: weight)) |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + // Find dominant color using weighted average |
| 75 | + guard !colors.isEmpty else { |
| 76 | + return .default |
| 77 | + } |
| 78 | + |
| 79 | + let totalWeight = colors.reduce(0) { $0 + $1.weight } |
| 80 | + guard totalWeight > 0 else { |
| 81 | + return .default |
| 82 | + } |
| 83 | + |
| 84 | + let avgR = colors.reduce(0) { $0 + $1.red * $1.weight } / totalWeight |
| 85 | + let avgG = colors.reduce(0) { $0 + $1.green * $1.weight } / totalWeight |
| 86 | + let avgB = colors.reduce(0) { $0 + $1.blue * $1.weight } / totalWeight |
| 87 | + |
| 88 | + // Create primary color (saturated and darker for background) |
| 89 | + let primary = adjustColorForBackground(r: avgR, g: avgG, b: avgB, darken: 0.4) |
| 90 | + |
| 91 | + // Create secondary color (even darker for gradient end) |
| 92 | + let secondary = adjustColorForBackground(r: avgR, g: avgG, b: avgB, darken: 0.7) |
| 93 | + |
| 94 | + return ColorPalette( |
| 95 | + primary: Color(nsColor: primary), |
| 96 | + secondary: Color(nsColor: secondary) |
| 97 | + ) |
| 98 | + } |
| 99 | + |
| 100 | + /// Extracts palette from image data off the main actor. |
| 101 | + /// - Parameter data: Raw image data. |
| 102 | + /// - Returns: Extracted color palette. |
| 103 | + @MainActor |
| 104 | + static func extractPalette(from data: Data) async -> ColorPalette { |
| 105 | + await Task.detached(priority: .userInitiated) { |
| 106 | + guard let image = NSImage(data: data) else { |
| 107 | + return ColorPalette.default |
| 108 | + } |
| 109 | + return extractPalette(from: image) |
| 110 | + }.value |
| 111 | + } |
| 112 | + |
| 113 | + // MARK: - Private Helpers |
| 114 | + |
| 115 | + private static func createBitmapContext(width: Int, height: Int) -> CGContext? { |
| 116 | + CGContext( |
| 117 | + data: nil, |
| 118 | + width: width, |
| 119 | + height: height, |
| 120 | + bitsPerComponent: 8, |
| 121 | + bytesPerRow: width * 4, |
| 122 | + space: CGColorSpaceCreateDeviceRGB(), |
| 123 | + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue |
| 124 | + ) |
| 125 | + } |
| 126 | + |
| 127 | + private static func adjustColorForBackground( |
| 128 | + r: CGFloat, |
| 129 | + g: CGFloat, |
| 130 | + b: CGFloat, |
| 131 | + darken: CGFloat |
| 132 | + ) -> NSColor { |
| 133 | + // Convert to HSB for easier manipulation |
| 134 | + let nsColor = NSColor(red: r, green: g, blue: b, alpha: 1.0) |
| 135 | + var hue: CGFloat = 0 |
| 136 | + var saturation: CGFloat = 0 |
| 137 | + var brightness: CGFloat = 0 |
| 138 | + var alpha: CGFloat = 0 |
| 139 | + |
| 140 | + nsColor.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) |
| 141 | + |
| 142 | + // Increase saturation slightly and darken significantly |
| 143 | + let adjustedSaturation = min(saturation * 1.2, 1.0) |
| 144 | + let adjustedBrightness = brightness * (1 - darken) |
| 145 | + |
| 146 | + return NSColor( |
| 147 | + hue: hue, |
| 148 | + saturation: adjustedSaturation, |
| 149 | + brightness: max(adjustedBrightness, 0.05), |
| 150 | + alpha: 1.0 |
| 151 | + ) |
| 152 | + } |
| 153 | +} |
0 commit comments