From 4d623c58a4804068a9ed01fe799ec2fa804b1cb2 Mon Sep 17 00:00:00 2001 From: ShikiSuen Date: Fri, 10 Nov 2023 00:11:47 +0800 Subject: [PATCH] CocoaImpl // Add API for finding accent colors. --- .../CocoaExtension/CocoaExtension_Misc.swift | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/Packages/vChewing_CocoaExtension/Sources/CocoaExtension/CocoaExtension_Misc.swift b/Packages/vChewing_CocoaExtension/Sources/CocoaExtension/CocoaExtension_Misc.swift index a4e533c2..93f3692a 100644 --- a/Packages/vChewing_CocoaExtension/Sources/CocoaExtension/CocoaExtension_Misc.swift +++ b/Packages/vChewing_CocoaExtension/Sources/CocoaExtension/CocoaExtension_Misc.swift @@ -284,3 +284,38 @@ public extension NSApplication { #endif } } + +// MARK: - Reading bundle's accent color. + +public extension NSColor { + static var accentColor: NSColor { + guard #unavailable(macOS 10.14) else { return .controlAccentColor } + return .alternateSelectedControlColor + } +} + +public extension Bundle { + func getAccentColor() -> NSColor { + let defaultResult: NSColor = .accentColor + let queryPhrase = localizedInfoDictionary?["NSAccentColorName"] as? String ?? infoDictionary?["NSAccentColorName"] as? String + guard let queryPhrase = queryPhrase, !queryPhrase.isEmpty else { return defaultResult } + guard #available(macOS 10.13, *) else { return defaultResult } + return NSColor(named: queryPhrase, bundle: self) ?? defaultResult + } +} + +public extension NSRunningApplication { + private static var temporatyBundlePtr: Bundle? + + static func findAccentColor(with bundleIdentifier: String) -> NSColor { + let matchedRunningApps = Self.runningApplications(withBundleIdentifier: bundleIdentifier) + guard let matchedAppURL = matchedRunningApps.first?.bundleURL else { return .accentColor } + Self.temporatyBundlePtr = Bundle(url: matchedAppURL) + defer { temporatyBundlePtr = nil } + let bundleColor = Self.temporatyBundlePtr?.getAccentColor().usingColorSpace(.deviceRGB) + guard let bundleColor = bundleColor else { return .accentColor } + let h = bundleColor.hueComponent + let s = bundleColor.saturationComponent + return .init(hue: h, saturation: s, brightness: 128, alpha: 1) + } +}