Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
public import AppKit
public import Foundation
public import SwiftUI

/// The one accent for cmux-drawn chrome: the color that means "this is the
Expand All @@ -23,22 +24,46 @@ public struct CmuxAccentColor: Sendable, Hashable {

public let mode: CmuxAccentColorMode

/// Normalized `#RRGGBB` color drawn in ``CmuxAccentColorMode/custom``
/// mode. `nil` there falls back to cmux blue.
public let customHex: String?

public init(mode: CmuxAccentColorMode = .defaultValue) {
self.init(mode: mode, customHex: nil)
}

public init(mode: CmuxAccentColorMode, customHex: String?) {
self.mode = mode
self.customHex = CmuxAccentColorMode.normalizedCustomHex(customHex)
}

/// The accent stored in `defaults` (`app.accentColor`).
public static func stored(in defaults: UserDefaults = .standard) -> CmuxAccentColor {
CmuxAccentColor(
mode: .stored(in: defaults),
customHex: CmuxAccentColorMode.storedCustomHex(in: defaults)
)
}

/// cmux's own blue for a light or dark appearance.
public static func cmuxBlue(isDark: Bool) -> NSColor {
NSColor(
srgbRed: 0,
green: (isDark ? 145.0 : 136.0) / 255.0,
blue: 1.0,
alpha: 1.0
)
}

/// The accent for a light or dark appearance.
public func nsColor(isDark: Bool) -> NSColor {
switch mode {
case .cmux:
return NSColor(
srgbRed: 0,
green: (isDark ? 145.0 : 136.0) / 255.0,
blue: 1.0,
alpha: 1.0
)
return Self.cmuxBlue(isDark: isDark)
case .system:
return Self.systemAccent(isDark: isDark)
case .custom:
return customHex.flatMap { NSColor(hex: $0) } ?? Self.cmuxBlue(isDark: isDark)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@ public enum CmuxAccentColorMode: String, CaseIterable, Sendable {
case cmux
/// The macOS accent color from System Settings > Appearance.
case system
/// A user-chosen color stored under ``customHexUserDefaultsKey``.
case custom

/// UserDefaults key storing the raw value.
public static let userDefaultsKey = "appAccentColor"

/// UserDefaults key storing the `#RRGGBB` color for ``custom``.
public static let customHexUserDefaultsKey = "appAccentColorCustomHex"

/// Mode used when nothing valid is stored.
public static let defaultValue: CmuxAccentColorMode = .cmux

Expand All @@ -19,4 +24,19 @@ public enum CmuxAccentColorMode: String, CaseIterable, Sendable {
public static func stored(in defaults: UserDefaults = .standard) -> CmuxAccentColorMode {
CmuxAccentColorMode(rawValue: defaults.string(forKey: userDefaultsKey) ?? "") ?? defaultValue
}

/// Reads the stored custom color, or `nil` when it is missing or not a
/// valid `#RRGGBB` hex.
public static func storedCustomHex(in defaults: UserDefaults = .standard) -> String? {
normalizedCustomHex(defaults.string(forKey: customHexUserDefaultsKey))
}

/// Uppercased `#RRGGBB` form of a 6-digit hex, or `nil` when invalid.
public static func normalizedCustomHex(_ raw: String?) -> String? {
guard let raw else { return nil }
var digits = raw.trimmingCharacters(in: .whitespacesAndNewlines)
if digits.hasPrefix("#") { digits.removeFirst() }
guard digits.count == 6, digits.allSatisfy(\.isHexDigit) else { return nil }
return "#" + digits.uppercased()
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
public import AppKit

/// Resolves ``CmuxAccentColor`` from `app.accentColor` once per change and
/// Resolves ``CmuxAccentColor`` from `app.accentColor` (mode and custom
/// color) once per change and
/// posts ``CmuxAccentColor/didChangeNotification`` (with itself as the
/// object) when the resolved accent changes: when the setting changes, or
/// when the macOS accent changes while the setting follows it.
Expand All @@ -15,11 +16,12 @@ public final class CmuxAccentColorObserver {
private let center: NotificationCenter
private var systemColorsToken: (any NSObjectProtocol)?
private var modeObservation: NSKeyValueObservation?
private var customHexObservation: NSKeyValueObservation?

public init(defaults: UserDefaults = .standard, center: NotificationCenter = .default) {
self.defaults = defaults
self.center = center
self.current = CmuxAccentColor(mode: .stored(in: defaults))
self.current = .stored(in: defaults)
}

public func startObserving() {
Expand All @@ -29,6 +31,11 @@ public final class CmuxAccentColorObserver {
self?.refresh()
}
}
customHexObservation = defaults.observe(\.appAccentColorCustomHex, options: []) { [weak self] _, _ in
Task { @MainActor [weak self] in
self?.refresh()
}
}
systemColorsToken = center.addObserver(
forName: NSColor.systemColorsDidChangeNotification,
object: nil,
Expand All @@ -44,7 +51,7 @@ public final class CmuxAccentColorObserver {
/// draws differently than before. Returns whether it posted.
@discardableResult
public func refresh() -> Bool {
let next = CmuxAccentColor(mode: .stored(in: defaults))
let next = CmuxAccentColor.stored(in: defaults)
guard next != current else { return false }
current = next
center.post(name: CmuxAccentColor.didChangeNotification, object: self)
Expand All @@ -58,4 +65,9 @@ extension UserDefaults {
@objc dynamic var appAccentColor: String? {
string(forKey: CmuxAccentColorMode.userDefaultsKey)
}

/// KVO hook for the custom accent hex, named after its UserDefaults key.
@objc dynamic var appAccentColorCustomHex: String? {
string(forKey: CmuxAccentColorMode.customHexUserDefaultsKey)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -548,10 +548,17 @@ enum CmuxEmbeddedConfigSchema {
"description": "App appearance mode."
},
"accentColor": {
"type": "string",
"enum": ["cmux", "system"],
"oneOf": [
{
"type": "string",
"enum": ["cmux", "system"]
},
{
"$ref": "#/$defs/colorHex"
}
],
"default": "cmux",
"description": "Accent for cmux-drawn chrome: the selected workspace, attention ring and pane flash, agent status, pane swap, canvas focus, and scroll markers. \"cmux\" uses cmux blue; \"system\" follows the macOS accent color and updates when it changes. workspaceColors.selectionColor and notifications.paneFlashColor still override their parts. Native controls always use the macOS accent."
"description": "Accent for cmux-drawn chrome: the selected workspace, attention ring and pane flash, agent status, pane swap, canvas focus, and scroll markers. \"cmux\" uses cmux blue; \"system\" follows the macOS accent color and updates when it changes; a \"#RRGGBB\" hex uses that color in light and dark mode. workspaceColors.selectionColor and notifications.paneFlashColor still override their parts. Native controls always use the macOS accent."
},
"appIcon": {
"type": "string",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,45 @@ import Testing
#expect(CmuxAccentColorMode.stored(in: defaults) == .cmux)
}

@Test func customModeDrawsTheStoredColorInBothSchemes() throws {
let suite = "CmuxAccentColorTests.custom.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }

defaults.set(CmuxAccentColorMode.custom.rawValue, forKey: CmuxAccentColorMode.userDefaultsKey)
defaults.set(" ff6a00 ", forKey: CmuxAccentColorMode.customHexUserDefaultsKey)
let accent = CmuxAccentColor.stored(in: defaults)
#expect(accent.mode == .custom)
#expect(accent.customHex == "#FF6A00")
#expect(rgbBytes(accent.nsColor(isDark: false)) == [255, 106, 0])
#expect(rgbBytes(accent.nsColor(isDark: true)) == [255, 106, 0])
}

@Test func customModeWithoutAValidColorFallsBackToCmuxBlue() {
for hex in [nil, "", "not-a-color", "#FF6A00AA"] {
let accent = CmuxAccentColor(mode: .custom, customHex: hex)
#expect(accent.customHex == nil)
#expect(rgbBytes(accent.nsColor(isDark: false)) == [0, 136, 255])
#expect(rgbBytes(accent.nsColor(isDark: true)) == [0, 145, 255])
}
}

@MainActor
@Test func observerPostsWhenTheCustomColorChanges() throws {
let suite = "CmuxAccentColorTests.customObserver.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
defaults.set(CmuxAccentColorMode.custom.rawValue, forKey: CmuxAccentColorMode.userDefaultsKey)
defaults.set("#FF6A00", forKey: CmuxAccentColorMode.customHexUserDefaultsKey)

let observer = CmuxAccentColorObserver(defaults: defaults, center: NotificationCenter())
#expect(observer.current.customHex == "#FF6A00")
defaults.set("#00FF00", forKey: CmuxAccentColorMode.customHexUserDefaultsKey)
#expect(observer.refresh() == true)
#expect(rgbBytes(observer.current.nsColor(isDark: true)) == [0, 255, 0])
#expect(observer.refresh() == false)
}

@Test func appearanceResolvesToMatchingScheme() throws {
let dark = try #require(NSAppearance(named: .darkAqua))
let aqua = try #require(NSAppearance(named: .aqua))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ public struct AppCatalogSection: SettingCatalogSection {
userDefaultsKey: CmuxAccentColorMode.userDefaultsKey
)

/// `#RRGGBB` color drawn when ``accentColor`` is
/// ``CmuxAccentColorMode/custom``. cmux.json sets it through a hex
/// `app.accentColor` value.
public let accentColorCustomHex = DefaultsKey<String>(
id: "app.accentColorCustomHex",
defaultValue: "",
userDefaultsKey: CmuxAccentColorMode.customHexUserDefaultsKey
)

public let language = DefaultsKey<AppLanguage>(
id: "app.language",
defaultValue: .system,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import CmuxFoundation

/// `app.accentColor` stores the mode's raw value (`"cmux"` or `"system"`).
/// `app.accentColor` stores the mode's raw value (`"cmux"`, `"system"` or `"custom"`).
extension CmuxAccentColorMode: SettingCodable {}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public struct AppSection: View {
@State private var language: DefaultsValueModel<AppLanguage>
@State private var appearance: DefaultsValueModel<AppearanceMode>
@State private var accentColor: DefaultsValueModel<CmuxAccentColorMode>
@State private var accentColorCustomHex: DefaultsValueModel<String>
@State private var appIcon: DefaultsValueModel<AppIconMode>
@State private var placement: DefaultsValueModel<WorkspacePlacement>
@State private var inheritDir: DefaultsValueModel<Bool>
Expand Down Expand Up @@ -77,6 +78,8 @@ public struct AppSection: View {
@State private var renameSelects: DefaultsValueModel<Bool>
@State private var paletteAllSurfaces: DefaultsValueModel<Bool>

@Environment(\.colorScheme) private var colorScheme

@State private var languageAtAppear: AppLanguage?
// Sticky: a picker change can rewrite the OS AppleLanguages override even when the selection returns to its starting value (clearing a preserved foreign override via an explicit pick, then System), so the restart hint must not rely on the value comparison alone.
@State private var languageOverrideTouched = false
Expand All @@ -97,6 +100,7 @@ public struct AppSection: View {
_language = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.app.language))
_appearance = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.app.appearance))
_accentColor = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.app.accentColor))
_accentColorCustomHex = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.app.accentColorCustomHex))
_appIcon = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.app.appIcon))
_placement = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.app.newWorkspacePlacement))
_inheritDir = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.app.workspaceInheritWorkingDirectory))
Expand Down Expand Up @@ -171,7 +175,7 @@ public struct AppSection: View {
AppChannelSwitchCard(hostActions: hostActions)
}
.task {
startSettingsObservation([language, appearance, accentColor, appIcon, placement, inheritDir, minimalMode, keepWorkspaceOpen, firstClick, focusHistoryIncludesPanesAndTabs, equalizeSplitsOnCreate, fileDrop, preferredEditor, openSupported, openMarkdown, globalFontMagnification, markdownFontSize, markdownFontFamily, markdownMaxWidth, canvasPaneGap, canvasSnapping, fileEditorWordWrap, fileEditorSyntaxHighlighting, fileEditorLineNumbers, fileEditorIndentGuides, fileEditorCurrentLineHighlight, fileEditorTabWidth, iMessage, reorder, dockBadge, menuBarOnly, showInMenuBar, paneRing, paneFlash, desktopNotifications, agentPermissionPrompt, agentTurnComplete, agentIdleReminder, soundName, soundWhenFocused, soundCommand, customSoundFile, soundOverrides, telemetry, confirmQuit, warnCloseTab, warnCloseX, warnCloseWorkspace, warnCloseWindow, hideCloseButton, renameSelects, paletteAllSurfaces])
startSettingsObservation([language, appearance, accentColor, accentColorCustomHex, appIcon, placement, inheritDir, minimalMode, keepWorkspaceOpen, firstClick, focusHistoryIncludesPanesAndTabs, equalizeSplitsOnCreate, fileDrop, preferredEditor, openSupported, openMarkdown, globalFontMagnification, markdownFontSize, markdownFontFamily, markdownMaxWidth, canvasPaneGap, canvasSnapping, fileEditorWordWrap, fileEditorSyntaxHighlighting, fileEditorLineNumbers, fileEditorIndentGuides, fileEditorCurrentLineHighlight, fileEditorTabWidth, iMessage, reorder, dockBadge, menuBarOnly, showInMenuBar, paneRing, paneFlash, desktopNotifications, agentPermissionPrompt, agentTurnComplete, agentIdleReminder, soundName, soundWhenFocused, soundCommand, customSoundFile, soundOverrides, telemetry, confirmQuit, warnCloseTab, warnCloseX, warnCloseWorkspace, warnCloseWindow, hideCloseButton, renameSelects, paletteAllSurfaces])
await soundAgentCache.loadIfNeeded { await hostActions.notificationSoundAgentOptions() }
if languageAtAppear == nil { languageAtAppear = language.current }; if telemetryAtAppear == nil { telemetryAtAppear = telemetry.current }
}
Expand All @@ -192,6 +196,16 @@ public struct AppSection: View {
)
}

/// Switching to Custom without a stored color seeds it with the accent
/// currently drawn, so the chrome does not jump before a color is picked.
private func selectAccentColorMode(_ mode: CmuxAccentColorMode) {
if mode == .custom, CmuxAccentColorMode.normalizedCustomHex(accentColorCustomHex.current) == nil {
let current = CmuxAccentColor(mode: accentColor.current, customHex: accentColorCustomHex.current)
accentColorCustomHex.set(current.nsColor(isDark: colorScheme == .dark).hexString())
}
accentColor.set(mode)
}

private func setGlobalFontMagnification(_ percent: Int) {
let clamped = GlobalFontMagnification.clamp(percent)
globalFontMagnification.set(clamped) { NotificationCenter.default.post(name: GlobalFontMagnification.didChangeNotification, object: nil) }
Expand Down Expand Up @@ -232,13 +246,26 @@ public struct AppSection: View {
subtitle: String(localized: "settings.app.accentColor.subtitle", defaultValue: "Color of the selected workspace, attention ring, agent status, and other cmux highlights. System follows the macOS accent color."),
controlWidth: Self.columnWidth
) {
Picker("", selection: Binding(get: { accentColor.current }, set: { accentColor.set($0) })) {
Text(String(localized: "settings.app.accentColor.cmux", defaultValue: "cmux Blue")).tag(CmuxAccentColorMode.cmux)
Text(String(localized: "settings.app.accentColor.system", defaultValue: "System")).tag(CmuxAccentColorMode.system)
HStack(spacing: 8) {
Picker("", selection: Binding(get: { accentColor.current }, set: { selectAccentColorMode($0) })) {
Text(String(localized: "settings.app.accentColor.cmux", defaultValue: "cmux Blue")).tag(CmuxAccentColorMode.cmux)
Text(String(localized: "settings.app.accentColor.system", defaultValue: "System")).tag(CmuxAccentColorMode.system)
Text(String(localized: "settings.app.accentColor.custom", defaultValue: "Custom")).tag(CmuxAccentColorMode.custom)
}
.labelsHidden()
.pickerStyle(.menu)
.accessibilityIdentifier("SettingsAccentColorPicker")
if accentColor.current == .custom {
HexColorPicker(
storedHex: accentColorCustomHex.current,
fallback: Color(nsColor: CmuxAccentColor.cmuxBlue(isDark: colorScheme == .dark)),
reconcileRevision: accentColorCustomHex.revision
) { hex in
accentColorCustomHex.set(hex)
}
.accessibilityIdentifier("SettingsAccentColorCustomPicker")
}
}
.labelsHidden()
.pickerStyle(.menu)
.accessibilityIdentifier("SettingsAccentColorPicker")
}
SettingsCardDivider()

Expand Down
Loading
Loading