From ec6ef9a46e8274abd1b6b4d6e34a968f6079029a Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 19:31:14 -0400 Subject: [PATCH 1/5] Add appearance configuration Signed-off-by: Vincent Taverna --- .../AppearanceConfiguration.swift | 70 ++++++++ Sources/ParcelConfig/ConfigDefaultFile.swift | 6 + Sources/ParcelConfig/ConfigJSONSchema.swift | 25 +++ Sources/ParcelConfig/ConfigValidator.swift | 40 ++++- Sources/ParcelConfig/Configuration.swift | 5 +- .../ParcelConfig/Resources/Schema.xcstrings | 4 + .../AppearanceConfigurationTests.swift | 156 ++++++++++++++++++ .../ConfigJSONSchemaTests.swift | 45 ++++- .../ParcelConfigTests/ConfigStoreTests.swift | 20 +++ .../ConfigValidationTests.swift | 2 + .../DashedConfigurationKeysTests.swift | 58 ++++--- .../LocalizationSourceTests.swift | 12 +- docs/configuration.md | 29 ++++ docs/parcel.schema.json | 90 ++++++++++ 14 files changed, 536 insertions(+), 26 deletions(-) create mode 100644 Sources/ParcelConfig/AppearanceConfiguration.swift create mode 100644 Tests/ParcelConfigTests/AppearanceConfigurationTests.swift diff --git a/Sources/ParcelConfig/AppearanceConfiguration.swift b/Sources/ParcelConfig/AppearanceConfiguration.swift new file mode 100644 index 00000000..7ac96ed1 --- /dev/null +++ b/Sources/ParcelConfig/AppearanceConfiguration.swift @@ -0,0 +1,70 @@ +public enum ConfigAppearancePalette: String, CaseIterable, Sendable { + case system, kiln, tide, grove, iris, dusk, rose +} + +public enum ConfigAppearanceMode: String, CaseIterable, Sendable { + case system, light, dark +} + +public enum AppearanceColorRole: String, CaseIterable, Sendable { + case activeBorder = "active-border-color" + case inactiveBorder = "inactive-border-color" + case glow = "glow-color" + case chipBackground = "chip-background-color" + case chipText = "chip-text-color" + case stackAccent = "stack-accent-color" + case cleanSpaceBackdrop = "clean-space-backdrop-color" +} + +public struct AppearanceHexColor: Equatable, Sendable { + private let rgb: UInt32 + + public var red: Double { Double((rgb >> 16) & 0xFF) / 255 } + public var green: Double { Double((rgb >> 8) & 0xFF) / 255 } + public var blue: Double { Double(rgb & 0xFF) / 255 } + + public init?(hex: String) { + let bytes = hex.utf8 + guard bytes.count == 7, bytes.first == 0x23, + bytes.dropFirst().allSatisfy({ + (0x30...0x39).contains($0) || (0x41...0x46).contains($0) || (0x61...0x66).contains($0) + }), + let rgb = UInt32(hex.dropFirst(), radix: 16) + else { return nil } + self.rgb = rgb + } + + public var hex: String { + let digits = String(rgb, radix: 16, uppercase: true) + return "#" + String(repeating: "0", count: 6 - digits.count) + digits + } +} + +public struct AppearanceConfiguration: Equatable, Sendable { + public static let borderOpacities = 0.0...1.0 + public static let borderRadii = 0.0...40.0 + + public var palette: ConfigAppearancePalette + public var mode: ConfigAppearanceMode + public var colors: [AppearanceColorRole: AppearanceHexColor] + public var borderOpacity: Double + public var borderRadius: Double + + public var isValid: Bool { + Self.borderOpacities.contains(borderOpacity) && Self.borderRadii.contains(borderRadius) + } + + public init( + palette: ConfigAppearancePalette = .system, + mode: ConfigAppearanceMode = .system, + colors: [AppearanceColorRole: AppearanceHexColor] = [:], + borderOpacity: Double = 1, + borderRadius: Double = 10 + ) { + self.palette = palette + self.mode = mode + self.colors = colors + self.borderOpacity = borderOpacity + self.borderRadius = borderRadius + } +} diff --git a/Sources/ParcelConfig/ConfigDefaultFile.swift b/Sources/ParcelConfig/ConfigDefaultFile.swift index ddab8b96..4c9b2bbb 100644 --- a/Sources/ParcelConfig/ConfigDefaultFile.swift +++ b/Sources/ParcelConfig/ConfigDefaultFile.swift @@ -9,6 +9,12 @@ extension ConfigStore { highlight = "active" highlight-width = 2.0 + [appearance] + palette = "system" + mode = "system" + border-opacity = 1.0 + border-radius = 10.0 + [focus-modes] no-peek-level = 0.5 no-peek-blur = true diff --git a/Sources/ParcelConfig/ConfigJSONSchema.swift b/Sources/ParcelConfig/ConfigJSONSchema.swift index 9a68c5ed..f2c8ce17 100644 --- a/Sources/ParcelConfig/ConfigJSONSchema.swift +++ b/Sources/ParcelConfig/ConfigJSONSchema.swift @@ -151,6 +151,7 @@ public enum ConfigJSONSchema { "restore-windows": boolean(defaults.memory.restoreWindows), ]), "motion": motion(defaults.motion), + "appearance": appearance(defaults.appearance), "focus-modes": object([ "no-peek-level": number( FocusModeConfiguration.noPeekLevels, defaultValue: defaults.focusModes.noPeekLevel), @@ -228,6 +229,30 @@ public enum ConfigJSONSchema { ) } + private static func appearance(_ defaults: AppearanceConfiguration) -> SchemaValue { + var properties: [String: SchemaValue] = [ + "palette": choice( + ConfigAppearancePalette.allCases.map(\.rawValue), defaultValue: defaults.palette.rawValue), + "mode": choice(ConfigAppearanceMode.allCases.map(\.rawValue), defaultValue: defaults.mode.rawValue), + "border-opacity": number(AppearanceConfiguration.borderOpacities, defaultValue: defaults.borderOpacity), + "border-radius": number(AppearanceConfiguration.borderRadii, defaultValue: defaults.borderRadius), + ] + for role in AppearanceColorRole.allCases { + properties[role.rawValue] = .object([ + "type": .string("string"), "minLength": .integer(7), "maxLength": .integer(7), + "pattern": .string("^#[0-9A-Fa-f]{6}$"), + "description": .string("Optional exact sRGB #RRGGBB override; omitted roles use the selected palette."), + ]) + } + return object( + properties, + extra: [ + "description": .string( + "System uses native colors. Appearance updates instantly without changing layout; mode affects only Parcel chrome. Accessibility preferences take priority over color overrides." + ) + ]) + } + private static func motion(_ defaults: MotionConfiguration) -> SchemaValue { let properties: [String: SchemaValue] = [ "enabled": boolean(defaults.enabled), diff --git a/Sources/ParcelConfig/ConfigValidator.swift b/Sources/ParcelConfig/ConfigValidator.swift index 4fe55fa3..98f00a7d 100644 --- a/Sources/ParcelConfig/ConfigValidator.swift +++ b/Sources/ParcelConfig/ConfigValidator.swift @@ -17,7 +17,7 @@ private struct Validation { root, allowed: [ "version", "general", "layout", "motion", "mouse", "hover-bar", "keybindings", "float-rules", "rules", - "accessibility", "mode", "classification", "callbacks", "focus-modes", "memory", + "accessibility", "mode", "classification", "callbacks", "focus-modes", "memory", "appearance", ] ) var configuration = ParcelConfiguration.defaults @@ -25,6 +25,7 @@ private struct Validation { configuration.general = general(root["general"]) configuration.layout = layout(root["layout"]) configuration.motion = motion(root["motion"]) + configuration.appearance = appearance(root["appearance"]) configuration.focusModes = focusModes(root["focus-modes"]) configuration.mouse = mouse(root["mouse"]) configuration.hoverBar = hoverBar(root["hover-bar"]) @@ -254,6 +255,43 @@ private struct Validation { return result } + mutating func appearance(_ node: TOMLNode?) -> AppearanceConfiguration { + var result = AppearanceConfiguration() + guard let node else { return result } + let values = table(node, path: "appearance", example: "[appearance]\npalette = \"system\"") + unknownKeys( + values, + allowed: ["palette", "mode", "border-opacity", "border-radius"] + + AppearanceColorRole.allCases.map(\.rawValue), + path: "appearance") + result.palette = choice(values["palette"], path: "appearance.palette", fallback: result.palette) + result.mode = choice(values["mode"], path: "appearance.mode", fallback: result.mode) + result.borderOpacity = number( + values["border-opacity"], path: "appearance.border-opacity", fallback: result.borderOpacity, + bounds: AppearanceConfiguration.borderOpacities) + result.borderRadius = number( + values["border-radius"], path: "appearance.border-radius", fallback: result.borderRadius, + bounds: AppearanceConfiguration.borderRadii) + for role in AppearanceColorRole.allCases { + let path = "appearance.\(role.rawValue)" + let example = "\(role.rawValue) = \"#B65C44\"" + guard let node = values[role.rawValue], + let hex = string(node, path: path, example: example) + else { continue } + guard let color = AppearanceHexColor(hex: hex) else { + failure( + node, + String( + localized: + "“\(path)” must use #RRGGBB with exactly six hexadecimal digits. For example: \(example).", + table: "Schema", bundle: .module)) + continue + } + result.colors[role] = color + } + return result + } + mutating func focusModes(_ node: TOMLNode?) -> FocusModeConfiguration { var result = FocusModeConfiguration() guard let node else { return result } diff --git a/Sources/ParcelConfig/Configuration.swift b/Sources/ParcelConfig/Configuration.swift index d5286e06..bb9e6248 100644 --- a/Sources/ParcelConfig/Configuration.swift +++ b/Sources/ParcelConfig/Configuration.swift @@ -25,6 +25,7 @@ public struct ParcelConfiguration: Equatable, Sendable { public var classification: ClassificationConfiguration public var accessibility: AccessibilityConfiguration public var callbacks: CallbackConfiguration + public var appearance: AppearanceConfiguration public static let defaults = ParcelConfiguration() @@ -44,7 +45,8 @@ public struct ParcelConfiguration: Equatable, Sendable { defaultModeEntries: [String: KeyChord] = [:], modes: [String: [BindingAction: KeyChord]] = [:], callbacks: CallbackConfiguration = CallbackConfiguration(), - focusModes: FocusModeConfiguration = FocusModeConfiguration() + focusModes: FocusModeConfiguration = FocusModeConfiguration(), + appearance: AppearanceConfiguration = AppearanceConfiguration() ) { self.version = version self.general = general @@ -62,6 +64,7 @@ public struct ParcelConfiguration: Equatable, Sendable { self.classification = classification self.accessibility = accessibility self.callbacks = callbacks + self.appearance = appearance } } diff --git a/Sources/ParcelConfig/Resources/Schema.xcstrings b/Sources/ParcelConfig/Resources/Schema.xcstrings index b5de6022..5cfcbf2b 100644 --- a/Sources/ParcelConfig/Resources/Schema.xcstrings +++ b/Sources/ParcelConfig/Resources/Schema.xcstrings @@ -119,6 +119,10 @@ "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” must be a finite number between %@ and %@. For example: %@." } } } }, + "“%@” must use #RRGGBB with exactly six hexadecimal digits. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” must use #RRGGBB with exactly six hexadecimal digits. For example: %@." } } } + }, "“%@” must be one of %@. For example: %@." : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” must be one of %@. For example: %@." } } } diff --git a/Tests/ParcelConfigTests/AppearanceConfigurationTests.swift b/Tests/ParcelConfigTests/AppearanceConfigurationTests.swift new file mode 100644 index 00000000..0d414c38 --- /dev/null +++ b/Tests/ParcelConfigTests/AppearanceConfigurationTests.swift @@ -0,0 +1,156 @@ +import ParcelConfig +import Testing + +@Suite struct AppearanceConfigurationTests { + private static let invalidHexColors = [ + "", "112233", "#123", "#11223344", "#11223G", "#+12345", "#123456", + " #112233", "#112233 ", "#112233\n", "#112233\0", + ] + + @Test func defaultsMatchEmptyConfigurationAndStarterFile() throws { + let expected = AppearanceConfiguration(palette: .system, mode: .system, borderOpacity: 1, borderRadius: 10) + #expect(expected.colors.isEmpty) + #expect(expected.isValid) + #expect(ParcelConfiguration.defaults.appearance == expected) + #expect(try configuration("").appearance == expected) + #expect(try configuration(ConfigStore.defaultFileContents).appearance == expected) + } + + @Test func paletteAndModeAreIndependent() throws { + for palette in ConfigAppearancePalette.allCases { + let value = try configuration("[appearance]\npalette = '\(palette.rawValue)'\nmode = 'dark'\n") + #expect(value.appearance == AppearanceConfiguration(palette: palette, mode: .dark)) + #expect(value.layout == ParcelConfiguration.defaults.layout) + #expect(value.motion == ParcelConfiguration.defaults.motion) + } + for mode in ConfigAppearanceMode.allCases { + let value = try configuration("[appearance]\npalette = 'kiln'\nmode = '\(mode.rawValue)'\n") + #expect(value.appearance == AppearanceConfiguration(palette: .kiln, mode: mode)) + #expect(value.focusModes == ParcelConfiguration.defaults.focusModes) + } + } + + @Test func omittedValuesKeepDefaultsWithoutSynthesizingOverrides() throws { + let appearance = try configuration("[appearance]\nmode = 'dark'\nborder-opacity = 0.35\n").appearance + #expect(appearance == AppearanceConfiguration(mode: .dark, borderOpacity: 0.35)) + } + + @Test func colorsExposeExactSRGBAndCanonicalizeWithoutChangingIdentity() throws { + let color = try #require(AppearanceHexColor(hex: "#007fFF")) + #expect(color.red == 0) + #expect(color.green == 127.0 / 255.0) + #expect(color.blue == 1) + #expect(color.hex == "#007FFF") + #expect(AppearanceHexColor(hex: color.hex) == color) + #expect(AppearanceHexColor(hex: "#000000")?.hex == "#000000") + } + + @Test(arguments: invalidHexColors) + func malformedHexIsRejectedRatherThanCoerced(hex: String) throws { + #expect(AppearanceHexColor(hex: hex) == nil) + try expectInvalidValue(key: AppearanceColorRole.activeBorder.rawValue, value: TOMLWriter.encode(.string(hex))) + } + + @Test(arguments: AppearanceColorRole.allCases) + func everyRoleCanBeOverriddenWithoutChangingOtherRoles(role: AppearanceColorRole) throws { + let color = try #require(AppearanceHexColor(hex: "#a1B2c3")) + let value = try configuration("[appearance]\n\(role.rawValue) = '\(color.hex)'\n") + #expect(value.appearance == AppearanceConfiguration(colors: [role: color])) + } + + @Test func simultaneousOverridesRemainIndependentOfPaletteModeAndLegacyBackdrop() throws { + let first = try #require(AppearanceHexColor(hex: "#AB0123")) + let second = try #require(AppearanceHexColor(hex: "#45CD67")) + var colors: [AppearanceColorRole: AppearanceHexColor] = [:] + var assignments = "" + for (index, role) in AppearanceColorRole.allCases.enumerated() { + let color = index.isMultiple(of: 2) ? first : second + colors[role] = color + assignments += "\(role.rawValue) = '\(color.hex)'\n" + } + let value = try configuration( + "[appearance]\npalette = 'grove'\nmode = 'light'\n" + assignments + + "[focus-modes]\nclean-space-color = 'mist'\n") + #expect(value.appearance == AppearanceConfiguration(palette: .grove, mode: .light, colors: colors)) + #expect(value.focusModes.cleanSpaceColor == .mist) + } + + @Test(arguments: ["true", "123456", "[]", "{}"]) + func colorOverridesRequireStrings(value: String) throws { + try expectInvalidValue(key: AppearanceColorRole.chipText.rawValue, value: value) + } + + @Test(arguments: ["palette", "mode"], ["'unknown'", "'System'", "true", "1", "[]", "{}"]) + func appearanceChoicesRejectInvalidNamesAndTypes(key: String, value: String) throws { + try expectInvalidValue(key: key, value: value) + } + + @Test(arguments: ["border-opacity", "border-radius"], ["nan", "inf", "-inf", "true", "[]", "{}"]) + func borderValuesRejectNonfiniteNumbersAndWrongTypes(key: String, value: String) throws { + try expectInvalidValue(key: key, value: value) + } + + @Test func borderValuesPreserveFractions() throws { + let value = try configuration("[appearance]\nborder-opacity = 0.625\nborder-radius = 12.75\n") + #expect(value.appearance == AppearanceConfiguration(borderOpacity: 0.625, borderRadius: 12.75)) + } + + @Test(arguments: ["'system'", "true", "[]", "1"]) + func appearanceRequiresATable(value: String) throws { + let result = ConfigValidator.validate(try TOMLDocument(parsing: "appearance = \(value)\n")) + #expect(result.configuration == nil) + let diagnostic = try #require(result.diagnostics.first) + #expect(diagnostic.severity == .error) + #expect(diagnostic.location.line == 1) + #expect(diagnostic.location.column == 14) + } + + @Test func unknownKeysWarnWithoutDiscardingValidPreferences() throws { + let result = ConfigValidator.validate( + try TOMLDocument(parsing: "[appearance]\npalette = 'rose'\n border-opcity = 0.5\n")) + #expect(result.configuration?.appearance == AppearanceConfiguration(palette: .rose)) + #expect(result.diagnostics.count == 1) + let warning = try #require(result.diagnostics.first) + #expect(warning.severity == .warning) + #expect(warning.location.line == 3) + #expect(warning.location.column == 3) + } + + @Test func oneBadOverrideRejectsTheWholeAppearanceEdit() throws { + let result = ConfigValidator.validate( + try TOMLDocument( + parsing: "[appearance]\npalette = 'tide'\nactive-border-color = '#ABCDEF'\nchip-text-color = '#123'\n")) + #expect(result.configuration == nil) + #expect(result.diagnostics.count == 1) + #expect(result.diagnostics.first?.severity == .error) + #expect(result.diagnostics.first?.location.line == 4) + } + + @Test(arguments: [Double.nan, .infinity, -.infinity, -0.01, 1.01]) + func directlyConstructedInvalidOpacityIsInspectable(value: Double) { + #expect(!AppearanceConfiguration(borderOpacity: value).isValid) + } + + @Test(arguments: [Double.nan, .infinity, -.infinity, -0.01, 40.01]) + func directlyConstructedInvalidRadiusIsInspectable(value: Double) { + #expect(!AppearanceConfiguration(borderRadius: value).isValid) + } + + private func expectInvalidValue(key: String, value: String) throws { + let result = ConfigValidator.validate( + try TOMLDocument(parsing: "# Appearance preferences\n[appearance]\n \(key) = \(value)\n")) + #expect(result.configuration == nil) + #expect(result.diagnostics.count == 1) + let error = try #require(result.diagnostics.first) + #expect(error.severity == .error) + #expect(error.location.line == 3) + #expect(error.location.column == key.count + 6) + #expect(error.message.contains("appearance.\(key)")) + } + + private func configuration(_ source: String) throws -> ParcelConfiguration { + let result = ConfigValidator.validate(try TOMLDocument(parsing: source)) + #expect(result.diagnostics.isEmpty) + return try #require(result.configuration) + } +} diff --git a/Tests/ParcelConfigTests/ConfigJSONSchemaTests.swift b/Tests/ParcelConfigTests/ConfigJSONSchemaTests.swift index 22a7c19a..ef3c8bd7 100644 --- a/Tests/ParcelConfigTests/ConfigJSONSchemaTests.swift +++ b/Tests/ParcelConfigTests/ConfigJSONSchemaTests.swift @@ -18,7 +18,7 @@ struct ConfigJSONSchemaTests { #expect( Set(properties.keys) == [ "version", "general", "layout", "motion", "mouse", "hover-bar", "keybindings", "float-rules", "rules", - "accessibility", "mode", "classification", "callbacks", "focus-modes", "memory", + "accessibility", "mode", "classification", "callbacks", "focus-modes", "memory", "appearance", ]) } @@ -131,6 +131,49 @@ struct ConfigJSONSchemaTests { check(try schema()) } + @Test func schemaAppearanceDefaultsRoundTripWithoutInventingColorOverrides() throws { + let appearance = try #require(schema()["properties"]?["appearance"]) + #expect(appearance["required"] == nil) + #expect(appearance["additionalProperties"] == .bool(true)) + let properties = try #require(appearance["properties"]?.object) + #expect( + Set(properties.keys) + == Set( + ["palette", "mode", "border-opacity", "border-radius"] + + AppearanceColorRole.allCases.map(\.rawValue))) + #expect(properties["palette"]?["enum"] == .array(ConfigAppearancePalette.allCases.map { .string($0.rawValue) })) + #expect(properties["mode"]?["enum"] == .array(ConfigAppearanceMode.allCases.map { .string($0.rawValue) })) + let palette = try #require(properties["palette"]?["default"]?.string) + let mode = try #require(properties["mode"]?["default"]?.string) + let opacity = try #require(properties["border-opacity"]?["default"]?.number) + let radius = try #require(properties["border-radius"]?["default"]?.number) + let source = + "[appearance]\npalette = '\(palette)'\nmode = '\(mode)'\nborder-opacity = \(opacity)\nborder-radius = \(radius)\n" + let result = ConfigValidator.validate(try TOMLDocument(parsing: source)) + #expect(result.diagnostics.isEmpty) + #expect(result.configuration?.appearance == ParcelConfiguration.defaults.appearance) + for role in AppearanceColorRole.allCases { + #expect(properties[role.rawValue]?["default"] == nil) + } + } + + @Test(arguments: AppearanceColorRole.allCases) + func schemaColorConstraintsAgreeWithStrictHexParsing(role: AppearanceColorRole) throws { + let property = try #require(schema()["properties"]?["appearance"]?["properties"]?[role.rawValue]) + #expect(property["type"] == .string("string")) + let pattern = try #require(property["pattern"]?.string) + let minimum = try #require(property["minLength"]?.number) + let maximum = try #require(property["maxLength"]?.number) + for hex in [ + "#000000", "#ffffff", "#a1B2c3", "#123", "#12345678", "#G12345", "#123456", + " #123456", "#123456 ", "#123456\n", "123456", "#+12345", + ] { + let length = Double(hex.unicodeScalars.count) + let accepted = try matches(pattern, hex) && length >= minimum && length <= maximum + #expect(accepted == (AppearanceHexColor(hex: hex) != nil)) + } + } + @Test func schemaFocusModesMatchDefaultsAndValidation() throws { let modes = try #require(schema()["properties"]?["focus-modes"]?["properties"]?.object) #expect(Set(modes.keys) == ["no-peek-level", "no-peek-blur", "clean-space-color"]) diff --git a/Tests/ParcelConfigTests/ConfigStoreTests.swift b/Tests/ParcelConfigTests/ConfigStoreTests.swift index 2a0cad00..c03bab9c 100644 --- a/Tests/ParcelConfigTests/ConfigStoreTests.swift +++ b/Tests/ParcelConfigTests/ConfigStoreTests.swift @@ -35,6 +35,26 @@ struct ConfigStoreTests { #expect(snapshot.diagnostics.isEmpty) } + @Test func rejectedAppearanceReloadKeepsColorsAndGeometryUntilRecovery() async throws { + let store = ConfigStore() + let source = + "[appearance]\npalette = 'kiln'\nmode = 'dark'\nactive-border-color = '#A1B2C3'\nborder-radius = 12.5\n" + let good = await store.load(source: source) + #expect(good.loadState == .loaded) + #expect(good.activeConfiguration.appearance.palette == .kiln) + let rejected = await store.load(source: "[appearance]\npalette = 'tide'\nactive-border-color = '#123'\n") + #expect(rejected.loadState == .rejected) + #expect(rejected.activeConfiguration == good.activeConfiguration) + #expect(rejected.lastGoodDocument?.render() == source) + let error = try #require(rejected.diagnostics.first) + #expect(error.severity == .error) + #expect(error.location.line == 3) + let recovered = await store.load(source: "[appearance]\npalette = 'rose'\nborder-opacity = 0.5\n") + #expect(recovered.loadState == .loaded) + #expect(recovered.diagnostics.isEmpty) + #expect(recovered.activeConfiguration.appearance == AppearanceConfiguration(palette: .rose, borderOpacity: 0.5)) + } + @Test func initiallyInvalidSyntaxKeepsDefaultsAndParserLocation() async throws { let store = ConfigStore() let snapshot = await store.load(source: "[layout]\nratio = \n") diff --git a/Tests/ParcelConfigTests/ConfigValidationTests.swift b/Tests/ParcelConfigTests/ConfigValidationTests.swift index 9e83d19f..d4303c25 100644 --- a/Tests/ParcelConfigTests/ConfigValidationTests.swift +++ b/Tests/ParcelConfigTests/ConfigValidationTests.swift @@ -1190,5 +1190,7 @@ extension ConfigValidationTests { NumericField(path: "layout.reserved.left", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), NumericField(path: "layout.window-cap", lower: "0", upper: "100", below: "-1", above: "101"), NumericField(path: "motion.speed", lower: "0.1", upper: "4", below: "0.099", above: "4.001"), + NumericField(path: "appearance.border-opacity", lower: "0", upper: "1", below: "-0.001", above: "1.001"), + NumericField(path: "appearance.border-radius", lower: "0", upper: "40", below: "-0.001", above: "40.001"), ] } diff --git a/Tests/ParcelConfigTests/DashedConfigurationKeysTests.swift b/Tests/ParcelConfigTests/DashedConfigurationKeysTests.swift index 16e5ad7c..65caf737 100644 --- a/Tests/ParcelConfigTests/DashedConfigurationKeysTests.swift +++ b/Tests/ParcelConfigTests/DashedConfigurationKeysTests.swift @@ -10,25 +10,31 @@ import Testing let alternateValue: String } - private static let settings = [ - Setting(table: "general", key: "launch-at-login", value: "true", alternateValue: "false"), - Setting(table: "layout", key: "portrait-layout", value: "'columns'", alternateValue: "'tree'"), - Setting(table: "layout", key: "window-cap", value: "2", alternateValue: "100"), - Setting(table: "layout", key: "when-full", value: "'float'", alternateValue: "'stack'"), - Setting(table: "memory", key: "restore-windows", value: "false", alternateValue: "true"), - Setting(table: "motion", key: "focus-border", value: "false", alternateValue: "true"), - Setting(table: "motion", key: "drop-hints", value: "false", alternateValue: "true"), - Setting(table: "motion", key: "experimental-dimming", value: "true", alternateValue: "false"), - Setting(table: "motion", key: "menu-bar-icon", value: "'logo'", alternateValue: "'minimap'"), - Setting(table: "motion", key: "highlight-width", value: "5.5", alternateValue: "2"), - Setting(table: "focus-modes", key: "no-peek-level", value: "0.7", alternateValue: "0.2"), - Setting(table: "focus-modes", key: "no-peek-blur", value: "false", alternateValue: "true"), - Setting(table: "focus-modes", key: "clean-space-color", value: "'stone'", alternateValue: "'mist'"), - Setting(table: "mouse", key: "swap-modifiers", value: "'ctrl'", alternateValue: "'shift'"), - Setting(table: "mouse", key: "stack-modifiers", value: "'shift'", alternateValue: "'ctrl'"), - Setting(table: "accessibility", key: "announce-layout-changes", value: "true", alternateValue: "false"), - Setting(table: "keybindings", key: "focus-left", value: "false", alternateValue: "'cmd-f20'"), - ] + private static let settings = + [ + Setting(table: "general", key: "launch-at-login", value: "true", alternateValue: "false"), + Setting(table: "layout", key: "portrait-layout", value: "'columns'", alternateValue: "'tree'"), + Setting(table: "layout", key: "window-cap", value: "2", alternateValue: "100"), + Setting(table: "layout", key: "when-full", value: "'float'", alternateValue: "'stack'"), + Setting(table: "memory", key: "restore-windows", value: "false", alternateValue: "true"), + Setting(table: "motion", key: "focus-border", value: "false", alternateValue: "true"), + Setting(table: "motion", key: "drop-hints", value: "false", alternateValue: "true"), + Setting(table: "motion", key: "experimental-dimming", value: "true", alternateValue: "false"), + Setting(table: "motion", key: "menu-bar-icon", value: "'logo'", alternateValue: "'minimap'"), + Setting(table: "motion", key: "highlight-width", value: "5.5", alternateValue: "2"), + Setting(table: "appearance", key: "border-opacity", value: "0.5", alternateValue: "0.75"), + Setting(table: "appearance", key: "border-radius", value: "12.5", alternateValue: "20"), + Setting(table: "focus-modes", key: "no-peek-level", value: "0.7", alternateValue: "0.2"), + Setting(table: "focus-modes", key: "no-peek-blur", value: "false", alternateValue: "true"), + Setting(table: "focus-modes", key: "clean-space-color", value: "'stone'", alternateValue: "'mist'"), + Setting(table: "mouse", key: "swap-modifiers", value: "'ctrl'", alternateValue: "'shift'"), + Setting(table: "mouse", key: "stack-modifiers", value: "'shift'", alternateValue: "'ctrl'"), + Setting(table: "accessibility", key: "announce-layout-changes", value: "true", alternateValue: "false"), + Setting(table: "keybindings", key: "focus-left", value: "false", alternateValue: "'cmd-f20'"), + ] + + AppearanceColorRole.allCases.map { + Setting(table: "appearance", key: $0.rawValue, value: "'#A1B2C3'", alternateValue: "'#D4E5F6'") + } @Test(arguments: settings, [0, 1, 2]) private func obsoleteKeysWarnAndNeverOverrideDashedKeys(setting: Setting, order: Int) throws { @@ -104,6 +110,14 @@ import Testing try document.setValue(.string("stone"), forKey: ["focus-modes", "clean-space-color"]) try document.setValue(.bool(false), forKey: ["motion", "drop-hints"]) try document.setValue(.string("logo"), forKey: ["motion", "menu-bar-icon"]) + try document.setValue(.string("kiln"), forKey: ["appearance", "palette"]) + try document.setValue(.string("dark"), forKey: ["appearance", "mode"]) + try document.setValue(.float(0.625), forKey: ["appearance", "border-opacity"]) + try document.setValue(.float(12.75), forKey: ["appearance", "border-radius"]) + let color = try #require(AppearanceHexColor(hex: "#123ABC")) + for role in AppearanceColorRole.allCases { + try document.setValue(.string(color.hex), forKey: ["appearance", role.rawValue]) + } let source = document.render() #expect(source.contains("# Preferences\nversion = 1\n")) #expect(!source.contains("_")) @@ -117,6 +131,12 @@ import Testing == FocusModeConfiguration(noPeekLevel: 0.7, noPeekBlur: false, cleanSpaceColor: .stone)) #expect(configuration.motion.dropHints == false) #expect(configuration.motion.menuBarIcon == .logo) + #expect( + configuration.appearance + == AppearanceConfiguration( + palette: .kiln, mode: .dark, + colors: Dictionary(uniqueKeysWithValues: AppearanceColorRole.allCases.map { ($0, color) }), + borderOpacity: 0.625, borderRadius: 12.75)) #expect(ConfigValidator.validate(try TOMLDocument(parsing: source)).configuration == configuration) } } diff --git a/Tests/ParcelConfigTests/LocalizationSourceTests.swift b/Tests/ParcelConfigTests/LocalizationSourceTests.swift index 27ba99fe..f89d0b86 100644 --- a/Tests/ParcelConfigTests/LocalizationSourceTests.swift +++ b/Tests/ParcelConfigTests/LocalizationSourceTests.swift @@ -57,16 +57,17 @@ import Testing localized: "Line \(line): \(String(value))", table: "Parser", bundle: .module) String(localized: "Default table", bundle: .module) SettingsText.string("Settings key") + AppearanceText.string("Palette key") String(localized: "Values: \(values.joined(separator: ")"))", table: "Schema", bundle: .module) minimumsText("Forget learned minimum size for \(bundleID)") """# let found = try references(in: source, file: "Example.swift") - #expect(found.map(\.table) == ["UI", "Parser", "Localizable", "Settings", "Schema", "Minimums"]) + #expect(found.map(\.table) == ["UI", "Parser", "Localizable", "Settings", "Appearance", "Schema", "Minimums"]) #expect(try normalized(found[0].literal) == "Quote: \"hello\"") #expect(try normalized(found[1].literal) == normalized("Line %lld: %@", swiftLiteral: false)) #expect(try normalized(#"New\nline\t\\path"#) == "New\nline\t\\path") #expect(try normalized("Missing") != normalized("Present")) - #expect(try normalized(found[4].literal) == normalized("Values: %@", swiftLiteral: false)) + #expect(try normalized(found[5].literal) == normalized("Values: %@", swiftLiteral: false)) } @Test func scannerHandlesMultilineContinuations() throws { @@ -114,7 +115,7 @@ import Testing private func references(in source: String, file: String) throws -> [Reference] { var calls = - #"String\s*\(\s*localized:\s*|SettingsText\.string\s*\(\s*|(? Date: Sat, 31 Oct 2026 19:39:09 -0400 Subject: [PATCH 2/5] Keep chrome colors live and add palettes Signed-off-by: Vincent Taverna --- Benchmarks/idle-waits.json | 1 - Package.swift | 3 +- Sources/ParcelApp/NativeAppRuntime.swift | 22 ++ .../Overlays/AppearancePalettes.swift | 124 +++++++ .../ParcelUI/Overlays/OverlayController.swift | 20 +- .../ParcelUI/Overlays/OverlayGeometry.swift | 10 +- .../ParcelUI/Overlays/OverlayPalette.swift | 44 ++- Sources/ParcelUI/Overlays/OverlayPanel.swift | 5 +- .../Overlays/StackChipController.swift | 4 +- .../ParcelUI/Resources/Appearance.xcstrings | 39 +++ .../Settings/AppearancePreferencesView.swift | 321 ++++++++++++++++++ .../Settings/SettingsAccessibilityAudit.swift | 60 +++- Sources/ParcelUI/Settings/SettingsModel.swift | 8 + .../ParcelUI/Settings/SettingsSection.swift | 4 +- Sources/ParcelUI/Settings/SettingsView.swift | 1 + Tests/ParcelAppTests/MenuAppTests.swift | 25 ++ .../ConfigurationAndDisplayTests.swift | 16 + .../Overlays/HighlightTests.swift | 124 +++++++ .../Overlays/PrivacyOverlayTests.swift | 38 ++- .../Overlays/StackChipTests.swift | 28 ++ .../SettingsAccessibilityTests.swift | 97 ++++++ Tests/ParcelUITests/SettingsTests.swift | 164 ++++++++- .../Tour/LearningLocalizationTests.swift | 2 +- 23 files changed, 1120 insertions(+), 40 deletions(-) create mode 100644 Sources/ParcelUI/Overlays/AppearancePalettes.swift create mode 100644 Sources/ParcelUI/Resources/Appearance.xcstrings create mode 100644 Sources/ParcelUI/Settings/AppearancePreferencesView.swift diff --git a/Benchmarks/idle-waits.json b/Benchmarks/idle-waits.json index 47833dfa..3a2adc6e 100644 --- a/Benchmarks/idle-waits.json +++ b/Benchmarks/idle-waits.json @@ -15,7 +15,6 @@ {"path":"ParcelPlatform/Spaces/SpaceController.swift","count":1,"why":"Explicit Space command confirmation; bounded deadline."}, {"path":"ParcelUI/Feedback/FeedbackController.swift","count":1,"why":"One-shot notice dismissal, cancelled when notice is replaced."}, {"path":"ParcelUI/HoverBar/HoverBarController.swift","count":1,"why":"Pointer activity schedules a hover deadline; cancelled when hidden or stopped."}, - {"path":"ParcelUI/MenuBarController.swift","count":1,"why":"Ten-frame finite icon morph; exits when no frames remain."}, {"path":"ParcelUI/Onboarding.swift","count":1,"why":"Finite onboarding motion; ends at its token duration."}, {"path":"ParcelUI/Settings/AlwaysFloatConfirmation.swift","count":1,"why":"Explicit confirmation countdown owns this wait while visible; expires after 12 or 60 unpaused seconds, pauses for accessibility and interaction, and cancels when the notice closes."}, {"path":"ParcelUI/Tour/TourView.swift","count":1,"why":"Finite tour motion; ends at its token duration."} diff --git a/Package.swift b/Package.swift index 83861cb1..4dc5cf25 100644 --- a/Package.swift +++ b/Package.swift @@ -58,7 +58,8 @@ let package = Package( name: "ParcelUI", dependencies: ["ParcelCore", "ParcelConfig", "ParcelEngine", "ParcelAnimation", "ParcelPlatform"], exclude: ["Overlays/README.md", "Overlays/StackChips.md", "Tour/README.md", "HoverBar/README.md"] - + catalogPaths(["Settings", "UI", "Minimums", "Feedback"]), resources: [.process("Resources")], + + catalogPaths(["Settings", "UI", "Minimums", "Feedback", "Appearance"]), + resources: [.process("Resources")], swiftSettings: strict, plugins: localizedStrings), .executableTarget( name: "ParcelApp", diff --git a/Sources/ParcelApp/NativeAppRuntime.swift b/Sources/ParcelApp/NativeAppRuntime.swift index 2cba1d91..9b9d2544 100644 --- a/Sources/ParcelApp/NativeAppRuntime.swift +++ b/Sources/ParcelApp/NativeAppRuntime.swift @@ -144,6 +144,7 @@ final class NativeAppRuntime: AppRuntime { } func startEngine(configuration: ParcelConfiguration) async throws { + applyAppearance(configuration.appearance) if let restorationTask { try await restorationTask.value } if services.engine?.isRunning == true { return } let native = NativeEngineWorld { [fixtureOnly] application in @@ -259,6 +260,7 @@ final class NativeAppRuntime: AppRuntime { func applyConfiguration(_ configuration: ParcelConfiguration) throws { highlightPreference.observe(configuration.motion.highlight) try services.engine?.applyConfiguration(configuration) + applyAppearance(configuration.appearance) callbackRunner.applyConfiguration(configuration.callbacks) learningConfiguration = configuration if hotkeyBindings != nil { @@ -274,6 +276,25 @@ final class NativeAppRuntime: AppRuntime { } } + func applyAppearance(_ configuration: AppearanceConfiguration) { + OverlayPaletteSource.shared.configure(configuration) + let name: NSAppearance.Name? + switch configuration.mode { + case .system: name = nil + case .light: name = .aqua + case .dark: name = .darkAqua + } + guard NSApplication.shared.appearance?.name != name else { return } + if let name { + guard let appearance = NSAppearance(named: name) else { + preconditionFailure("Required macOS appearance unavailable") + } + NSApplication.shared.appearance = appearance + } else { + NSApplication.shared.appearance = nil + } + } + private func updateOverlays(_ configuration: ParcelConfiguration) { services.composition?.clearNotice(.dimming) if !configuration.motion.enabled { services.composition?.clearNotice(.motion) } @@ -640,6 +661,7 @@ final class NativeAppRuntime: AppRuntime { extension NativeAppRuntime { func startShell() async throws { + applyAppearance(services.composition?.configuration.appearance ?? learningConfiguration.appearance) prepareFeedback() secureInput.start() shortcutEnvironment.start() diff --git a/Sources/ParcelUI/Overlays/AppearancePalettes.swift b/Sources/ParcelUI/Overlays/AppearancePalettes.swift new file mode 100644 index 00000000..06b3975f --- /dev/null +++ b/Sources/ParcelUI/Overlays/AppearancePalettes.swift @@ -0,0 +1,124 @@ +import AppKit +import ParcelConfig + +struct AppearancePaletteColors { + let active: AppearanceHexColor + let inactive: AppearanceHexColor + let glow: AppearanceHexColor + let background: AppearanceHexColor + let text: AppearanceHexColor + let stack: AppearanceHexColor + + init(_ active: String, _ inactive: String, _ glow: String, _ background: String, _ text: String, _ stack: String) { + func color(_ hex: String) -> AppearanceHexColor { + guard let value = AppearanceHexColor(hex: hex) else { preconditionFailure("Invalid curated palette color") } + return value + } + self.active = color(active) + self.inactive = color(inactive) + self.glow = color(glow) + self.background = color(background) + self.text = color(text) + self.stack = color(stack) + } + + var roles: [AppearanceColorRole: AppearanceHexColor] { + [ + .activeBorder: active, .inactiveBorder: inactive, .glow: glow, .chipBackground: background, + .chipText: text, .stackAccent: stack, .cleanSpaceBackdrop: background, + ] + } + + static func curated(_ palette: ConfigAppearancePalette, dark: Bool) -> Self? { + switch (palette, dark) { + case (.system, _): nil + case (.kiln, false): Self("#8B4637", "#765B23", "#256967", "#FBF4EA", "#322620", "#256967") + case (.kiln, true): Self("#DEA084", "#D3B566", "#7CBDAB", "#241F1B", "#F5EADD", "#7CBDAB") + case (.tide, false): Self("#326A80", "#505F77", "#4F638E", "#EDF5F6", "#20353D", "#256D68") + case (.tide, true): Self("#80B8CC", "#A5B4CD", "#AABBE0", "#18262B", "#E4F1F3", "#83C7B8") + case (.grove, false): Self("#4F6840", "#695F3D", "#346B62", "#F0F4EA", "#2D3727", "#74601F") + case (.grove, true): Self("#ADC794", "#D2BD83", "#82C1AD", "#20271D", "#E7EFDE", "#D6B969") + case (.iris, false): Self("#705487", "#666078", "#466D78", "#F5F0F8", "#352D42", "#7C5068") + case (.iris, true): Self("#BAA2D0", "#BDB1C7", "#8DBFCC", "#282130", "#EEE6F4", "#D5A0B8") + case (.dusk, false): Self("#805363", "#6D6078", "#3E6974", "#F7F1ED", "#3E3034", "#876029") + case (.dusk, true): Self("#D6A0B5", "#BDB0CF", "#87BAC7", "#2B2222", "#F4E6DC", "#D4B67A") + case (.rose, false): Self("#935167", "#705F63", "#476D58", "#FAF0F1", "#422E36", "#875938") + case (.rose, true): Self("#DCA0B2", "#C6ADB5", "#95C2A4", "#2D2227", "#F5E5ED", "#D2AF8B") + } + } +} + +@MainActor +enum AppearancePaletteResolver { + static func drawingAppearance( + configuration: AppearanceConfiguration, appearance: NSAppearance, accessibility: OverlayAccessibility + ) -> NSAppearance { + if configuration.mode == .system && !accessibility.increaseContrast { return appearance } + let dark: Bool + switch configuration.mode { + case .system: dark = appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + case .light: dark = false + case .dark: dark = true + } + let name: NSAppearance.Name = + accessibility.increaseContrast + ? (dark ? .accessibilityHighContrastDarkAqua : .accessibilityHighContrastAqua) + : (dark ? .darkAqua : .aqua) + guard let result = NSAppearance(named: name) else { + preconditionFailure("Required macOS appearance unavailable") + } + return result + } + + static func resolve( + configuration: AppearanceConfiguration, appearance: NSAppearance, accessibility: OverlayAccessibility + ) -> OverlayPalette { + precondition(configuration.isValid) + let appearance = drawingAppearance( + configuration: configuration, appearance: appearance, accessibility: accessibility) + var result: OverlayPalette? + appearance.performAsCurrentDrawingAppearance { + let dark = appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + let system = OverlayPalette.system() + var roles: [AppearanceColorRole: CGColor] = [ + .activeBorder: system.activeBorder, .inactiveBorder: system.inactiveBorder, .glow: system.glow, + .chipBackground: system.chipBackground, .chipText: system.chipText, .stackAccent: system.stackAccent, + .cleanSpaceBackdrop: NSColor.windowBackgroundColor.cgColor, + ] + if let curated = AppearancePaletteColors.curated(configuration.palette, dark: dark) { + roles = curated.roles.mapValues { color($0) } + } + for (role, override) in configuration.colors { roles[role] = color(override) } + if accessibility.increaseContrast { + let background: CGColor + let foreground: CGColor + if configuration.palette == .system && configuration.colors.isEmpty { + background = NSColor.windowBackgroundColor.cgColor + foreground = NSColor.labelColor.cgColor + } else { + background = CGColor(gray: dark ? 0 : 1, alpha: 1) + foreground = CGColor(gray: dark ? 1 : 0, alpha: 1) + } + for role in AppearanceColorRole.allCases { + roles[role] = role == .chipBackground || role == .cleanSpaceBackdrop ? background : foreground + } + } + func role(_ role: AppearanceColorRole) -> CGColor { + guard let color = roles[role] else { preconditionFailure("Missing appearance color role") } + return color + } + result = OverlayPalette( + activeBorder: role(.activeBorder), inactiveBorder: role(.inactiveBorder), glow: role(.glow), + chipBackground: role(.chipBackground), chipText: role(.chipText), stackAccent: role(.stackAccent), + cleanSpaceBackdrop: role(.cleanSpaceBackdrop), + borderOpacity: accessibility.increaseContrast || accessibility.reduceTransparency + ? 1 : Float(configuration.borderOpacity)) + } + guard let result else { preconditionFailure("Appearance did not resolve chrome colors") } + return result + } + + private static func color(_ hex: AppearanceHexColor) -> CGColor { + NSColor(srgbRed: hex.red, green: hex.green, blue: hex.blue, alpha: 1).cgColor + } +} diff --git a/Sources/ParcelUI/Overlays/OverlayController.swift b/Sources/ParcelUI/Overlays/OverlayController.swift index c9bbff6a..2c524f67 100644 --- a/Sources/ParcelUI/Overlays/OverlayController.swift +++ b/Sources/ParcelUI/Overlays/OverlayController.swift @@ -299,7 +299,7 @@ public final class OverlayController { let tile = makeTile(panel: panel, filled: true) hintLayers[id] = tile tile.move( - to: panel.display.localFrame(target.frame), radius: target.cornerRadius, + to: panel.display.localFrame(target.frame), radius: chromeRadius(target), motion: instantMotion, token: .glance) } refreshPanelVisibility() @@ -472,9 +472,14 @@ public final class OverlayController { continue } let palette = paletteSource.resolve(for: panel.effectiveAppearance, accessibility: accessibility) + let legacyBackdrop = + paletteSource.usesSystemBackdrop && !accessibility.increaseContrast + && focusModes.cleanSpaceColor != FocusModeConfiguration().cleanSpaceColor let backdropColor = - palette.cleanSpaceBackdrop.map(OverlayPalette.appKitColor) - ?? focusModes.cleanSpaceColor.backdropColor + legacyBackdrop + ? focusModes.cleanSpaceColor.backdropColor + : palette.cleanSpaceBackdrop.map(OverlayPalette.appKitColor) + ?? focusModes.cleanSpaceColor.backdropColor let privacy = privacyPanels[id] ?? PrivacyOverlayPanel( @@ -678,7 +683,12 @@ public final class OverlayController { let frame = observedPrivacyFrames[window.id]?.frame ?? nativeHighlightWindows?[window.id]?.focusFrame ?? window.focusFrame - return OverlayWindow(id: window.id, frame: frame, cornerRadius: window.cornerRadius) + return OverlayWindow( + id: window.id, frame: frame, cornerRadius: paletteSource.borderRadius ?? window.cornerRadius) + } + + private func chromeRadius(_ window: OverlayWindow) -> CGFloat { + min(paletteSource.borderRadius ?? window.cornerRadius, window.frame.width / 2, window.frame.height / 2) } private func renderFocus(displays: Set? = nil) { @@ -809,7 +819,7 @@ public final class OverlayController { .activeBorder, scale: panel.display.scale, filled: false) tile.move( - to: panel.display.localFrame(window.frame), radius: window.cornerRadius, + to: panel.display.localFrame(window.frame), radius: chromeRadius(window), motion: currentMotion, token: .shuffle, from: existing == nil ? panel.display.localFrame(before.frame) : nil, staggerIndex: index, transient: true diff --git a/Sources/ParcelUI/Overlays/OverlayGeometry.swift b/Sources/ParcelUI/Overlays/OverlayGeometry.swift index 76fc8c76..e86699c6 100644 --- a/Sources/ParcelUI/Overlays/OverlayGeometry.swift +++ b/Sources/ParcelUI/Overlays/OverlayGeometry.swift @@ -268,6 +268,7 @@ final class OverlayHighlightRenderer { let color: CGColor let glowColor: CGColor let paletteVersion: UInt64? + let opacity: Float let scale: CGFloat } @@ -286,13 +287,13 @@ final class OverlayHighlightRenderer { let next = Inputs( bounds: tile.layer.bounds, radius: tile.layer.cornerRadius, style: style, color: style.active ? palette.activeBorder : palette.inactiveBorder, glowColor: palette.glow, - paletteVersion: version, scale: scale) + paletteVersion: version, opacity: palette.borderOpacity ?? style.opacity, scale: scale) let colorsChanged = version.map { inputs?.paletteVersion != $0 } ?? (inputs?.color != next.color || inputs?.glowColor != next.glowColor) guard colorsChanged || inputs?.bounds != next.bounds || inputs?.radius != next.radius - || inputs?.style != style || inputs?.scale != scale + || inputs?.style != style || inputs?.scale != scale || inputs?.opacity != next.opacity else { return } let geometryChanged = inputs?.bounds != next.bounds || inputs?.radius != next.radius @@ -326,7 +327,7 @@ final class OverlayHighlightRenderer { tile.layer.borderWidth = 0 tile.layer.backgroundColor = nil tile.layer.contentsScale = scale - tile.layer.opacity = style.opacity + tile.layer.opacity = next.opacity tile.ticks.isHidden = true updateStroke( stroke, color: next.color, width: style.width, opacity: 1, scale: scale, dashed: !style.active) @@ -342,7 +343,8 @@ final class OverlayHighlightRenderer { stroke.strokeColor = next.color for band in glow { band.strokeColor = next.glowColor } } - if colorsChanged || styleChanged { styleUpdateCount += 1 } + if inputs?.opacity != next.opacity { tile.layer.opacity = next.opacity } + if colorsChanged || styleChanged || inputs?.opacity != next.opacity { styleUpdateCount += 1 } } inputs = next } diff --git a/Sources/ParcelUI/Overlays/OverlayPalette.swift b/Sources/ParcelUI/Overlays/OverlayPalette.swift index 91cce662..97bce46b 100644 --- a/Sources/ParcelUI/Overlays/OverlayPalette.swift +++ b/Sources/ParcelUI/Overlays/OverlayPalette.swift @@ -1,4 +1,5 @@ public import AppKit +public import ParcelConfig /// Resolved chrome roles. A palette resolver runs with the panel's appearance current. public struct OverlayPalette { @@ -9,10 +10,12 @@ public struct OverlayPalette { public let chipText: CGColor public let stackAccent: CGColor public let cleanSpaceBackdrop: CGColor? + public let borderOpacity: Float? public init( activeBorder: CGColor, inactiveBorder: CGColor, glow: CGColor, - chipBackground: CGColor, chipText: CGColor, stackAccent: CGColor, cleanSpaceBackdrop: CGColor? + chipBackground: CGColor, chipText: CGColor, stackAccent: CGColor, cleanSpaceBackdrop: CGColor?, + borderOpacity: Float? = nil ) { self.activeBorder = activeBorder self.inactiveBorder = inactiveBorder @@ -21,6 +24,8 @@ public struct OverlayPalette { self.chipText = chipText self.stackAccent = stackAccent self.cleanSpaceBackdrop = cleanSpaceBackdrop + precondition(borderOpacity.map { $0.isFinite && (0...1).contains($0) } ?? true) + self.borderOpacity = borderOpacity } @MainActor static func appKitColor(_ color: CGColor) -> NSColor { @@ -40,8 +45,17 @@ public struct OverlayPalette { @MainActor public final class OverlayPaletteSource { public typealias Resolver = @MainActor (NSAppearance, OverlayAccessibility) -> OverlayPalette - public static let shared = OverlayPaletteSource() + public static let shared = OverlayPaletteSource(configuration: AppearanceConfiguration()) public private(set) var version: UInt64 = 1 + private var configuredAppearance: AppearanceConfiguration? + var borderRadius: CGFloat? { + guard let configuredAppearance, configuredAppearance.borderRadius != AppearanceConfiguration().borderRadius + else { return nil } + return CGFloat(configuredAppearance.borderRadius) + } + var usesSystemBackdrop: Bool { + configuredAppearance?.palette == .system && configuredAppearance?.colors[.cleanSpaceBackdrop] == nil + } private var resolver: Resolver private var cache: [String: (OverlayAccessibility, OverlayPalette)] = [:] private var listeners: [UUID: @MainActor () -> Void] = [:] @@ -65,7 +79,24 @@ public final class OverlayPaletteSource { } } + public convenience init(configuration: AppearanceConfiguration) { + self.init() + configure(configuration) + } + + public func configure(_ configuration: AppearanceConfiguration) { + precondition(configuration.isValid) + guard configuredAppearance != configuration else { return } + configuredAppearance = configuration + resolver = { appearance, accessibility in + AppearancePaletteResolver.resolve( + configuration: configuration, appearance: appearance, accessibility: accessibility) + } + invalidate() + } + public func setResolver(_ resolver: @escaping Resolver) { + configuredAppearance = nil self.resolver = resolver invalidate() } @@ -116,11 +147,20 @@ class OverlayChromeView: NSView { required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } + override var wantsUpdateLayer: Bool { true } + + override func updateLayer() { refreshPalette() } + override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance() refreshPalette() } + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + refreshPalette() + } + func refreshPalette() { let options = OverlayAccessibility.system let palette = paletteSource.resolve(for: effectiveAppearance, accessibility: options) diff --git a/Sources/ParcelUI/Overlays/OverlayPanel.swift b/Sources/ParcelUI/Overlays/OverlayPanel.swift index 2b9ef5df..43831f5c 100644 --- a/Sources/ParcelUI/Overlays/OverlayPanel.swift +++ b/Sources/ParcelUI/Overlays/OverlayPanel.swift @@ -224,10 +224,9 @@ final class OverlayTileLayer { } func recolor(_ color: CGColor, fillOpacity: CGFloat? = nil) { - guard layer.borderColor != color else { return } withoutImplicitAnimations { - layer.borderColor = color - ticks.strokeColor = color + if layer.borderColor != color { layer.borderColor = color } + if ticks.strokeColor != color { ticks.strokeColor = color } if let fillOpacity { guard let fill = color.copy(alpha: fillOpacity) else { preconditionFailure("Invalid overlay fill color") diff --git a/Sources/ParcelUI/Overlays/StackChipController.swift b/Sources/ParcelUI/Overlays/StackChipController.swift index 61939cba..ce797b0f 100644 --- a/Sources/ParcelUI/Overlays/StackChipController.swift +++ b/Sources/ParcelUI/Overlays/StackChipController.swift @@ -89,10 +89,10 @@ final class StackChipView: OverlayChromeView { init( group: StackChipGroup, focus: @escaping @MainActor (WindowID) -> Void, - close: @escaping @MainActor (WindowID) -> Void + close: @escaping @MainActor (WindowID) -> Void, paletteSource: OverlayPaletteSource = .shared ) { windows = group.windows - super.init(frame: CGRect(origin: .zero, size: group.frame.size)) + super.init(frame: CGRect(origin: .zero, size: group.frame.size), paletteSource: paletteSource) wantsLayer = true setAccessibilityElement(true) setAccessibilityRole(.tabGroup) diff --git a/Sources/ParcelUI/Resources/Appearance.xcstrings b/Sources/ParcelUI/Resources/Appearance.xcstrings new file mode 100644 index 00000000..684abfea --- /dev/null +++ b/Sources/ParcelUI/Resources/Appearance.xcstrings @@ -0,0 +1,39 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "%@, %@ preview" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "%1$@, %2$@ preview" } } } }, + "Active border" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Active border" } } } }, + "Appearance" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Appearance" } } } }, + "Border opacity (percent)" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Border opacity (percent)" } } } }, + "Border radius (points)" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Border radius (points)" } } } }, + "Borders" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Borders" } } } }, + "Chip background" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Chip background" } } } }, + "Chip text" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Chip text" } } } }, + "Choose an opacity from 0 to 100 percent." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Choose an opacity from 0 to 100 percent." } } } }, + "Choose a radius from 0 to 40 points." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Choose a radius from 0 to 40 points." } } } }, + "Clean Space backdrop" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Clean Space backdrop" } } } }, + "Color mode" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Color mode" } } } }, + "Colors update immediately without moving your windows." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Colors update immediately without moving your windows." } } } }, + "Compare every palette in Light and Dark. System uses your macOS accent color." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Compare every palette in Light and Dark. System uses your macOS accent color." } } } }, + "Custom color overrides from your configuration are included in every preview." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Custom color overrides from your configuration are included in every preview." } } } }, + "Dark" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Dark" } } } }, + "Dusk" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Dusk" } } } }, + "Follow macOS" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Follow macOS" } } } }, + "Glow" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Glow" } } } }, + "Grove" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Grove" } } } }, + "Inactive border" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Inactive border" } } } }, + "Increase Contrast and Reduce Transparency keep borders opaque." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Increase Contrast and Reduce Transparency keep borders opaque." } } } }, + "Iris" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Iris" } } } }, + "Kiln" : { "comment" : "The house palette, inspired by terracotta, ochre, and teal.", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Kiln" } } } }, + "Light" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Light" } } } }, + "Palette" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Palette" } } } }, + "Palette previews" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Palette previews" } } } }, + "Rose" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Rose" } } } }, + "Selected" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Selected" } } } }, + "Stack accent" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Stack accent" } } } }, + "System" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "System" } } } }, + "Tide" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Tide" } } } }, + "Tile" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Tile" } } } } + }, + "version" : "1.0" +} diff --git a/Sources/ParcelUI/Settings/AppearancePreferencesView.swift b/Sources/ParcelUI/Settings/AppearancePreferencesView.swift new file mode 100644 index 00000000..0b4f9fc8 --- /dev/null +++ b/Sources/ParcelUI/Settings/AppearancePreferencesView.swift @@ -0,0 +1,321 @@ +import AppKit +import ParcelConfig +import SwiftUI + +@MainActor +struct AppearancePreferencesView: View { + let model: SettingsModel + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.accessibilityReduceTransparency) private var reduceTransparency + @Environment(\.accessibilityDifferentiateWithoutColor) private var differentiateWithoutColor + @Environment(\.colorSchemeContrast) private var contrast + @State private var paletteVersion = OverlayPaletteSource.shared.version + @State private var paletteObservation: UUID? + + var body: some View { + Form { + Section(AppearanceText.string("Appearance")) { + Picker( + AppearanceText.string("Palette"), + selection: Binding( + get: { model.configuration.appearance.palette }, + set: { save(.string($0.rawValue), field: .palette) }) + ) { + ForEach(ConfigAppearancePalette.allCases, id: \.self) { palette in + Text(palette.appearanceTitle).tag(palette) + } + } + .pickerStyle(.menu) + .accessibilityLabel(AppearanceText.string("Palette")) + .accessibilityIdentifier("settings.appearance.palette") + Picker( + AppearanceText.string("Color mode"), + selection: Binding( + get: { model.configuration.appearance.mode }, + set: { save(.string($0.rawValue), field: .mode) }) + ) { + ForEach(ConfigAppearanceMode.allCases, id: \.self) { mode in + Text(mode.appearanceTitle).tag(mode) + } + } + .pickerStyle(.menu) + .accessibilityLabel(AppearanceText.string("Color mode")) + .accessibilityIdentifier("settings.appearance.mode") + Text(AppearanceText.string("Colors update immediately without moving your windows.")) + .font(.caption).foregroundStyle(.secondary) + } + Section(AppearanceText.string("Borders")) { + SettingsValueEditor( + title: AppearanceText.string("Border opacity (percent)"), + value: (model.configuration.appearance.borderOpacity * 100).formatted( + .number.grouping(.never).precision(.fractionLength(0...16))) + ) { text in + try await model.setValue( + .float(try SettingsNumberParser.number(text) / 100), for: .appearance(.borderOpacity)) + } + .accessibilityIdentifier("settings.appearance.borderOpacity") + .accessibilityHint(AppearanceText.string("Choose an opacity from 0 to 100 percent.")) + SettingsValueEditor( + title: AppearanceText.string("Border radius (points)"), + value: model.configuration.appearance.borderRadius.formatted( + .number.grouping(.never).precision(.fractionLength(0...16))) + ) { text in + try await model.setValue( + .float(try SettingsNumberParser.number(text)), for: .appearance(.borderRadius)) + } + .accessibilityIdentifier("settings.appearance.borderRadius") + .accessibilityHint(AppearanceText.string("Choose a radius from 0 to 40 points.")) + Text(AppearanceText.string("Increase Contrast and Reduce Transparency keep borders opaque.")) + .font(.caption).foregroundStyle(.secondary) + } + Section(AppearanceText.string("Palette previews")) { + Text( + AppearanceText.string( + "Compare every palette in Light and Dark. System uses your macOS accent color.") + ) + .font(.caption).foregroundStyle(.secondary) + if !model.configuration.appearance.colors.isEmpty { + Text( + AppearanceText.string( + "Custom color overrides from your configuration are included in every preview.") + ) + .font(.caption).foregroundStyle(.secondary) + } + LazyVGrid(columns: [GridItem(.adaptive(minimum: 360), spacing: 16)], spacing: 16) { + ForEach(ConfigAppearancePalette.allCases, id: \.self) { palette in + AppearancePaletteCard( + configuration: model.configuration.appearance, preset: palette, + accessibility: accessibility, paletteVersion: paletteVersion) + } + } + } + } + .formStyle(.grouped) + .onAppear { + guard paletteObservation == nil else { return } + paletteVersion = OverlayPaletteSource.shared.version + paletteObservation = OverlayPaletteSource.shared.observe { + paletteVersion = OverlayPaletteSource.shared.version + } + } + .onDisappear { + if let paletteObservation { OverlayPaletteSource.shared.removeObserver(paletteObservation) } + paletteObservation = nil + } + } + + private var accessibility: OverlayAccessibility { + OverlayAccessibility( + reduceMotion: reduceMotion, reduceTransparency: reduceTransparency, + increaseContrast: contrast == .increased, differentiateWithoutColor: differentiateWithoutColor) + } + + private func save(_ value: TOMLValue, field: SettingsAppearanceField) { + Task { + do { try await model.setValue(value, for: .appearance(field)) } catch { model.report(error) } + } + } +} + +@MainActor +struct AppearancePreviewSample { + let configuration: AppearanceConfiguration + let palette: OverlayPalette + let borderOpacity: Double + let windowBackground: CGColor + + init( + configuration: AppearanceConfiguration, preset: ConfigAppearancePalette, + mode: ConfigAppearanceMode, accessibility: OverlayAccessibility + ) { + precondition(mode != .system, "Previews require an explicit color mode") + var configuration = configuration + configuration.palette = preset + configuration.mode = mode + self.configuration = configuration + guard let appearance = NSAppearance(named: mode == .dark ? .darkAqua : .aqua) else { + preconditionFailure("Preview appearance is unavailable") + } + var palette: OverlayPalette? + var background: CGColor? + appearance.performAsCurrentDrawingAppearance { + palette = AppearancePaletteResolver.resolve( + configuration: configuration, appearance: appearance, accessibility: accessibility) + background = NSColor.windowBackgroundColor.cgColor + } + guard let palette, let background, let borderOpacity = palette.borderOpacity else { + preconditionFailure("Preview colors and border opacity did not resolve") + } + self.palette = palette + self.borderOpacity = Double(borderOpacity) + windowBackground = background + } + + func color(for role: AppearanceColorRole) -> CGColor { + switch role { + case .activeBorder: return palette.activeBorder + case .inactiveBorder: return palette.inactiveBorder + case .glow: return palette.glow + case .chipBackground: return palette.chipBackground + case .chipText: return palette.chipText + case .stackAccent: return palette.stackAccent + case .cleanSpaceBackdrop: + guard let color = palette.cleanSpaceBackdrop else { + preconditionFailure("Preview backdrop did not resolve") + } + return color + } + } +} + +@MainActor +struct AppearancePaletteCard: View { + let configuration: AppearanceConfiguration + let preset: ConfigAppearancePalette + let accessibility: OverlayAccessibility + var paletteVersion: UInt64 = 0 + + var body: some View { + let _ = paletteVersion + VStack(alignment: .leading, spacing: 12) { + HStack { + Text(preset.appearanceTitle).font(.headline).accessibilityAddTraits(.isHeader) + Spacer() + if configuration.palette == preset { + Label(AppearanceText.string("Selected"), systemImage: "checkmark.circle.fill") + .font(.caption) + } + } + HStack(alignment: .top, spacing: 12) { + preview(mode: .light) + preview(mode: .dark) + } + } + .padding(12) + .background(.background, in: RoundedRectangle(cornerRadius: 12)) + .overlay { + RoundedRectangle(cornerRadius: 12) + .strokeBorder(.secondary, lineWidth: accessibility.increaseContrast ? 2 : 1) + } + .accessibilityElement(children: .contain) + } + + private func preview(mode: ConfigAppearanceMode) -> some View { + let sample = AppearancePreviewSample( + configuration: configuration, preset: preset, mode: mode, accessibility: accessibility) + return VStack(alignment: .leading, spacing: 8) { + Text(mode.appearanceTitle).font(.caption).foregroundStyle(.secondary) + scene(sample: sample) + .accessibilityHidden(true) + swatches(sample: sample, mode: mode) + } + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityElement(children: .contain) + .accessibilityLabel(AppearanceText.string("\(preset.appearanceTitle), \(mode.appearanceTitle) preview")) + .accessibilityIdentifier("settings.appearance.preview.\(preset.rawValue).\(mode.rawValue)") + } + + private func swatches(sample: AppearancePreviewSample, mode: ConfigAppearanceMode) -> some View { + HStack(spacing: 6) { + ForEach(AppearanceColorRole.allCases, id: \.self) { role in + swatch(sample: sample, mode: mode, role: role) + } + } + } + + private func swatch(sample: AppearancePreviewSample, mode: ConfigAppearanceMode, role: AppearanceColorRole) + -> some View + { + Circle() + .fill(Color(cgColor: sample.color(for: role))) + .overlay { Circle().strokeBorder(.secondary, lineWidth: 1) } + .frame(width: 16, height: 16) + .help(role.appearanceTitle) + .accessibilityElement(children: .ignore) + .accessibilityLabel(role.appearanceTitle) + .accessibilityIdentifier("settings.appearance.preview.\(preset.rawValue).\(mode.rawValue).\(role.rawValue)") + } + + private func scene(sample: AppearancePreviewSample) -> some View { + let radius = sample.configuration.borderRadius / 2 + let width: CGFloat = accessibility.increaseContrast ? 3 : 2 + return HStack(spacing: 8) { + RoundedRectangle(cornerRadius: radius) + .fill(Color(cgColor: sample.windowBackground)) + .overlay(alignment: .bottomLeading) { + HStack(spacing: 4) { + Capsule().fill(Color(cgColor: sample.palette.stackAccent)).frame(width: 12, height: 3) + Text(AppearanceText.string("Tile")) + .font(.caption2).foregroundStyle(Color(cgColor: sample.palette.chipText)) + } + .padding(5) + .background(Color(cgColor: sample.palette.chipBackground), in: Capsule()) + .padding(6) + } + .overlay { + RoundedRectangle(cornerRadius: radius) + .strokeBorder( + Color(cgColor: sample.palette.activeBorder).opacity(sample.borderOpacity), + lineWidth: width) + } + RoundedRectangle(cornerRadius: radius) + .fill(Color(cgColor: sample.windowBackground)) + .overlay { + RoundedRectangle(cornerRadius: radius) + .strokeBorder( + Color(cgColor: sample.palette.inactiveBorder).opacity(sample.borderOpacity), + lineWidth: width) + } + .frame(width: 36) + } + .frame(height: 76) + .padding(8) + .background( + Color(cgColor: sample.color(for: .cleanSpaceBackdrop)), + in: RoundedRectangle(cornerRadius: 8)) + } +} + +enum AppearanceText { + static func string(_ value: String.LocalizationValue) -> String { + String(localized: value, table: "Appearance", bundle: .module) + } +} + +extension ConfigAppearancePalette { + var appearanceTitle: String { + switch self { + case .system: AppearanceText.string("System") + case .kiln: AppearanceText.string("Kiln") + case .tide: AppearanceText.string("Tide") + case .grove: AppearanceText.string("Grove") + case .iris: AppearanceText.string("Iris") + case .dusk: AppearanceText.string("Dusk") + case .rose: AppearanceText.string("Rose") + } + } +} + +extension ConfigAppearanceMode { + var appearanceTitle: String { + switch self { + case .system: AppearanceText.string("Follow macOS") + case .light: AppearanceText.string("Light") + case .dark: AppearanceText.string("Dark") + } + } +} + +extension AppearanceColorRole { + var appearanceTitle: String { + switch self { + case .activeBorder: AppearanceText.string("Active border") + case .inactiveBorder: AppearanceText.string("Inactive border") + case .glow: AppearanceText.string("Glow") + case .chipBackground: AppearanceText.string("Chip background") + case .chipText: AppearanceText.string("Chip text") + case .stackAccent: AppearanceText.string("Stack accent") + case .cleanSpaceBackdrop: AppearanceText.string("Clean Space backdrop") + } + } +} diff --git a/Sources/ParcelUI/Settings/SettingsAccessibilityAudit.swift b/Sources/ParcelUI/Settings/SettingsAccessibilityAudit.swift index d9cf6e16..724a22ed 100644 --- a/Sources/ParcelUI/Settings/SettingsAccessibilityAudit.swift +++ b/Sources/ParcelUI/Settings/SettingsAccessibilityAudit.swift @@ -9,6 +9,48 @@ public struct SettingsAccessibilityControl: Codable, Sendable { public let keyboardReachable: Bool } +@MainActor +struct SettingsAccessibilityElement { + let object: NSObject + + // SwiftUI's virtual nodes implement the selectors without declaring NSAccessibilityProtocol. + private func value(for key: String, as type: T.Type) -> T? { + guard object.responds(to: NSSelectorFromString(key)) else { return nil } + return object.value(forKey: key) as? T + } + + func accessibilityRole() -> NSAccessibility.Role? { + value(for: "accessibilityRole", as: String.self).map { NSAccessibility.Role(rawValue: $0) } + } + func accessibilityLabel() -> String? { value(for: "accessibilityLabel", as: String.self) } + func accessibilityTitle() -> String? { value(for: "accessibilityTitle", as: String.self) } + func accessibilityIdentifier() -> String? { value(for: "accessibilityIdentifier", as: String.self) } + func isAccessibilityEnabled() -> Bool { + if let native = object as? any NSAccessibilityProtocol { return native.isAccessibilityEnabled() } + guard object.responds(to: NSSelectorFromString("isAccessibilityEnabled")), + let enabled = object.value(forKey: "accessibilityEnabled") as? NSNumber + else { return false } + return enabled.boolValue + } + func isEqual(_ other: Self) -> Bool { object.isEqual(other.object) } + + func children(navigation: Bool) -> [Self] { + // Scroller parts are not key views, and AppKit mis-types their navigation array. + guard accessibilityRole() != .scrollBar else { return [] } + let key = navigation ? "accessibilityChildrenInNavigationOrder" : "accessibilityChildren" + guard object.responds(to: NSSelectorFromString(key)), let value = object.value(forKey: key) else { return [] } + guard let children = value as? NSArray else { preconditionFailure("Unsupported accessibility children") } + return children.map { child in + guard let object = child as? NSObject else { preconditionFailure("Unsupported accessibility element") } + return Self(object: object) + } + } + + func descendants(navigation: Bool = false) -> [Self] { + [self] + children(navigation: navigation).flatMap { $0.descendants(navigation: navigation) } + } +} + @MainActor public enum SettingsAccessibilityAudit { public static func run(model: SettingsModel, permissions: AnyView) async throws -> [SettingsAccessibilityControl] { @@ -45,8 +87,9 @@ public enum SettingsAccessibilityAudit { host.layoutSubtreeIfNeeded() window.displayIfNeeded() await Task.yield() - let elements = descendants(host) - let navigation = navigationDescendants(host) + let root = SettingsAccessibilityElement(object: host) + let elements = root.descendants() + let navigation = root.descendants(navigation: true) let interactive = elements.filter { [.button, .checkBox, .popUpButton, .textField, .radioButton, .slider].contains($0.accessibilityRole()) } @@ -63,17 +106,4 @@ public enum SettingsAccessibilityAudit { enabled: element.isAccessibilityEnabled(), keyboardReachable: reachable) } } - - private static func descendants(_ element: any NSAccessibilityProtocol) -> [any NSAccessibilityProtocol] { - [element] - + (element.accessibilityChildren() ?? []).compactMap { $0 as? any NSAccessibilityProtocol }.flatMap { - descendants($0) - } - } - - private static func navigationDescendants(_ element: any NSAccessibilityProtocol) -> [any NSAccessibilityProtocol] { - let children = element.accessibilityChildrenInNavigationOrder() ?? [] - return [element] - + children.compactMap { $0 as? any NSAccessibilityProtocol }.flatMap { navigationDescendants($0) } - } } diff --git a/Sources/ParcelUI/Settings/SettingsModel.swift b/Sources/ParcelUI/Settings/SettingsModel.swift index 24762a02..1450d639 100644 --- a/Sources/ParcelUI/Settings/SettingsModel.swift +++ b/Sources/ParcelUI/Settings/SettingsModel.swift @@ -24,6 +24,12 @@ public enum SettingsMotionField: String, CaseIterable, Sendable { case menuBarIcon = "menu-bar-icon" } +public enum SettingsAppearanceField: String, CaseIterable, Sendable { + case palette, mode + case borderOpacity = "border-opacity" + case borderRadius = "border-radius" +} + public enum SettingsMouseField: String, CaseIterable, Sendable { case enabled case swapModifiers = "swap-modifiers" @@ -52,6 +58,7 @@ public enum SettingsField: Sendable { case disabledDefaultFloatApps case layout(SettingsLayoutField, display: UUID? = nil) case motion(SettingsMotionField) + case appearance(SettingsAppearanceField) case focusModes(SettingsFocusModeField) case mouse(SettingsMouseField) case hoverBar(SettingsHoverBarField) @@ -64,6 +71,7 @@ public enum SettingsField: Sendable { case .announceLayoutChanges: return ["accessibility", "announce-layout-changes"] case .disabledDefaultFloatApps: return ["classification", "disabled-default-float-apps"] case .motion(let field): return ["motion", field.rawValue] + case .appearance(let field): return ["appearance", field.rawValue] case .focusModes(let field): return ["focus-modes", field.rawValue] case .mouse(let field): return ["mouse", field.rawValue] case .hoverBar(let field): return ["hover-bar", field.rawValue] diff --git a/Sources/ParcelUI/Settings/SettingsSection.swift b/Sources/ParcelUI/Settings/SettingsSection.swift index 0d209d0e..75f9d1f3 100644 --- a/Sources/ParcelUI/Settings/SettingsSection.swift +++ b/Sources/ParcelUI/Settings/SettingsSection.swift @@ -1,5 +1,5 @@ enum SettingsSection: String, CaseIterable { - case general, layout, mouse, motion, dimming, hoverBar, shortcuts, rules, apps, permissions, about + case general, layout, mouse, motion, appearance, dimming, hoverBar, shortcuts, rules, apps, permissions, about var title: String { switch self { @@ -7,6 +7,7 @@ enum SettingsSection: String, CaseIterable { case .layout: SettingsText.string("Layout") case .mouse: SettingsText.string("Mouse") case .motion: SettingsText.string("Motion") + case .appearance: AppearanceText.string("Appearance") case .dimming: SettingsText.string("Focus modes") case .hoverBar: SettingsText.string("Hover bar") case .shortcuts: SettingsText.string("Shortcuts") @@ -23,6 +24,7 @@ enum SettingsSection: String, CaseIterable { case .layout: "square.grid.2x2" case .mouse: "computermouse" case .motion: "sparkles" + case .appearance: "paintpalette" case .dimming: "circle.lefthalf.filled" case .hoverBar: "lightbulb" case .shortcuts: "keyboard" diff --git a/Sources/ParcelUI/Settings/SettingsView.swift b/Sources/ParcelUI/Settings/SettingsView.swift index e9d915dd..9fead540 100644 --- a/Sources/ParcelUI/Settings/SettingsView.swift +++ b/Sources/ParcelUI/Settings/SettingsView.swift @@ -167,6 +167,7 @@ public struct SettingsView: View { case .layout: layout case .mouse: mouse case .motion: motion + case .appearance: AppearancePreferencesView(model: model) case .dimming: dimming case .hoverBar: hoverBar case .shortcuts: shortcuts diff --git a/Tests/ParcelAppTests/MenuAppTests.swift b/Tests/ParcelAppTests/MenuAppTests.swift index a033de0b..15abcc7e 100644 --- a/Tests/ParcelAppTests/MenuAppTests.swift +++ b/Tests/ParcelAppTests/MenuAppTests.swift @@ -120,6 +120,31 @@ extension AppKitTestSuite { struct RuntimeMenuAppTests { init() { _ = NSApplication.shared } + @Test func chromeModeAppliesBeforeTheEngineStartsAndCanReturnToSystem() throws { + let application = NSApplication.shared + let previous = application.appearance + defer { + OverlayPaletteSource.shared.configure(.init()) + application.appearance = previous + } + let runtime = NativeAppRuntime(store: ConfigStore(), socketPath: "/tmp/appearance-tests-unused.sock") + var configuration = ParcelConfiguration.defaults + configuration.appearance = .init(palette: .kiln, mode: .dark) + try runtime.applyConfiguration(configuration) + #expect(application.appearance?.name == .darkAqua) + #expect(runtime.services.engine == nil) + let light = try #require(NSAppearance(named: .aqua)) + let background = OverlayPaletteSource.shared.resolve(for: light, accessibility: .init()).chipBackground + configuration.appearance.mode = .light + try runtime.applyConfiguration(configuration) + #expect(application.appearance?.name == .aqua) + #expect( + OverlayPaletteSource.shared.resolve(for: light, accessibility: .init()).chipBackground != background) + configuration.appearance.mode = .system + try runtime.applyConfiguration(configuration) + #expect(application.appearance == nil) + } + @Test func runtimeHighlightToggleMissingCompositionIsVisibleFailure() async throws { let runtime = NativeAppRuntime(store: ConfigStore(), socketPath: "/tmp/menu-tests-unused.sock") await #expect(throws: AppFailure.self) { try await runtime.services.send(.toggleBorders) } diff --git a/Tests/ParcelEngineTests/ConfigurationAndDisplayTests.swift b/Tests/ParcelEngineTests/ConfigurationAndDisplayTests.swift index 2462bdc8..efcff293 100644 --- a/Tests/ParcelEngineTests/ConfigurationAndDisplayTests.swift +++ b/Tests/ParcelEngineTests/ConfigurationAndDisplayTests.swift @@ -291,6 +291,22 @@ struct ParcelEngineConfigurationTests { await harness.engine.stop() } + @Test func appearanceReloadDoesNotRelayoutOrWriteWindowFrames() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let before = harness.engine.snapshot + let count = harness.engine.layoutPassCount + let writes = harness.world.writes.count + var configuration = harness.engine.configuration + configuration.appearance = .init(palette: .kiln, mode: .dark, borderOpacity: 0.5, borderRadius: 16) + try harness.engine.applyConfiguration(configuration) + #expect(harness.engine.configuration.appearance == configuration.appearance) + #expect(harness.scheduler.pendingCount == 0 && harness.engine.layoutPassCount == count) + #expect(harness.engine.snapshot == before && harness.world.writes.count == writes) + await harness.engine.stop() + } + @Test func unchangedConfigurationDoesNotScheduleAnotherPass() async throws { let harness = try EngineHarness() try await harness.start() diff --git a/Tests/ParcelUITests/Overlays/HighlightTests.swift b/Tests/ParcelUITests/Overlays/HighlightTests.swift index cdde8eec..6f09fbba 100644 --- a/Tests/ParcelUITests/Overlays/HighlightTests.swift +++ b/Tests/ParcelUITests/Overlays/HighlightTests.swift @@ -443,6 +443,130 @@ extension AppKitTestSuite { #expect(changed.chipText == first.chipText) } + @Test(arguments: ConfigAppearancePalette.allCases.filter { $0 != .system }, [false, true]) + func curatedPalettesMeetContrastForEveryRole(palette: ConfigAppearancePalette, dark: Bool) throws { + let appearance = try #require(NSAppearance(named: dark ? .darkAqua : .aqua)) + let source = OverlayPaletteSource(configuration: .init(palette: palette)) + let colors = source.resolve(for: appearance, accessibility: .init()) + let backdrop = try #require(colors.cleanSpaceBackdrop) + for background in [colors.chipBackground, backdrop] { + #expect(try contrast(colors.chipText, background) >= 4.5) + for foreground in [colors.activeBorder, colors.inactiveBorder, colors.glow, colors.stackAccent] { + #expect(try contrast(foreground, background) >= 3) + #expect(foreground.alpha == 1) + } + } + #expect(colors.borderOpacity == 1) + let increased = source.resolve(for: appearance, accessibility: .init(increaseContrast: true)) + #expect(try contrast(increased.chipText, increased.chipBackground) >= 7) + for (normal, strong) in zip( + [colors.activeBorder, colors.inactiveBorder, colors.glow, colors.stackAccent], + [increased.activeBorder, increased.inactiveBorder, increased.glow, increased.stackAccent]) + { + #expect(try contrast(strong, increased.chipBackground) >= contrast(normal, colors.chipBackground)) + } + } + + @Test func systemPaletteUsesNativeSemanticColorsInEachDrawingAppearance() throws { + let source = OverlayPaletteSource(configuration: .init()) + for name in [NSAppearance.Name.aqua, .darkAqua] { + let appearance = try #require(NSAppearance(named: name)) + let palette = source.resolve(for: appearance, accessibility: .init()) + appearance.performAsCurrentDrawingAppearance { + #expect(palette.activeBorder == NSColor.controlAccentColor.cgColor) + #expect(palette.inactiveBorder == NSColor.secondaryLabelColor.cgColor) + #expect(palette.chipBackground == NSColor.windowBackgroundColor.cgColor) + #expect(palette.chipText == NSColor.labelColor.cgColor) + #expect(palette.cleanSpaceBackdrop == NSColor.windowBackgroundColor.cgColor) + } + } + } + + @Test func forcedModeAndReturningToSystemInvalidateCachedColors() throws { + let light = try #require(NSAppearance(named: .aqua)) + let dark = try #require(NSAppearance(named: .darkAqua)) + let source = OverlayPaletteSource(configuration: .init(palette: .kiln, mode: .dark)) + let forced = source.resolve(for: light, accessibility: .init()) + #expect(forced.chipBackground == source.resolve(for: dark, accessibility: .init()).chipBackground) + let version = source.version + source.configure(.init(palette: .kiln, mode: .dark)) + #expect(source.version == version) + source.configure(.init(palette: .kiln)) + #expect(source.version > version) + #expect(source.resolve(for: light, accessibility: .init()).chipBackground != forced.chipBackground) + #expect(source.resolve(for: dark, accessibility: .init()).chipBackground == forced.chipBackground) + } + + @Test func customRolesAndOpacityYieldToDisplayAccessibility() throws { + let appearance = try #require(NSAppearance(named: .aqua)) + let custom = try #require(AppearanceHexColor(hex: "#777777")) + let source = OverlayPaletteSource( + configuration: .init( + palette: .rose, + colors: Dictionary(uniqueKeysWithValues: AppearanceColorRole.allCases.map { ($0, custom) }), + borderOpacity: 0.2)) + let palette = source.resolve(for: appearance, accessibility: .init()) + for role in [ + palette.activeBorder, palette.inactiveBorder, palette.glow, palette.chipBackground, + palette.chipText, palette.stackAccent, try #require(palette.cleanSpaceBackdrop), + ] { + let color = try #require(NSColor(cgColor: role)?.usingColorSpace(.sRGB)) + #expect(abs(Double(color.redComponent) - custom.red) < 0.00001) + } + #expect(palette.borderOpacity == 0.2) + let solid = source.resolve(for: appearance, accessibility: .init(reduceTransparency: true)) + #expect(solid.borderOpacity == 1 && solid.chipBackground == palette.chipBackground) + let strong = source.resolve(for: appearance, accessibility: .init(increaseContrast: true)) + #expect(strong.borderOpacity == 1) + #expect(try contrast(strong.chipText, strong.chipBackground) >= 7) + #expect(try contrast(strong.activeBorder, strong.chipBackground) >= 7) + #expect(strong.chipBackground != palette.chipBackground) + } + + @Test func paletteAndBorderSettingsRepaintRetainedLayersWithoutMovingWindows() throws { + let source = OverlayPaletteSource(configuration: .init(palette: .kiln)) + let controller = OverlayController( + configuration: .init(enabled: false, highlight: .all), accessibility: .init(), + brightness: TestOverlayBrightness(), paletteSource: source, notifications: .isolatedForTesting, + orderPanels: false, onFailure: { Issue.record($0) }) + defer { controller.stop() } + controller.setDisplays([display], primaryDisplayHeight: 220) + controller.updateAndRender(OverlaySnapshot(windows: [first, second], focusedWindow: 1)) + let tile = try #require(controller.focusLayers[display.id]) + let inactive = try #require(controller.highlightCanvases[display.id]?.inactive[2]) + let renderer = try #require(tile.highlightRenderer) + let mask = controller.highlightCanvases[display.id]?.mask.path + let path = renderer.stroke.path + let frame = tile.layer.frame + let color = renderer.stroke.strokeColor + source.configure(.init(palette: .tide, borderOpacity: 0.4)) + controller.renderPendingDisplays(at: CACurrentMediaTime() + 1) + #expect(controller.focusLayers[display.id] === tile) + #expect(controller.highlightCanvases[display.id]?.inactive[2] === inactive) + #expect(renderer.stroke.strokeColor != color && tile.layer.opacity == 0.4) + #expect(renderer.stroke.path === path && controller.highlightCanvases[display.id]?.mask.path === mask) + source.configure(.init(palette: .tide, borderRadius: 24)) + controller.renderPendingDisplays(at: CACurrentMediaTime() + 2) + #expect(tile.layer.cornerRadius == 24 && inactive.layer.cornerRadius == 24) + #expect(tile.layer.frame == frame && controller.activeAnimationCount == 0) + #expect(controller.highlightCanvases[display.id]?.mask.path === mask) + } + + private func contrast(_ first: CGColor, _ second: CGColor) throws -> Double { + func luminance(_ color: CGColor) throws -> Double { + let rgb = try #require(NSColor(cgColor: color)?.usingColorSpace(.sRGB)) + func linear(_ value: CGFloat) -> Double { + let value = Double(value) + return value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4) + } + return 0.2126 * linear(rgb.redComponent) + 0.7152 * linear(rgb.greenComponent) + + 0.0722 * linear(rgb.blueComponent) + } + let first = try luminance(first) + let second = try luminance(second) + return (max(first, second) + 0.05) / (min(first, second) + 0.05) + } + @Test func frameBurstsCommitLatestGeometryOncePerDisplayRefresh() throws { let controller = controller(style: .glow) defer { controller.stop() } diff --git a/Tests/ParcelUITests/Overlays/PrivacyOverlayTests.swift b/Tests/ParcelUITests/Overlays/PrivacyOverlayTests.swift index 5627bf86..ab38c35f 100644 --- a/Tests/ParcelUITests/Overlays/PrivacyOverlayTests.swift +++ b/Tests/ParcelUITests/Overlays/PrivacyOverlayTests.swift @@ -134,11 +134,47 @@ extension AppKitTestSuite { controller.updateAndRender(snapshot(noPeek: true)) let panel = try #require(controller.privacyPanels[primary.id]) #expect(!panel.usesBlur && panel.tintOpacity == 0.1) - #expect(panel.tintColor == ConfigCleanSpaceColor.mist.backdropColor) + if accessibility.increaseContrast { + let appearance = try #require(controller.panels[primary.id]?.effectiveAppearance) + let palette = OverlayPaletteSource.shared.resolve(for: appearance, accessibility: accessibility) + #expect(panel.tintColor.cgColor == palette.cleanSpaceBackdrop) + } else { + #expect(panel.tintColor == ConfigCleanSpaceColor.mist.backdropColor) + } #expect(panel.contentView?.layer?.animationKeys()?.isEmpty != false) #expect(brightness.writes.isEmpty) } + @Test func paletteChangeRecolorsRetainedCleanSpacePanelsWithoutWindowChanges() throws { + let source = OverlayPaletteSource(configuration: .init(mode: .light)) + let controller = OverlayController( + configuration: .init(enabled: false), accessibility: .init(), brightness: TestOverlayBrightness(), + paletteSource: source, notifications: .isolatedForTesting, orderPanels: false, + onFailure: { Issue.record($0) }) + defer { controller.stop() } + controller.setDisplays([primary], primaryDisplayHeight: 600) + let key = WorkspaceKey(display: DisplayID(rawValue: primary.id), space: SpaceID(rawValue: 1)) + controller.updateAndRender( + OverlaySnapshot( + windows: [focused, other], focusedWindow: focused.id, + privacyWorkspaces: [OverlayPrivacyWorkspace(key: key, cleanSpace: true, focusedWindow: focused.id)]) + ) + let backdrop = try #require(controller.backdrops[primary.id]) + let privacy = try #require(controller.privacyPanels[primary.id]) + let color = backdrop.backgroundColor + let regions = privacy.regions + let frame = backdrop.frame + source.configure(.init(palette: .kiln, mode: .dark)) + controller.renderPendingDisplays(at: CACurrentMediaTime() + 1) + let appearance = try #require(controller.panels[primary.id]?.effectiveAppearance) + let palette = source.resolve(for: appearance, accessibility: .init()) + #expect(controller.backdrops[primary.id] === backdrop && controller.privacyPanels[primary.id] === privacy) + #expect(backdrop.backgroundColor != color && backdrop.backgroundColor.cgColor == palette.cleanSpaceBackdrop) + #expect(privacy.tintColor.cgColor == palette.cleanSpaceBackdrop && privacy.tintOpacity == 1) + #expect(backdrop.frame == frame && privacy.regions == regions) + #expect(!backdrop.isVisible && !privacy.isVisible) + } + @Test func missingVerifierUsesTheIntendedOverlayWithoutWarning() { var failures = 0 let controller = OverlayController( diff --git a/Tests/ParcelUITests/Overlays/StackChipTests.swift b/Tests/ParcelUITests/Overlays/StackChipTests.swift index f52a9012..efb27230 100644 --- a/Tests/ParcelUITests/Overlays/StackChipTests.swift +++ b/Tests/ParcelUITests/Overlays/StackChipTests.swift @@ -218,9 +218,37 @@ extension AppKitTestSuite { let border = view.layer?.borderColor view.appearance = dark #expect(view.layer?.backgroundColor != background && view.layer?.borderColor != border) + let palette = OverlayPaletteSource.shared.resolve(for: dark, accessibility: .system) + for button in view.subviews.compactMap({ $0 as? NSButton }) { + #expect( + button.contentTintColor?.cgColor == (button.state == .on ? palette.stackAccent : palette.chipText)) + } #expect(view.subviews.map(\.frame) == group.chips.map(\.frame)) } + @Test func displayColorNotificationsRefreshRetainedChipButtons() throws { + @MainActor final class Accent { + var color = NSColor.systemOrange + } + let accent = Accent() + let source = OverlayPaletteSource { _, _ in .system(activeBorder: accent.color) } + let group = try #require(StackChips.groups(in: LearningScene.state(cap: 1)).first) + let view = StackChipView(group: group, focus: { _ in }, close: { _ in }, paletteSource: source) + let selected = try #require(view.subviews.compactMap { $0 as? NSButton }.first { $0.state == .on }) + let tint = selected.contentTintColor + let version = source.version + accent.color = .systemBlue + NotificationCenter.default.post(name: NSColor.systemColorsDidChangeNotification, object: nil) + #expect(source.version > version && selected.contentTintColor != tint) + let changed = selected.contentTintColor + accent.color = .systemGreen + NSWorkspace.shared.notificationCenter.post( + name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil) + #expect(selected.contentTintColor != changed) + #expect(view.subviews.contains { $0 === selected } && selected.state == .on) + #expect(view.frame.size == group.frame.size) + } + @Test func hiddenControllerReusesPanelsAndButtonsAcrossRenamesAndSelectionChanges() throws { let controller = StackChipController(focus: { _ in }, close: { _ in }, orderPanels: false) defer { controller.stop() } diff --git a/Tests/ParcelUITests/SettingsAccessibilityTests.swift b/Tests/ParcelUITests/SettingsAccessibilityTests.swift index fb23e014..147bfdb9 100644 --- a/Tests/ParcelUITests/SettingsAccessibilityTests.swift +++ b/Tests/ParcelUITests/SettingsAccessibilityTests.swift @@ -35,6 +35,67 @@ extension AppKitTestSuite { #expect(bitmap.tiffRepresentation?.isEmpty == false) } + @Test func appearanceControlsHaveReadableKeyboardReachableLabels() async throws { + let model = SettingsModel( + store: ConfigStore( + fileURL: FileManager.default.temporaryDirectory.appendingPathComponent( + "appearance-accessibility-\(UUID())/parcel.toml"))) + try await withAppearanceAccessibilityHost(AppearancePreferencesView(model: model)) { elements, navigation in + let pickers = elements.filter { $0.accessibilityRole() == .popUpButton } + #expect(pickers.count == 2) + for identifier in ["settings.appearance.palette", "settings.appearance.mode"] { + let picker = try #require(pickers.first { $0.accessibilityIdentifier() == identifier }) + #expect(picker.accessibilityLabel()?.isEmpty == false) + #expect(picker.isAccessibilityEnabled()) + #expect(navigation.contains { $0.isEqual(picker) }) + } + let editors = elements.filter { $0.accessibilityRole() == .textField } + #expect(editors.count == 2) + for editor in editors { + #expect(editor.accessibilityLabel()?.isEmpty == false) + #expect(editor.isAccessibilityEnabled()) + #expect(navigation.contains { $0.isEqual(editor) }) + } + let controls = elements.filter { + [.button, .popUpButton, .textField].contains($0.accessibilityRole()) + } + for control in controls { + #expect(!(control.accessibilityLabel() ?? control.accessibilityTitle() ?? "").isEmpty) + if control.isAccessibilityEnabled() { + #expect(navigation.contains { $0.isEqual(control) }) + } + } + } + } + + @Test func everyPalettePreviewNamesBothModesAndEveryColorRole() async throws { + #expect( + Set(ConfigAppearancePalette.allCases.map(\.appearanceTitle)).count + == ConfigAppearancePalette.allCases.count) + #expect( + Set(ConfigAppearanceMode.allCases.map(\.appearanceTitle)).count == ConfigAppearanceMode.allCases.count) + for preset in ConfigAppearancePalette.allCases { + try await withAppearanceAccessibilityHost( + AppearancePaletteCard(configuration: .init(), preset: preset, accessibility: .init()) + ) { elements, _ in + for mode in [ConfigAppearanceMode.light, .dark] { + let identifier = "settings.appearance.preview.\(preset.rawValue).\(mode.rawValue)" + let preview = try #require(elements.first { $0.accessibilityIdentifier() == identifier }) + #expect(preview.accessibilityLabel()?.isEmpty == false) + #expect(preview.accessibilityRole() != nil) + for role in AppearanceColorRole.allCases { + let swatch = try #require( + elements.first { + $0.accessibilityIdentifier() == "\(identifier).\(role.rawValue)" + }) + #expect(swatch.accessibilityLabel()?.isEmpty == false) + #expect(swatch.accessibilityRole() != nil) + } + } + } + } + } + @Test func recorderIsLabelledAndAcceptsKeyboardFocus() { let button = RecordingButton() #expect(button.acceptsFirstResponder) @@ -63,3 +124,39 @@ extension AppKitTestSuite { } } } + +@MainActor +private func withAppearanceAccessibilityHost( + _ view: Content, + body: ([SettingsAccessibilityElement], [SettingsAccessibilityElement]) throws -> Void +) async throws { + // SwiftUI builds its accessibility tree only when AppKit has an accessibility client. + let getter = NSSelectorFromString("accessibilityAttributeValue:") + let setter = NSSelectorFromString("accessibilitySetValue:forAttribute:") + let attribute = "AXEnhancedUserInterface" + let application = NSApplication.shared + try #require(application.responds(to: getter) && application.responds(to: setter)) + let original = try #require(application.perform(getter, with: attribute)?.takeUnretainedValue() as? NSNumber) + _ = application.perform(setter, with: NSNumber(value: true), with: attribute) + defer { + _ = application.perform(setter, with: original, with: attribute) + #expect( + (application.perform(getter, with: attribute)?.takeUnretainedValue() as? NSNumber)?.boolValue + == original.boolValue) + } + let enabled = try #require(application.perform(getter, with: attribute)?.takeUnretainedValue() as? NSNumber) + try #require(enabled.boolValue) + let host = NSHostingView(rootView: view) + let window = NSWindow( + contentRect: CGRect(x: 0, y: 0, width: 850, height: 700), styleMask: [.titled], backing: .buffered, + defer: false) + window.isReleasedWhenClosed = false + defer { window.close() } + window.contentView = host + window.orderFront(nil) + host.layoutSubtreeIfNeeded() + window.displayIfNeeded() + await Task.yield() + let root = SettingsAccessibilityElement(object: host) + try body(root.descendants(), root.descendants(navigation: true)) +} diff --git a/Tests/ParcelUITests/SettingsTests.swift b/Tests/ParcelUITests/SettingsTests.swift index 0d83834a..e14716c4 100644 --- a/Tests/ParcelUITests/SettingsTests.swift +++ b/Tests/ParcelUITests/SettingsTests.swift @@ -28,6 +28,98 @@ struct SettingsTests { } } + @Test func appearanceEditsPersistWithoutChangingCommentsOverridesOrOtherSettings() async throws { + let source = + "# appearance café\r\n[appearance]\r\npalette = 'kiln' # palette\r\nmode = 'system' # mode\r\nborder-opacity = 1.0 # opacity\r\nborder-radius = 10 # radius\r\nactive-border-color = '#123456' # custom\r\n[layout]\r\nratio = 0.6 # layout\r\n[motion]\r\nsound = true\r\n[focus-modes]\r\nclean-space-color = 'mist'\r\n" + let commands = AppearanceSettingsCommands() + try await withSettings(source: source, commands: commands) { model, file in + let original = model.configuration + try await model.setValue(.string("tide"), for: .appearance(.palette)) + try await model.setValue(.string("dark"), for: .appearance(.mode)) + try await model.setValue(.float(0.65), for: .appearance(.borderOpacity)) + try await model.setValue(.float(16), for: .appearance(.borderRadius)) + #expect( + model.configuration.appearance + == AppearanceConfiguration( + palette: .tide, mode: .dark, colors: original.appearance.colors, + borderOpacity: 0.65, borderRadius: 16)) + var expected = original + expected.appearance = model.configuration.appearance + #expect(model.configuration == expected) + #expect( + try file.read() + == source.replacingOccurrences(of: "palette = 'kiln'", with: "palette = \"tide\"") + .replacingOccurrences(of: "mode = 'system'", with: "mode = \"dark\"") + .replacingOccurrences(of: "border-opacity = 1.0", with: "border-opacity = 0.65") + .replacingOccurrences(of: "border-radius = 10", with: "border-radius = 16.0")) + #expect(try SettingsDocumentEditor.validate(TOMLDocument(parsing: file.read())) == expected) + #expect(commands.sent.isEmpty) + #expect(model.error == nil) + } + } + + @Test func everyAppearancePaletteAndModePersistFromDefaults() async throws { + try await withSettings(source: nil) { model, file in + for palette in ConfigAppearancePalette.allCases { + try await model.setValue(.string(palette.rawValue), for: .appearance(.palette)) + #expect(model.configuration.appearance.palette == palette) + } + for mode in ConfigAppearanceMode.allCases { + try await model.setValue(.string(mode.rawValue), for: .appearance(.mode)) + #expect(model.configuration.appearance.mode == mode) + } + let document = try TOMLDocument(parsing: file.read()) + #expect(try SettingsDocumentEditor.validate(document) == model.configuration) + #expect(document.node(forKey: ["appearance", "palette"])?.value == .string("rose")) + #expect(document.node(forKey: ["appearance", "mode"])?.value == .string("dark")) + #expect(document.node(forKey: ["layout"]) == nil) + #expect(document.node(forKey: ["motion"]) == nil) + #expect(model.configuration.appearance.colors.isEmpty) + } + } + + @Test func invalidAppearanceEditsNeverReachDisk() async throws { + let source = "# unchanged\n[appearance]\npalette='grove'\n" + try await withSettings(source: source) { model, file in + let original = model.configuration + for (field, value) in [ + (SettingsAppearanceField.palette, TOMLValue.string("unknown")), + (.mode, .string("unknown")), (.palette, .bool(true)), (.mode, .integer(1)), + (.borderOpacity, .float(-0.01)), (.borderOpacity, .float(1.01)), + (.borderOpacity, .float(.nan)), (.borderOpacity, .string("opaque")), + (.borderRadius, .float(-1)), (.borderRadius, .float(41)), (.borderRadius, .float(.infinity)), + ] { + await #expect(throws: SettingsFailure.self) { try await model.setValue(value, for: .appearance(field)) } + #expect(try file.read() == source) + #expect(model.configuration == original) + #expect(model.error != nil) + } + try await model.setValue(.float(0), for: .appearance(.borderOpacity)) + try await model.setValue(.float(40), for: .appearance(.borderRadius)) + #expect(model.configuration.appearance.borderOpacity == 0) + #expect(model.configuration.appearance.borderRadius == 40) + #expect(model.error == nil) + } + } + + @Test func externalAppearanceChangesRefreshSettingsWithoutCommands() async throws { + let commands = AppearanceSettingsCommands() + try await withSettings(source: "# preferences\n", commands: commands) { model, file in + try file.write("[appearance]\npalette='iris'\nmode='light'\nborder-opacity=0.8\nborder-radius=14\n") + try await waitForSettings { + model.configuration.appearance + == AppearanceConfiguration( + palette: .iris, mode: .light, borderOpacity: 0.8, borderRadius: 14) + } + try await model.setValue(.string("dusk"), for: .appearance(.palette)) + #expect(model.configuration.appearance.palette == .dusk) + #expect(model.configuration.appearance.mode == .light) + #expect(model.configuration.appearance.borderOpacity == 0.8) + #expect(model.configuration.appearance.borderRadius == 14) + #expect(commands.sent.isEmpty) + } + } + @Test func memorySwitchesPersistWithoutChangingLayoutOrComments() async throws { let source = "# memory\n[memory]\nenabled = true # keep\nrestore-windows = true\n[layout]\nratio = 0.6\n" try await withSettings(source: source) { model, file in @@ -189,6 +281,7 @@ struct SettingsTests { var fields: [SettingsField] = [.launchAtLogin, .prefix, .announceLayoutChanges] fields += SettingsLayoutField.allCases.map { .layout($0) } fields += SettingsMotionField.allCases.map { .motion($0) } + fields += SettingsAppearanceField.allCases.map { .appearance($0) } fields += SettingsMouseField.allCases.map { .mouse($0) } fields += SettingsHoverBarField.allCases.map { .hoverBar($0) } fields += SettingsFocusModeField.allCases.map { .focusModes($0) } @@ -201,6 +294,11 @@ struct SettingsTests { #expect(SettingsField.focusModes(.noPeekLevel).path(in: document) == ["focus-modes", "no-peek-level"]) #expect(SettingsField.focusModes(.noPeekBlur).path(in: document) == ["focus-modes", "no-peek-blur"]) #expect(SettingsField.focusModes(.cleanSpaceColor).path(in: document) == ["focus-modes", "clean-space-color"]) + for field in SettingsAppearanceField.allCases { + #expect(SettingsField.appearance(field).path(in: document) == ["appearance", field.rawValue]) + } + #expect(SettingsField.appearance(.borderOpacity).path(in: document) == ["appearance", "border-opacity"]) + #expect(SettingsField.appearance(.borderRadius).path(in: document) == ["appearance", "border-radius"]) } @Test func everyConfigurationControlWritesItsSchemaPath() async throws { @@ -774,13 +872,14 @@ private struct SettingsFile: Sendable { } @MainActor -private func withSettings(source: String?, body: @MainActor (SettingsModel, SettingsFile) async throws -> Void) - async throws -{ +private func withSettings( + source: String?, commands: (any UICommandSink)? = nil, + body: @MainActor (SettingsModel, SettingsFile) async throws -> Void +) async throws { let file = try SettingsFile() defer { file.remove() } if let source { try file.write(source) } - let model = SettingsModel(store: ConfigStore(fileURL: file.url)) + let model = SettingsModel(store: ConfigStore(fileURL: file.url), commands: commands) await model.start() do { try await body(model, file) } catch { await model.stop() @@ -812,6 +911,63 @@ private func waitForSettings(_ predicate: @MainActor () -> Bool) async throws { private enum SettingsTestError: Error { case observationEnded } +@MainActor private final class AppearanceSettingsCommands: UICommandSink { + var sent: [ConfigCommand] = [] + func send(_ command: ConfigCommand) async throws { sent.append(command) } +} + +extension AppKitTestSuite { + @MainActor + struct AppearancePreviewTests { + @Test func lightAndDarkPreviewsStayIndependentOfConfiguredMode() { + let configuration = AppearanceConfiguration(palette: .kiln, mode: .dark, borderRadius: 18) + let light = AppearancePreviewSample( + configuration: configuration, preset: .tide, mode: .light, accessibility: .init()) + let dark = AppearancePreviewSample( + configuration: configuration, preset: .tide, mode: .dark, accessibility: .init()) + #expect(light.configuration.mode == .light) + #expect(dark.configuration.mode == .dark) + #expect(light.configuration.palette == .tide) + #expect(dark.configuration.palette == .tide) + #expect(light.configuration.borderRadius == 18) + #expect(dark.configuration.borderRadius == 18) + #expect(light.palette.chipBackground != dark.palette.chipBackground) + for sample in [light, dark] { + for role in AppearanceColorRole.allCases { + #expect(NSColor(cgColor: sample.color(for: role)) != nil) + } + } + #expect(configuration.palette == .kiln) + #expect(configuration.mode == .dark) + } + + @Test func previewsIncludeCustomRolesAndAccessibleBorderOpacity() throws { + let custom = try #require(AppearanceHexColor(hex: "#123456")) + let configuration = AppearanceConfiguration( + palette: .rose, mode: .dark, colors: [.activeBorder: custom], borderOpacity: 0.3, borderRadius: 22) + let standard = AppearancePreviewSample( + configuration: configuration, preset: .grove, mode: .light, accessibility: .init()) + let activeColor = try #require(NSColor(cgColor: standard.palette.activeBorder)?.usingColorSpace(.sRGB)) + #expect(abs(activeColor.redComponent - custom.red) < 0.001) + #expect(abs(activeColor.greenComponent - custom.green) < 0.001) + #expect(abs(activeColor.blueComponent - custom.blue) < 0.001) + #expect(standard.configuration.colors == configuration.colors) + #expect(standard.configuration.borderRadius == 22) + #expect(abs(standard.borderOpacity - 0.3) < 0.001) + for options in [OverlayAccessibility(reduceTransparency: true), .init(increaseContrast: true)] { + let accessible = AppearancePreviewSample( + configuration: configuration, preset: .grove, mode: .dark, accessibility: options) + #expect(accessible.palette.borderOpacity == 1) + #expect( + accessible.configuration + == AppearanceConfiguration( + palette: .grove, mode: .dark, colors: [.activeBorder: custom], borderOpacity: 0.3, + borderRadius: 22)) + } + } + } +} + extension AppKitTestSuite { @Suite(.timeLimit(.minutes(1))) @MainActor diff --git a/Tests/ParcelUITests/Tour/LearningLocalizationTests.swift b/Tests/ParcelUITests/Tour/LearningLocalizationTests.swift index 43e0471c..b4e60a63 100644 --- a/Tests/ParcelUITests/Tour/LearningLocalizationTests.swift +++ b/Tests/ParcelUITests/Tour/LearningLocalizationTests.swift @@ -24,7 +24,7 @@ struct LearningLocalizationTests { } } - @Test(arguments: ["TourSetup", "Menu", "WhatsNew", "Highlights"]) + @Test(arguments: ["TourSetup", "Menu", "WhatsNew", "Highlights", "Appearance"]) func featureCatalogsHaveCompiledEnglishValues(table: String) throws { let catalog = try loadCatalog(table) let runtimeURL = try #require( -- knotmirror 0.0.1 From 52a42bf7041b847f3951498392b9f876720985be Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 19:43:22 -0400 Subject: [PATCH 3/5] Make accessible chrome colors fully opaque Signed-off-by: Vincent Taverna --- Sources/ParcelUI/Overlays/AppearancePalettes.swift | 8 ++++++++ Tests/ParcelUITests/Overlays/HighlightTests.swift | 10 ++++++++++ 2 files changed, 18 insertions(+) diff --git a/Sources/ParcelUI/Overlays/AppearancePalettes.swift b/Sources/ParcelUI/Overlays/AppearancePalettes.swift index 06b3975f..1ab3f1b9 100644 --- a/Sources/ParcelUI/Overlays/AppearancePalettes.swift +++ b/Sources/ParcelUI/Overlays/AppearancePalettes.swift @@ -103,6 +103,14 @@ enum AppearancePaletteResolver { roles[role] = role == .chipBackground || role == .cleanSpaceBackdrop ? background : foreground } } + if accessibility.increaseContrast || accessibility.reduceTransparency { + roles = roles.mapValues { color in + guard let opaque = color.copy(alpha: 1) else { + preconditionFailure("Appearance color cannot be made opaque") + } + return opaque + } + } func role(_ role: AppearanceColorRole) -> CGColor { guard let color = roles[role] else { preconditionFailure("Missing appearance color role") } return color diff --git a/Tests/ParcelUITests/Overlays/HighlightTests.swift b/Tests/ParcelUITests/Overlays/HighlightTests.swift index 6f09fbba..5ec48433 100644 --- a/Tests/ParcelUITests/Overlays/HighlightTests.swift +++ b/Tests/ParcelUITests/Overlays/HighlightTests.swift @@ -479,6 +479,16 @@ extension AppKitTestSuite { #expect(palette.chipText == NSColor.labelColor.cgColor) #expect(palette.cleanSpaceBackdrop == NSColor.windowBackgroundColor.cgColor) } + for options in [OverlayAccessibility(reduceTransparency: true), .init(increaseContrast: true)] { + let solid = source.resolve(for: appearance, accessibility: options) + for role in [ + solid.activeBorder, solid.inactiveBorder, solid.glow, solid.chipBackground, + solid.chipText, solid.stackAccent, try #require(solid.cleanSpaceBackdrop), + ] { + #expect(role.alpha == 1) + } + #expect(solid.borderOpacity == 1) + } } } -- knotmirror 0.0.1 From 42ef27e10068695a799c744a4f3bef9b2eb00f31 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 20:43:30 -0400 Subject: [PATCH 4/5] Apply appearance before engine reloads Signed-off-by: Vincent Taverna --- Sources/ParcelApp/NativeAppRuntime.swift | 2 +- .../AppRuntimeRegressionTests.swift | 38 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Sources/ParcelApp/NativeAppRuntime.swift b/Sources/ParcelApp/NativeAppRuntime.swift index 172ec553..fac338d3 100644 --- a/Sources/ParcelApp/NativeAppRuntime.swift +++ b/Sources/ParcelApp/NativeAppRuntime.swift @@ -270,8 +270,8 @@ final class NativeAppRuntime: AppRuntime { func applyConfiguration(_ configuration: ParcelConfiguration) throws { highlightPreference.observe(configuration.motion.highlight) - try services.engine?.applyConfiguration(configuration) applyAppearance(configuration.appearance) + try services.engine?.applyConfiguration(configuration) callbackRunner.applyConfiguration(configuration.callbacks) learningConfiguration = configuration hoverFocus.cancel() diff --git a/Tests/ParcelAppTests/AppRuntimeRegressionTests.swift b/Tests/ParcelAppTests/AppRuntimeRegressionTests.swift index 4fe798ec..f12a51fc 100644 --- a/Tests/ParcelAppTests/AppRuntimeRegressionTests.swift +++ b/Tests/ParcelAppTests/AppRuntimeRegressionTests.swift @@ -399,6 +399,44 @@ extension AppKitTestSuite { #expect(changes == 2) } + @Test func rejectedEngineReloadStillAppliesPaletteAndColorMode() throws { + let application = NSApplication.shared + let previous = application.appearance + defer { + OverlayPaletteSource.shared.configure(.init()) + application.appearance = previous + } + let baseline = ParcelConfiguration.defaults + let engine = try ParcelEngine( + world: RecordingWorld(), clock: SystemEngineClock(), scheduler: RunLoopEngineScheduler(), + displayLink: { _ in throw AppFailure(message: "This test never starts a display link") }, + announcer: AppAnnouncer(onModeChange: {}), log: AppEngineLog(), configuration: baseline, + trace: nil, reduceMotionSource: nil) + let runtime = NativeAppRuntime(store: ConfigStore(), socketPath: "/tmp/appearance-reload-unused.sock") + runtime.services.engine = engine + let choices: [(ConfigAppearancePalette, ConfigAppearanceMode, NSAppearance.Name?)] = [ + (.kiln, .dark, .darkAqua), (.tide, .light, .aqua), (.rose, .system, nil), + ] + for (palette, mode, name) in choices { + var rejected = baseline + rejected.version = 2 + rejected.appearance = .init(palette: palette, mode: mode) + #expect(throws: EngineError.invalidConfiguration("Unsupported configuration version")) { + try runtime.applyConfiguration(rejected) + } + #expect(engine.configuration == baseline) + #expect(application.appearance?.name == name) + let expected = OverlayPaletteSource(configuration: rejected.appearance) + for drawingName in [NSAppearance.Name.aqua, .darkAqua] { + let appearance = try #require(NSAppearance(named: drawingName)) + let actual = OverlayPaletteSource.shared.resolve(for: appearance, accessibility: .init()) + let resolved = expected.resolve(for: appearance, accessibility: .init()) + #expect(actual.activeBorder == resolved.activeBorder) + #expect(actual.chipBackground == resolved.chipBackground) + } + } + } + @Test func pausedStartupNeverWritesBeforeResume() async throws { _ = NSApplication.shared let suite = "dev.vinnymac.parcel.tests.\(UUID())" -- knotmirror 0.0.1 From 02c93f2126b37ace0dbaaa22e87690deaeafd866 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 20:45:34 -0400 Subject: [PATCH 5/5] Restore appearance choices and accessible palettes Signed-off-by: Vincent Taverna --- .../AppearanceConfiguration.swift | 6 +- Sources/ParcelConfig/ConfigDefaultFile.swift | 1 - Sources/ParcelConfig/ConfigJSONSchema.swift | 11 +- Sources/ParcelConfig/ConfigValidator.swift | 8 +- .../Overlays/AppearancePalettes.swift | 76 ++++--- .../ParcelUI/Overlays/OverlayController.swift | 9 +- .../ParcelUI/Overlays/OverlayPalette.swift | 11 +- .../ParcelUI/Resources/Appearance.xcstrings | 11 + .../Settings/AppearancePreferencesView.swift | 206 ++++++++++++++---- .../Settings/FocusModePreferencesView.swift | 18 ++ .../Settings/SettingsDocumentEditor.swift | 36 +++ Sources/ParcelUI/Settings/SettingsModel.swift | 12 + .../AppearanceConfigurationTests.swift | 11 +- .../ConfigJSONSchemaTests.swift | 15 +- .../Overlays/HighlightTests.swift | 165 ++++++++++---- .../Overlays/PrivacyOverlayTests.swift | 56 ++++- .../SettingsAccessibilityTests.swift | 134 ++++++++++-- Tests/ParcelUITests/SettingsTests.swift | 93 ++++++++ docs/configuration.md | 16 +- docs/parcel.schema.json | 4 +- 20 files changed, 713 insertions(+), 186 deletions(-) diff --git a/Sources/ParcelConfig/AppearanceConfiguration.swift b/Sources/ParcelConfig/AppearanceConfiguration.swift index 7ac96ed1..8ae9f988 100644 --- a/Sources/ParcelConfig/AppearanceConfiguration.swift +++ b/Sources/ParcelConfig/AppearanceConfiguration.swift @@ -48,10 +48,10 @@ public struct AppearanceConfiguration: Equatable, Sendable { public var mode: ConfigAppearanceMode public var colors: [AppearanceColorRole: AppearanceHexColor] public var borderOpacity: Double - public var borderRadius: Double + public var borderRadius: Double? public var isValid: Bool { - Self.borderOpacities.contains(borderOpacity) && Self.borderRadii.contains(borderRadius) + Self.borderOpacities.contains(borderOpacity) && (borderRadius.map { Self.borderRadii.contains($0) } ?? true) } public init( @@ -59,7 +59,7 @@ public struct AppearanceConfiguration: Equatable, Sendable { mode: ConfigAppearanceMode = .system, colors: [AppearanceColorRole: AppearanceHexColor] = [:], borderOpacity: Double = 1, - borderRadius: Double = 10 + borderRadius: Double? = nil ) { self.palette = palette self.mode = mode diff --git a/Sources/ParcelConfig/ConfigDefaultFile.swift b/Sources/ParcelConfig/ConfigDefaultFile.swift index f3302897..5a12df38 100644 --- a/Sources/ParcelConfig/ConfigDefaultFile.swift +++ b/Sources/ParcelConfig/ConfigDefaultFile.swift @@ -13,7 +13,6 @@ extension ConfigStore { palette = "system" mode = "system" border-opacity = 1.0 - border-radius = 10.0 [focus-modes] no-peek-level = 0.5 diff --git a/Sources/ParcelConfig/ConfigJSONSchema.swift b/Sources/ParcelConfig/ConfigJSONSchema.swift index 38e21076..2bab3f72 100644 --- a/Sources/ParcelConfig/ConfigJSONSchema.swift +++ b/Sources/ParcelConfig/ConfigJSONSchema.swift @@ -243,7 +243,9 @@ public enum ConfigJSONSchema { ConfigAppearancePalette.allCases.map(\.rawValue), defaultValue: defaults.palette.rawValue), "mode": choice(ConfigAppearanceMode.allCases.map(\.rawValue), defaultValue: defaults.mode.rawValue), "border-opacity": number(AppearanceConfiguration.borderOpacities, defaultValue: defaults.borderOpacity), - "border-radius": number(AppearanceConfiguration.borderRadii, defaultValue: defaults.borderRadius), + "border-radius": number( + AppearanceConfiguration.borderRadii, defaultValue: nil, + description: "Optional radius in points; omitted means match each window's native corner radius."), ] for role in AppearanceColorRole.allCases { properties[role.rawValue] = .object([ @@ -256,7 +258,7 @@ public enum ConfigJSONSchema { properties, extra: [ "description": .string( - "System uses native colors. Appearance updates instantly without changing layout; mode affects only Parcel chrome. Accessibility preferences take priority over color overrides." + "System uses native colors. Appearance updates instantly without changing layout; mode affects Parcel's windows and chrome, not other apps. Accessibility preferences take priority over color overrides." ) ]) } @@ -407,11 +409,14 @@ public enum ConfigJSONSchema { return .object(result) } - private static func number(_ range: ClosedRange, defaultValue: Double?) -> SchemaValue { + private static func number(_ range: ClosedRange, defaultValue: Double?, description: String? = nil) + -> SchemaValue + { var result: [String: SchemaValue] = [ "type": .string("number"), "minimum": .number(range.lowerBound), "maximum": .number(range.upperBound), ] if let defaultValue { result["default"] = .number(defaultValue) } + if let description { result["description"] = .string(description) } return .object(result) } diff --git a/Sources/ParcelConfig/ConfigValidator.swift b/Sources/ParcelConfig/ConfigValidator.swift index 0466fdee..2a006351 100644 --- a/Sources/ParcelConfig/ConfigValidator.swift +++ b/Sources/ParcelConfig/ConfigValidator.swift @@ -269,9 +269,11 @@ private struct Validation { result.borderOpacity = number( values["border-opacity"], path: "appearance.border-opacity", fallback: result.borderOpacity, bounds: AppearanceConfiguration.borderOpacities) - result.borderRadius = number( - values["border-radius"], path: "appearance.border-radius", fallback: result.borderRadius, - bounds: AppearanceConfiguration.borderRadii) + if let radius = values["border-radius"] { + result.borderRadius = number( + radius, path: "appearance.border-radius", fallback: AppearanceConfiguration.borderRadii.lowerBound, + bounds: AppearanceConfiguration.borderRadii) + } for role in AppearanceColorRole.allCases { let path = "appearance.\(role.rawValue)" let example = "\(role.rawValue) = \"#B65C44\"" diff --git a/Sources/ParcelUI/Overlays/AppearancePalettes.swift b/Sources/ParcelUI/Overlays/AppearancePalettes.swift index 1ab3f1b9..4dc06622 100644 --- a/Sources/ParcelUI/Overlays/AppearancePalettes.swift +++ b/Sources/ParcelUI/Overlays/AppearancePalettes.swift @@ -32,18 +32,18 @@ struct AppearancePaletteColors { static func curated(_ palette: ConfigAppearancePalette, dark: Bool) -> Self? { switch (palette, dark) { case (.system, _): nil - case (.kiln, false): Self("#8B4637", "#765B23", "#256967", "#FBF4EA", "#322620", "#256967") - case (.kiln, true): Self("#DEA084", "#D3B566", "#7CBDAB", "#241F1B", "#F5EADD", "#7CBDAB") - case (.tide, false): Self("#326A80", "#505F77", "#4F638E", "#EDF5F6", "#20353D", "#256D68") - case (.tide, true): Self("#80B8CC", "#A5B4CD", "#AABBE0", "#18262B", "#E4F1F3", "#83C7B8") - case (.grove, false): Self("#4F6840", "#695F3D", "#346B62", "#F0F4EA", "#2D3727", "#74601F") - case (.grove, true): Self("#ADC794", "#D2BD83", "#82C1AD", "#20271D", "#E7EFDE", "#D6B969") - case (.iris, false): Self("#705487", "#666078", "#466D78", "#F5F0F8", "#352D42", "#7C5068") - case (.iris, true): Self("#BAA2D0", "#BDB1C7", "#8DBFCC", "#282130", "#EEE6F4", "#D5A0B8") - case (.dusk, false): Self("#805363", "#6D6078", "#3E6974", "#F7F1ED", "#3E3034", "#876029") - case (.dusk, true): Self("#D6A0B5", "#BDB0CF", "#87BAC7", "#2B2222", "#F4E6DC", "#D4B67A") - case (.rose, false): Self("#935167", "#705F63", "#476D58", "#FAF0F1", "#422E36", "#875938") - case (.rose, true): Self("#DCA0B2", "#C6ADB5", "#95C2A4", "#2D2227", "#F5E5ED", "#D2AF8B") + case (.kiln, false): Self("#995C4F", "#9D8961", "#256967", "#FBF4EA", "#322620", "#256967") + case (.kiln, true): Self("#BB876F", "#806E3E", "#7CBDAB", "#241F1B", "#F5EADD", "#7CBDAB") + case (.tide, false): Self("#3E7387", "#828C9D", "#4F638E", "#EDF5F6", "#20353D", "#256D68") + case (.tide, true): Self("#6B9AAA", "#677080", "#AABBE0", "#18262B", "#E4F1F3", "#83C7B8") + case (.grove, false): Self("#5C734E", "#938B73", "#346B62", "#F0F4EA", "#2D3727", "#74601F") + case (.grove, true): Self("#859972", "#7B6F4D", "#82C1AD", "#20271D", "#E7EFDE", "#D6B969") + case (.iris, false): Self("#7C6291", "#8E899B", "#466D78", "#F5F0F8", "#352D42", "#7C5068") + case (.iris, true): Self("#9F8BB2", "#746D7A", "#8DBFCC", "#282130", "#EEE6F4", "#D5A0B8") + case (.dusk, false): Self("#8A606F", "#92889A", "#3E6974", "#F7F1ED", "#3E3034", "#876029") + case (.dusk, true): Self("#B38698", "#746C7F", "#87BAC7", "#2B2222", "#F4E6DC", "#D4B67A") + case (.rose, false): Self("#98596E", "#95888B", "#476D58", "#FAF0F1", "#422E36", "#875938") + case (.rose, true): Self("#B78594", "#7B6B70", "#95C2A4", "#2D2227", "#F5E5ED", "#D2AF8B") } } } @@ -83,24 +83,21 @@ enum AppearancePaletteResolver { var roles: [AppearanceColorRole: CGColor] = [ .activeBorder: system.activeBorder, .inactiveBorder: system.inactiveBorder, .glow: system.glow, .chipBackground: system.chipBackground, .chipText: system.chipText, .stackAccent: system.stackAccent, - .cleanSpaceBackdrop: NSColor.windowBackgroundColor.cgColor, ] if let curated = AppearancePaletteColors.curated(configuration.palette, dark: dark) { roles = curated.roles.mapValues { color($0) } } for (role, override) in configuration.colors { roles[role] = color(override) } if accessibility.increaseContrast { - let background: CGColor - let foreground: CGColor - if configuration.palette == .system && configuration.colors.isEmpty { - background = NSColor.windowBackgroundColor.cgColor - foreground = NSColor.labelColor.cgColor - } else { - background = CGColor(gray: dark ? 0 : 1, alpha: 1) - foreground = CGColor(gray: dark ? 1 : 0, alpha: 1) - } - for role in AppearanceColorRole.allCases { - roles[role] = role == .chipBackground || role == .cleanSpaceBackdrop ? background : foreground + let background = CGColor(gray: dark ? 0 : 1, alpha: 1) + roles[.chipBackground] = background + roles[.chipText] = CGColor(gray: dark ? 1 : 0, alpha: 1) + if roles[.cleanSpaceBackdrop] != nil { roles[.cleanSpaceBackdrop] = background } + let neutral = dark ? 0.584 : 0.349 + roles[.inactiveBorder] = NSColor(srgbRed: neutral, green: neutral, blue: neutral, alpha: 1).cgColor + for role in [AppearanceColorRole.activeBorder, .glow, .stackAccent] { + guard let accent = roles[role] else { preconditionFailure("Missing appearance accent") } + roles[role] = highContrastAccent(accent, dark: dark) } } if accessibility.increaseContrast || accessibility.reduceTransparency { @@ -118,7 +115,7 @@ enum AppearancePaletteResolver { result = OverlayPalette( activeBorder: role(.activeBorder), inactiveBorder: role(.inactiveBorder), glow: role(.glow), chipBackground: role(.chipBackground), chipText: role(.chipText), stackAccent: role(.stackAccent), - cleanSpaceBackdrop: role(.cleanSpaceBackdrop), + cleanSpaceBackdrop: roles[.cleanSpaceBackdrop], borderOpacity: accessibility.increaseContrast || accessibility.reduceTransparency ? 1 : Float(configuration.borderOpacity)) } @@ -126,6 +123,35 @@ enum AppearancePaletteResolver { return result } + private static func highContrastAccent(_ color: CGColor, dark: Bool) -> CGColor { + guard let rgb = NSColor(cgColor: color)?.usingColorSpace(.sRGB) else { + preconditionFailure("Appearance accent cannot be converted to sRGB") + } + let channels = [rgb.redComponent, rgb.greenComponent, rgb.blueComponent] + let destination: CGFloat = dark ? 1 : 0 + // Leave room for a 7:1 neutral border while keeping the accent at least 1.5:1 apart. + let target = dark ? 0.49 : 0.048 + func adjusted(_ amount: CGFloat) -> [CGFloat] { + channels.map { $0 + (destination - $0) * amount } + } + func meetsContrast(_ channels: [CGFloat]) -> Bool { + let luminance = zip(channels, [0.2126, 0.7152, 0.0722]).reduce(0.0) { sum, pair in + let value = Double(pair.0) + let linear = value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4) + return sum + linear * pair.1 + } + return dark ? luminance >= target : luminance <= target + } + var low: CGFloat = 0 + var high: CGFloat = meetsContrast(channels) ? 0 : 1 + for _ in 0..<24 { + let middle = (low + high) / 2 + if meetsContrast(adjusted(middle)) { high = middle } else { low = middle } + } + let result = adjusted(high) + return NSColor(srgbRed: result[0], green: result[1], blue: result[2], alpha: 1).cgColor + } + private static func color(_ hex: AppearanceHexColor) -> CGColor { NSColor(srgbRed: hex.red, green: hex.green, blue: hex.blue, alpha: 1).cgColor } diff --git a/Sources/ParcelUI/Overlays/OverlayController.swift b/Sources/ParcelUI/Overlays/OverlayController.swift index 2c524f67..96705639 100644 --- a/Sources/ParcelUI/Overlays/OverlayController.swift +++ b/Sources/ParcelUI/Overlays/OverlayController.swift @@ -472,14 +472,9 @@ public final class OverlayController { continue } let palette = paletteSource.resolve(for: panel.effectiveAppearance, accessibility: accessibility) - let legacyBackdrop = - paletteSource.usesSystemBackdrop && !accessibility.increaseContrast - && focusModes.cleanSpaceColor != FocusModeConfiguration().cleanSpaceColor let backdropColor = - legacyBackdrop - ? focusModes.cleanSpaceColor.backdropColor - : palette.cleanSpaceBackdrop.map(OverlayPalette.appKitColor) - ?? focusModes.cleanSpaceColor.backdropColor + palette.cleanSpaceBackdrop.map(OverlayPalette.appKitColor) + ?? focusModes.cleanSpaceColor.backdropColor let privacy = privacyPanels[id] ?? PrivacyOverlayPanel( diff --git a/Sources/ParcelUI/Overlays/OverlayPalette.swift b/Sources/ParcelUI/Overlays/OverlayPalette.swift index 2bcc109f..607a1f13 100644 --- a/Sources/ParcelUI/Overlays/OverlayPalette.swift +++ b/Sources/ParcelUI/Overlays/OverlayPalette.swift @@ -49,12 +49,7 @@ public final class OverlayPaletteSource { public private(set) var version: UInt64 = 1 private var configuredAppearance: AppearanceConfiguration? var borderRadius: CGFloat? { - guard let configuredAppearance, configuredAppearance.borderRadius != AppearanceConfiguration().borderRadius - else { return nil } - return CGFloat(configuredAppearance.borderRadius) - } - var usesSystemBackdrop: Bool { - configuredAppearance?.palette == .system && configuredAppearance?.colors[.cleanSpaceBackdrop] == nil + configuredAppearance?.borderRadius.map { CGFloat($0) } } private var resolver: Resolver private var cache: [String: (OverlayAccessibility, OverlayPalette)] = [:] @@ -147,10 +142,6 @@ class OverlayChromeView: NSView { required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } - override var wantsUpdateLayer: Bool { true } - - override func updateLayer() { refreshPalette() } - override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance() refreshPalette() diff --git a/Sources/ParcelUI/Resources/Appearance.xcstrings b/Sources/ParcelUI/Resources/Appearance.xcstrings index 684abfea..57327206 100644 --- a/Sources/ParcelUI/Resources/Appearance.xcstrings +++ b/Sources/ParcelUI/Resources/Appearance.xcstrings @@ -1,6 +1,17 @@ { "sourceLanguage" : "en", "strings" : { + "%@ %@" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "%1$@ %2$@" } } } }, + "%@: %@" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "%1$@: %2$@" } } } }, + "%@ palette. %@. %@." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "%1$@ palette. %2$@. %3$@." } } } }, + "Automatic radius uses a sample window in previews." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Automatic radius uses a sample window in previews." } } } }, + "Choose a radius from 0 to 40 points, or leave blank to match the window." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Choose a radius from 0 to 40 points, or leave blank to match the window." } } } }, + "Custom colors" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Custom colors" } } } }, + "Match window radius" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Match window radius" } } } }, + "Reset %@" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Reset %1$@" } } } }, + "Reset all custom colors" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Reset all custom colors" } } } }, + "The Appearance palette or custom backdrop color controls Clean Space. Choose System and reset the backdrop override to use this picker." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "The Appearance palette or custom backdrop color controls Clean Space. Choose System and reset the backdrop override to use this picker." } } } }, + "This appearance value cannot be safely reset. Edit it in the configuration file." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "This appearance value cannot be safely reset. Edit it in the configuration file." } } } }, "%@, %@ preview" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "%1$@, %2$@ preview" } } } }, "Active border" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Active border" } } } }, "Appearance" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Appearance" } } } }, diff --git a/Sources/ParcelUI/Settings/AppearancePreferencesView.swift b/Sources/ParcelUI/Settings/AppearancePreferencesView.swift index 0b4f9fc8..b5e9f3b1 100644 --- a/Sources/ParcelUI/Settings/AppearancePreferencesView.swift +++ b/Sources/ParcelUI/Settings/AppearancePreferencesView.swift @@ -57,23 +57,55 @@ struct AppearancePreferencesView: View { .accessibilityHint(AppearanceText.string("Choose an opacity from 0 to 100 percent.")) SettingsValueEditor( title: AppearanceText.string("Border radius (points)"), - value: model.configuration.appearance.borderRadius.formatted( - .number.grouping(.never).precision(.fractionLength(0...16))) + value: model.configuration.appearance.borderRadius.map { + $0.formatted(.number.grouping(.never).precision(.fractionLength(0...16))) + } ?? "" ) { text in - try await model.setValue( - .float(try SettingsNumberParser.number(text)), for: .appearance(.borderRadius)) + try await model.setAppearanceBorderRadius( + text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ? nil : try SettingsNumberParser.number(text)) } .accessibilityIdentifier("settings.appearance.borderRadius") - .accessibilityHint(AppearanceText.string("Choose a radius from 0 to 40 points.")) + .accessibilityHint( + AppearanceText.string("Choose a radius from 0 to 40 points, or leave blank to match the window.")) + Button(AppearanceText.string("Match window radius")) { + perform { try await model.setAppearanceBorderRadius(nil) } + } + .disabled(model.configuration.appearance.borderRadius == nil) + .accessibilityIdentifier("settings.appearance.borderRadius.reset") Text(AppearanceText.string("Increase Contrast and Reduce Transparency keep borders opaque.")) .font(.caption).foregroundStyle(.secondary) } + if !model.configuration.appearance.colors.isEmpty { + Section(AppearanceText.string("Custom colors")) { + ForEach(AppearanceColorRole.allCases, id: \.self) { role in + if let color = model.configuration.appearance.colors[role] { + HStack { + Text(role.appearanceTitle) + Spacer() + Text(color.hex).monospaced() + .accessibilityLabel(AppearanceText.string("\(role.appearanceTitle) \(color.hex)")) + Button(AppearanceText.string("Reset \(role.appearanceTitle)")) { + perform { try await model.resetAppearanceColors([role]) } + } + .accessibilityIdentifier("settings.appearance.override.\(role.rawValue).reset") + } + } + } + Button(AppearanceText.string("Reset all custom colors")) { + perform { try await model.resetAppearanceColors() } + } + .accessibilityIdentifier("settings.appearance.overrides.reset") + } + } Section(AppearanceText.string("Palette previews")) { Text( AppearanceText.string( "Compare every palette in Light and Dark. System uses your macOS accent color.") ) .font(.caption).foregroundStyle(.secondary) + Text(AppearanceText.string("Automatic radius uses a sample window in previews.")) + .font(.caption).foregroundStyle(.secondary) if !model.configuration.appearance.colors.isEmpty { Text( AppearanceText.string( @@ -85,7 +117,9 @@ struct AppearancePreferencesView: View { ForEach(ConfigAppearancePalette.allCases, id: \.self) { palette in AppearancePaletteCard( configuration: model.configuration.appearance, preset: palette, - accessibility: accessibility, paletteVersion: paletteVersion) + accessibility: accessibility, paletteVersion: paletteVersion, + cleanSpaceColor: model.configuration.focusModes.cleanSpaceColor, + select: { save(.string(palette.rawValue), field: .palette) }) } } } @@ -111,8 +145,12 @@ struct AppearancePreferencesView: View { } private func save(_ value: TOMLValue, field: SettingsAppearanceField) { + perform { try await model.setValue(value, for: .appearance(field)) } + } + + private func perform(_ action: @escaping @MainActor () async throws -> Void) { Task { - do { try await model.setValue(value, for: .appearance(field)) } catch { model.report(error) } + do { try await action() } catch { model.report(error) } } } } @@ -123,11 +161,15 @@ struct AppearancePreviewSample { let palette: OverlayPalette let borderOpacity: Double let windowBackground: CGColor + let cleanSpaceColor: ConfigCleanSpaceColor + var borderRadius: Double { configuration.borderRadius ?? 10 } init( configuration: AppearanceConfiguration, preset: ConfigAppearancePalette, - mode: ConfigAppearanceMode, accessibility: OverlayAccessibility + mode: ConfigAppearanceMode, accessibility: OverlayAccessibility, + cleanSpaceColor: ConfigCleanSpaceColor = .graphite ) { + self.cleanSpaceColor = cleanSpaceColor precondition(mode != .system, "Previews require an explicit color mode") var configuration = configuration configuration.palette = preset @@ -159,12 +201,70 @@ struct AppearancePreviewSample { case .chipBackground: return palette.chipBackground case .chipText: return palette.chipText case .stackAccent: return palette.stackAccent - case .cleanSpaceBackdrop: - guard let color = palette.cleanSpaceBackdrop else { - preconditionFailure("Preview backdrop did not resolve") + case .cleanSpaceBackdrop: return palette.cleanSpaceBackdrop ?? cleanSpaceColor.backdropColor.cgColor + } + } + + var accessibilitySummary: String { + let roles = AppearanceColorRole.allCases.map { role in + guard let rgb = NSColor(cgColor: color(for: role))?.usingColorSpace(.sRGB) else { + preconditionFailure("Preview color cannot be converted to sRGB") } - return color + let hex = + "#" + + [rgb.redComponent, rgb.greenComponent, rgb.blueComponent].map { + String(format: "%02X", Int(($0 * 255).rounded())) + }.joined() + return AppearanceText.string("\(role.appearanceTitle) \(hex)") + }.joined(separator: ", ") + return AppearanceText.string("\(configuration.mode.appearanceTitle): \(roles)") + } +} + +@MainActor +final class AppearancePreviewCache { + typealias Sampler = + @MainActor ( + AppearanceConfiguration, ConfigAppearancePalette, ConfigAppearanceMode, + OverlayAccessibility, ConfigCleanSpaceColor + ) -> AppearancePreviewSample + private let makeSample: Sampler + + init( + makeSample: @escaping Sampler = { configuration, preset, mode, accessibility, cleanSpaceColor in + AppearancePreviewSample( + configuration: configuration, preset: preset, mode: mode, + accessibility: accessibility, cleanSpaceColor: cleanSpaceColor) } + ) { + self.makeSample = makeSample + } + + private struct Key: Equatable { + let configuration: AppearanceConfiguration + let preset: ConfigAppearancePalette + let accessibility: OverlayAccessibility + let version: UInt64 + let cleanSpaceColor: ConfigCleanSpaceColor + } + private var key: Key? + private var samples: [ConfigAppearanceMode: AppearancePreviewSample] = [:] + + func sample( + configuration: AppearanceConfiguration, preset: ConfigAppearancePalette, mode: ConfigAppearanceMode, + accessibility: OverlayAccessibility, version: UInt64, cleanSpaceColor: ConfigCleanSpaceColor + ) -> AppearancePreviewSample { + let key = Key( + configuration: configuration, preset: preset, accessibility: accessibility, + version: version, cleanSpaceColor: cleanSpaceColor) + if self.key != key { + self.key = key + samples.removeAll(keepingCapacity: true) + } + if let sample = samples[mode] { return sample } + let sample = makeSample(configuration, preset, mode, accessibility, cleanSpaceColor) + samples[mode] = sample + return sample } } @@ -174,70 +274,80 @@ struct AppearancePaletteCard: View { let preset: ConfigAppearancePalette let accessibility: OverlayAccessibility var paletteVersion: UInt64 = 0 + var cleanSpaceColor: ConfigCleanSpaceColor = .graphite + let select: @MainActor () -> Void + @State private var cache = AppearancePreviewCache() var body: some View { - let _ = paletteVersion - VStack(alignment: .leading, spacing: 12) { - HStack { - Text(preset.appearanceTitle).font(.headline).accessibilityAddTraits(.isHeader) - Spacer() - if configuration.palette == preset { - Label(AppearanceText.string("Selected"), systemImage: "checkmark.circle.fill") - .font(.caption) + let light = sample(mode: .light) + let dark = sample(mode: .dark) + Button(action: select) { + VStack(alignment: .leading, spacing: 12) { + HStack { + Text(preset.appearanceTitle).font(.headline) + Spacer() + if configuration.palette == preset { + Label(AppearanceText.string("Selected"), systemImage: "checkmark.circle.fill") + .font(.caption) + } + } + HStack(alignment: .top, spacing: 12) { + preview(sample: light, mode: .light) + preview(sample: dark, mode: .dark) } } - HStack(alignment: .top, spacing: 12) { - preview(mode: .light) - preview(mode: .dark) + .padding(12) + .background(.background, in: RoundedRectangle(cornerRadius: 12)) + .overlay { + RoundedRectangle(cornerRadius: 12) + .strokeBorder(.secondary, lineWidth: accessibility.increaseContrast ? 2 : 1) } } - .padding(12) - .background(.background, in: RoundedRectangle(cornerRadius: 12)) - .overlay { - RoundedRectangle(cornerRadius: 12) - .strokeBorder(.secondary, lineWidth: accessibility.increaseContrast ? 2 : 1) - } - .accessibilityElement(children: .contain) + .buttonStyle(.plain) + .accessibilityLabel( + AppearanceText.string( + "\(preset.appearanceTitle) palette. \(light.accessibilitySummary). \(dark.accessibilitySummary).") + ) + .accessibilityValue(configuration.palette == preset ? AppearanceText.string("Selected") : "") + .accessibilityAddTraits(configuration.palette == preset ? .isSelected : []) + .accessibilityIdentifier("settings.appearance.preview.\(preset.rawValue)") + } + + private func sample(mode: ConfigAppearanceMode) -> AppearancePreviewSample { + cache.sample( + configuration: configuration, preset: preset, mode: mode, accessibility: accessibility, + version: paletteVersion, cleanSpaceColor: cleanSpaceColor) } - private func preview(mode: ConfigAppearanceMode) -> some View { - let sample = AppearancePreviewSample( - configuration: configuration, preset: preset, mode: mode, accessibility: accessibility) - return VStack(alignment: .leading, spacing: 8) { + private func preview(sample: AppearancePreviewSample, mode: ConfigAppearanceMode) -> some View { + VStack(alignment: .leading, spacing: 8) { Text(mode.appearanceTitle).font(.caption).foregroundStyle(.secondary) scene(sample: sample) - .accessibilityHidden(true) - swatches(sample: sample, mode: mode) + swatches(sample: sample) } .frame(maxWidth: .infinity, alignment: .leading) - .accessibilityElement(children: .contain) - .accessibilityLabel(AppearanceText.string("\(preset.appearanceTitle), \(mode.appearanceTitle) preview")) - .accessibilityIdentifier("settings.appearance.preview.\(preset.rawValue).\(mode.rawValue)") + .accessibilityHidden(true) } - private func swatches(sample: AppearancePreviewSample, mode: ConfigAppearanceMode) -> some View { + private func swatches(sample: AppearancePreviewSample) -> some View { HStack(spacing: 6) { ForEach(AppearanceColorRole.allCases, id: \.self) { role in - swatch(sample: sample, mode: mode, role: role) + swatch(sample: sample, role: role) } } } - private func swatch(sample: AppearancePreviewSample, mode: ConfigAppearanceMode, role: AppearanceColorRole) - -> some View - { + private func swatch(sample: AppearancePreviewSample, role: AppearanceColorRole) -> some View { Circle() .fill(Color(cgColor: sample.color(for: role))) .overlay { Circle().strokeBorder(.secondary, lineWidth: 1) } .frame(width: 16, height: 16) .help(role.appearanceTitle) - .accessibilityElement(children: .ignore) - .accessibilityLabel(role.appearanceTitle) - .accessibilityIdentifier("settings.appearance.preview.\(preset.rawValue).\(mode.rawValue).\(role.rawValue)") + .accessibilityHidden(true) } private func scene(sample: AppearancePreviewSample) -> some View { - let radius = sample.configuration.borderRadius / 2 + let radius = sample.borderRadius let width: CGFloat = accessibility.increaseContrast ? 3 : 2 return HStack(spacing: 8) { RoundedRectangle(cornerRadius: radius) diff --git a/Sources/ParcelUI/Settings/FocusModePreferencesView.swift b/Sources/ParcelUI/Settings/FocusModePreferencesView.swift index 08706fac..1cda3708 100644 --- a/Sources/ParcelUI/Settings/FocusModePreferencesView.swift +++ b/Sources/ParcelUI/Settings/FocusModePreferencesView.swift @@ -51,8 +51,15 @@ struct FocusModePreferencesView: View { Text(color.settingsTitle).tag(color) } } + .disabled(appearanceControlsBackdrop) .accessibilityLabel(SettingsText.string("Backdrop color")) + .accessibilityHint(appearanceControlsBackdrop ? backdropExplanation : "") .accessibilityIdentifier("settings.focusModes.cleanSpaceColor") + if appearanceControlsBackdrop { + Text(backdropExplanation) + .font(.caption).foregroundStyle(.secondary) + .accessibilityLabel(backdropExplanation) + } Text(SettingsText.string("Clean Space clears on sleep, lock, or display disconnect.")) .font(.caption).foregroundStyle(.secondary) } @@ -60,6 +67,17 @@ struct FocusModePreferencesView: View { .formStyle(.grouped) } + private var appearanceControlsBackdrop: Bool { + model.configuration.appearance.palette != .system + || model.configuration.appearance.colors[.cleanSpaceBackdrop] != nil + } + + private var backdropExplanation: String { + AppearanceText.string( + "The Appearance palette or custom backdrop color controls Clean Space. Choose System and reset the backdrop override to use this picker." + ) + } + private func modeButton(_ command: ConfigCommand) -> some View { Button(command.settingsTitle) { Task { diff --git a/Sources/ParcelUI/Settings/SettingsDocumentEditor.swift b/Sources/ParcelUI/Settings/SettingsDocumentEditor.swift index 6eb8ea42..f9dc2816 100644 --- a/Sources/ParcelUI/Settings/SettingsDocumentEditor.swift +++ b/Sources/ParcelUI/Settings/SettingsDocumentEditor.swift @@ -4,6 +4,7 @@ import ParcelConfig enum SettingsEdit: Sendable { case value(SettingsField, TOMLValue) case values([(SettingsField, TOMLValue)]) + case removeAppearanceValues([String]) case shortcut(ConfigCommand, KeyChord?) case hoverPreferences(HoverBarConfiguration, onlyMissing: Bool) case addRule(FloatRule) @@ -34,6 +35,8 @@ enum SettingsDocumentEditor { for (field, value) in values { try document.setValue(value, forKey: field.path(in: document)) } + case .removeAppearanceValues(let keys): + for key in keys { try removeAppearanceValue(key, from: &document) } case .shortcut(let command, let chord): try document.setValue( chord.map { .string($0.description) } ?? .bool(false), forKey: ["keybindings", command.rawValue]) @@ -207,6 +210,39 @@ enum SettingsDocumentEditor { return range } + private static func removeAppearanceValue(_ key: String, from document: inout TOMLDocument) throws { + guard let value = document.node(forKey: ["appearance", key]) else { return } + guard let keyRange = value.keyRange, + let appearance = document.node(forKey: ["appearance"]), case .table(let entries) = appearance.value + else { + throw SettingsFailure( + AppearanceText.string( + "This appearance value cannot be safely reset. Edit it in the configuration file.")) + } + let scalars = Array(document.source.unicodeScalars) + var assignmentStart = keyRange.start.offset + while assignmentStart > 0, scalars[assignmentStart - 1] != "\n" { assignmentStart -= 1 } + var edits = [(removalRange(assignmentStart.. 0, + let comma = comma(in: scalars, from: ordered[index - 1].range.end.offset, to: keyRange.start.offset) + { + edits.append((comma..= 4.5) - for foreground in [colors.activeBorder, colors.inactiveBorder, colors.glow, colors.stackAccent] { - #expect(try contrast(foreground, background) >= 3) - #expect(foreground.alpha == 1) + let darkSurface = NSColor(srgbRed: 30.0 / 255, green: 30.0 / 255, blue: 30.0 / 255, alpha: 1).cgColor + for surface in [NSColor.white.cgColor, darkSurface] { + for border in [colors.activeBorder, colors.inactiveBorder] { + #expect(try contrast(border, surface) >= 3) + #expect(border.alpha == 1) } } #expect(colors.borderOpacity == 1) - let increased = source.resolve(for: appearance, accessibility: .init(increaseContrast: true)) - #expect(try contrast(increased.chipText, increased.chipBackground) >= 7) - for (normal, strong) in zip( - [colors.activeBorder, colors.inactiveBorder, colors.glow, colors.stackAccent], - [increased.activeBorder, increased.inactiveBorder, increased.glow, increased.stackAccent]) - { - #expect(try contrast(strong, increased.chipBackground) >= contrast(normal, colors.chipBackground)) + } + + @Test(arguments: ConfigAppearancePalette.allCases.filter { $0 != .system }, [false, true]) + func curatedInactiveBordersRecedeWithoutRelyingOnHue(palette: ConfigAppearancePalette, dark: Bool) throws { + let appearance = try #require(NSAppearance(named: dark ? .darkAqua : .aqua)) + let colors = OverlayPaletteSource(configuration: .init(palette: palette)) + .resolve(for: appearance, accessibility: .init()) + #expect(try contrast(colors.activeBorder, colors.inactiveBorder) >= 1.5) + let surface = dark ? NSColor.black.cgColor : NSColor.white.cgColor + #expect(try contrast(colors.activeBorder, surface) > contrast(colors.inactiveBorder, surface)) + } + + @Test(arguments: ConfigAppearancePalette.allCases.filter { $0 != .system }, [false, true]) + func curatedChipRolesContrastWithTheirOwnBackground(palette: ConfigAppearancePalette, dark: Bool) throws { + let appearance = try #require(NSAppearance(named: dark ? .darkAqua : .aqua)) + let colors = OverlayPaletteSource(configuration: .init(palette: palette)) + .resolve(for: appearance, accessibility: .init()) + #expect(try contrast(colors.chipText, colors.chipBackground) >= 4.5) + #expect(try contrast(colors.stackAccent, colors.chipBackground) >= 3) + } + + @Test(arguments: ConfigAppearancePalette.allCases, [false, true]) + func increasedContrastKeepsAccentsDistinctFromInactiveBorders(palette: ConfigAppearancePalette, dark: Bool) + throws + { + let appearance = try #require(NSAppearance(named: dark ? .darkAqua : .aqua)) + let colors = OverlayPaletteSource(configuration: .init(palette: palette)) + .resolve(for: appearance, accessibility: .init(increaseContrast: true)) + #expect(try contrast(colors.chipText, colors.chipBackground) >= 7) + #expect(try contrast(colors.inactiveBorder, colors.chipBackground) >= 7) + for accent in [colors.activeBorder, colors.glow, colors.stackAccent] { + #expect(try contrast(accent, colors.chipBackground) >= 7) + #expect(try contrast(accent, colors.inactiveBorder) >= 1.5) + #expect(accent != colors.chipText) + if palette != .system { + let rgb = try #require(NSColor(cgColor: accent)?.usingColorSpace(.sRGB)) + #expect( + max(rgb.redComponent, rgb.greenComponent, rgb.blueComponent) + - min(rgb.redComponent, rgb.greenComponent, rgb.blueComponent) > 0.01) + } } } @@ -482,13 +514,13 @@ extension AppKitTestSuite { #expect(palette.inactiveBorder == NSColor.secondaryLabelColor.cgColor) #expect(palette.chipBackground == NSColor.windowBackgroundColor.cgColor) #expect(palette.chipText == NSColor.labelColor.cgColor) - #expect(palette.cleanSpaceBackdrop == NSColor.windowBackgroundColor.cgColor) + #expect(palette.cleanSpaceBackdrop == nil) } for options in [OverlayAccessibility(reduceTransparency: true), .init(increaseContrast: true)] { let solid = source.resolve(for: appearance, accessibility: options) for role in [ solid.activeBorder, solid.inactiveBorder, solid.glow, solid.chipBackground, - solid.chipText, solid.stackAccent, try #require(solid.cleanSpaceBackdrop), + solid.chipText, solid.stackAccent, ] { #expect(role.alpha == 1) } @@ -538,7 +570,7 @@ extension AppKitTestSuite { #expect(strong.chipBackground != palette.chipBackground) } - @Test func paletteAndBorderSettingsRepaintRetainedLayersWithoutMovingWindows() throws { + @Test func paletteAndBorderSettingsRepaintWithoutMovingWindows() throws { let source = OverlayPaletteSource(configuration: .init(palette: .kiln)) let controller = OverlayController( configuration: .init(enabled: false, highlight: .all), accessibility: .init(), @@ -548,23 +580,65 @@ extension AppKitTestSuite { controller.setDisplays([display], primaryDisplayHeight: 220) controller.updateAndRender(OverlaySnapshot(windows: [first, second], focusedWindow: 1)) let tile = try #require(controller.focusLayers[display.id]) - let inactive = try #require(controller.highlightCanvases[display.id]?.inactive[2]) - let renderer = try #require(tile.highlightRenderer) - let mask = controller.highlightCanvases[display.id]?.mask.path - let path = renderer.stroke.path let frame = tile.layer.frame - let color = renderer.stroke.strokeColor + let color = tile.highlightRenderer?.stroke.strokeColor source.configure(.init(palette: .tide, borderOpacity: 0.4)) controller.renderPendingDisplays(at: CACurrentMediaTime() + 1) - #expect(controller.focusLayers[display.id] === tile) - #expect(controller.highlightCanvases[display.id]?.inactive[2] === inactive) - #expect(renderer.stroke.strokeColor != color && tile.layer.opacity == 0.4) - #expect(renderer.stroke.path === path && controller.highlightCanvases[display.id]?.mask.path === mask) + let recolored = try #require(controller.focusLayers[display.id]) + #expect(recolored.highlightRenderer?.stroke.strokeColor != color && recolored.layer.opacity == 0.4) + #expect(recolored.layer.frame == frame && controller.activeAnimationCount == 0) + try expectClearContent(image(controller), windows: [first, second]) source.configure(.init(palette: .tide, borderRadius: 24)) controller.renderPendingDisplays(at: CACurrentMediaTime() + 2) - #expect(tile.layer.cornerRadius == 24 && inactive.layer.cornerRadius == 24) - #expect(tile.layer.frame == frame && controller.activeAnimationCount == 0) - #expect(controller.highlightCanvases[display.id]?.mask.path === mask) + let rounded = try #require(controller.focusLayers[display.id]) + let inactive = try #require(controller.highlightCanvases[display.id]?.inactive[2]) + #expect(rounded.layer.cornerRadius == 24 && inactive.layer.cornerRadius == 24) + #expect(rounded.layer.frame == frame && controller.activeAnimationCount == 0) + try expectClearContent(image(controller), windows: [first, second]) + } + + @Test(arguments: [0.0, 10.0, 11.0, 40.0]) + func explicitRadiusOverridesNativeRadiusAndOmissionRestoresIt(radius: Double) throws { + let source = OverlayPaletteSource(configuration: .init()) + let controller = OverlayController( + configuration: .init(enabled: false, highlight: .all), + accessibility: .init(), brightness: TestOverlayBrightness(), paletteSource: source, + notifications: .isolatedForTesting, orderPanels: false, onFailure: { Issue.record($0) }) + defer { controller.stop() } + controller.setDisplays([display], primaryDisplayHeight: 220) + let window = OverlayWindow(id: 1, frame: first.frame, cornerRadius: 18) + controller.updateAndRender(OverlaySnapshot(windows: [window], focusedWindow: 1)) + #expect(controller.focusLayers[display.id]?.layer.cornerRadius == 18) + source.configure(.init(borderRadius: radius)) + controller.renderPendingDisplays(at: CACurrentMediaTime() + 1) + #expect(controller.focusLayers[display.id]?.layer.cornerRadius == CGFloat(radius)) + source.configure(.init()) + controller.renderPendingDisplays(at: CACurrentMediaTime() + 2) + #expect(controller.focusLayers[display.id]?.layer.cornerRadius == 18) + #expect(controller.focusLayers[display.id]?.layer.frame == display.localFrame(window.frame)) + #expect(controller.activeAnimationCount == 0) + } + + @Test func chromeRedrawDoesNotRecolorButPaletteAndAppearanceChangesDo() throws { + let source = OverlayPaletteSource(configuration: .init()) + let view = PaletteTrackingChromeView( + frame: CGRect(x: 0, y: 0, width: 100, height: 100), paletteSource: source) + let light = try #require(NSAppearance(named: .aqua)) + let darkAppearance = try #require(NSAppearance(named: .darkAqua)) + view.appearance = light + let before = view.paletteChanges + for _ in 0..<5 { + view.needsDisplay = true + view.displayIfNeeded() + } + #expect(view.paletteChanges == before) + let color = view.layer?.backgroundColor + view.appearance = darkAppearance + #expect(view.paletteChanges > before && view.layer?.backgroundColor != color) + let dark = view.layer?.backgroundColor + source.configure(.init(palette: .kiln)) + #expect(view.layer?.backgroundColor != dark) + #expect(view.layer?.animationKeys()?.isEmpty != false) } private func contrast(_ first: CGColor, _ second: CGColor) throws -> Double { @@ -626,22 +700,24 @@ extension AppKitTestSuite { defer { controller.stop() } controller.setDisplays([display], primaryDisplayHeight: 220) controller.updateAndRender(OverlaySnapshot(windows: [first], focusedWindow: 1)) - let canvas = try #require(controller.highlightCanvases[display.id]) - let renderer = try #require(controller.focusLayers[display.id]?.highlightRenderer) - let path = renderer.stroke.path - let mask = canvas.mask.path - let color = renderer.stroke.strokeColor + let tile = try #require(controller.focusLayers[display.id]) + let frame = tile.layer.frame + let color = tile.highlightRenderer?.stroke.strokeColor application.appearance = dark - try await waitForUI("Appearance restyles a retained border") { + try await waitForUI("Appearance restyles the border") { controller.renderPendingDisplays(at: CACurrentMediaTime()) - return renderer.stroke.strokeColor != color + return controller.focusLayers[display.id]?.highlightRenderer?.stroke.strokeColor != color } - #expect(renderer.stroke.path === path && canvas.mask.path === mask) - let darkColor = renderer.stroke.strokeColor + let recolored = try #require(controller.focusLayers[display.id]) + #expect(recolored.layer.frame == frame && controller.activeAnimationCount == 0) + try expectClearContent(image(controller), windows: [first]) + let darkColor = recolored.highlightRenderer?.stroke.strokeColor source.setResolver { _, _ in .system(activeBorder: .systemOrange) } controller.renderPendingDisplays(at: CACurrentMediaTime()) - #expect(renderer.stroke.strokeColor != darkColor) - #expect(renderer.stroke.path === path && canvas.mask.path === mask) + let changed = try #require(controller.focusLayers[display.id]) + #expect(changed.highlightRenderer?.stroke.strokeColor != darkColor) + #expect(changed.layer.frame == frame && controller.activeAnimationCount == 0) + try expectClearContent(image(controller), windows: [first]) } @Test func visibilityReadsHaveOneInFlightAndOneTrailingRead() async throws { @@ -770,6 +846,15 @@ extension AppKitTestSuite { } } +@MainActor +private final class PaletteTrackingChromeView: OverlayChromeView { + var paletteChanges = 0 + override func applyPalette(_ palette: OverlayPalette) { + paletteChanges += 1 + super.applyPalette(palette) + } +} + @Suite struct HighlightGeometryTests { @Test @MainActor func engineAdapterKeepsSheetCutoutsWhenPrivacyModesAreOff() { let app = AppID(pid: 123, bundleID: "dev.parcel.highlight-test") diff --git a/Tests/ParcelUITests/Overlays/PrivacyOverlayTests.swift b/Tests/ParcelUITests/Overlays/PrivacyOverlayTests.swift index ab38c35f..445fe47e 100644 --- a/Tests/ParcelUITests/Overlays/PrivacyOverlayTests.swift +++ b/Tests/ParcelUITests/Overlays/PrivacyOverlayTests.swift @@ -134,17 +134,44 @@ extension AppKitTestSuite { controller.updateAndRender(snapshot(noPeek: true)) let panel = try #require(controller.privacyPanels[primary.id]) #expect(!panel.usesBlur && panel.tintOpacity == 0.1) - if accessibility.increaseContrast { - let appearance = try #require(controller.panels[primary.id]?.effectiveAppearance) - let palette = OverlayPaletteSource.shared.resolve(for: appearance, accessibility: accessibility) - #expect(panel.tintColor.cgColor == palette.cleanSpaceBackdrop) - } else { - #expect(panel.tintColor == ConfigCleanSpaceColor.mist.backdropColor) - } + #expect(panel.tintColor == ConfigCleanSpaceColor.mist.backdropColor) #expect(panel.contentView?.layer?.animationKeys()?.isEmpty != false) #expect(brightness.writes.isEmpty) } + @Test( + arguments: [ConfigAppearanceMode.light, .dark], + [OverlayAccessibility(), OverlayAccessibility(increaseContrast: true)]) + func systemCleanSpaceHonorsEveryBackdropChoiceIncludingDefault( + mode: ConfigAppearanceMode, accessibility: OverlayAccessibility + ) throws { + let source = OverlayPaletteSource(configuration: .init(mode: mode)) + let controller = OverlayController( + configuration: .init(enabled: false), accessibility: accessibility, + brightness: TestOverlayBrightness(), paletteSource: source, notifications: .isolatedForTesting, + orderPanels: false, onFailure: { Issue.record($0) }) + defer { controller.stop() } + controller.setDisplays([primary], primaryDisplayHeight: 600) + controller.updateAndRender(snapshot(cleanSpace: true)) + #expect(controller.backdrops[primary.id]?.backgroundColor == ConfigCleanSpaceColor.graphite.backdropColor) + for color in [ConfigCleanSpaceColor.mist, .stone, .graphite] { + controller.updateAndRender( + configuration: controller.configuration, accessibility: accessibility, + focusModes: .init(cleanSpaceColor: color)) + #expect(controller.backdrops[primary.id]?.backgroundColor == color.backdropColor) + #expect(controller.privacyPanels[primary.id]?.tintColor == color.backdropColor) + } + let custom = try #require(AppearanceHexColor(hex: "#123456")) + source.configure(.init(mode: mode, colors: [.cleanSpaceBackdrop: custom])) + controller.renderPendingDisplays(at: CACurrentMediaTime() + 1) + let appearance = try #require(controller.panels[primary.id]?.effectiveAppearance) + let palette = source.resolve(for: appearance, accessibility: accessibility) + #expect(controller.backdrops[primary.id]?.backgroundColor?.cgColor == palette.cleanSpaceBackdrop) + source.configure(.init(mode: mode)) + controller.renderPendingDisplays(at: CACurrentMediaTime() + 2) + #expect(controller.backdrops[primary.id]?.backgroundColor == ConfigCleanSpaceColor.graphite.backdropColor) + } + @Test func paletteChangeRecolorsRetainedCleanSpacePanelsWithoutWindowChanges() throws { let source = OverlayPaletteSource(configuration: .init(mode: .light)) let controller = OverlayController( @@ -168,11 +195,16 @@ extension AppKitTestSuite { controller.renderPendingDisplays(at: CACurrentMediaTime() + 1) let appearance = try #require(controller.panels[primary.id]?.effectiveAppearance) let palette = source.resolve(for: appearance, accessibility: .init()) - #expect(controller.backdrops[primary.id] === backdrop && controller.privacyPanels[primary.id] === privacy) - #expect(backdrop.backgroundColor != color && backdrop.backgroundColor.cgColor == palette.cleanSpaceBackdrop) - #expect(privacy.tintColor.cgColor == palette.cleanSpaceBackdrop && privacy.tintOpacity == 1) - #expect(backdrop.frame == frame && privacy.regions == regions) - #expect(!backdrop.isVisible && !privacy.isVisible) + let recoloredBackdrop = try #require(controller.backdrops[primary.id]) + let recoloredPrivacy = try #require(controller.privacyPanels[primary.id]) + #expect( + recoloredBackdrop.backgroundColor != color + && recoloredBackdrop.backgroundColor.cgColor == palette.cleanSpaceBackdrop) + #expect( + recoloredPrivacy.tintColor.cgColor == palette.cleanSpaceBackdrop && recoloredPrivacy.tintOpacity == 1) + #expect(recoloredBackdrop.frame == frame && recoloredPrivacy.regions == regions) + #expect(!recoloredBackdrop.isVisible && !recoloredPrivacy.isVisible) + #expect(controller.activeAnimationCount == 0) } @Test func missingVerifierUsesTheIntendedOverlayWithoutWarning() { diff --git a/Tests/ParcelUITests/SettingsAccessibilityTests.swift b/Tests/ParcelUITests/SettingsAccessibilityTests.swift index 147bfdb9..cf5340f4 100644 --- a/Tests/ParcelUITests/SettingsAccessibilityTests.swift +++ b/Tests/ParcelUITests/SettingsAccessibilityTests.swift @@ -68,32 +68,124 @@ extension AppKitTestSuite { } } - @Test func everyPalettePreviewNamesBothModesAndEveryColorRole() async throws { - #expect( - Set(ConfigAppearancePalette.allCases.map(\.appearanceTitle)).count - == ConfigAppearancePalette.allCases.count) - #expect( - Set(ConfigAppearanceMode.allCases.map(\.appearanceTitle)).count == ConfigAppearanceMode.allCases.count) + @Test func eachPaletteIsOneKeyboardReachableVoiceOverButtonWithColorSummary() async throws { for preset in ConfigAppearancePalette.allCases { + var selections = 0 try await withAppearanceAccessibilityHost( - AppearancePaletteCard(configuration: .init(), preset: preset, accessibility: .init()) - ) { elements, _ in - for mode in [ConfigAppearanceMode.light, .dark] { - let identifier = "settings.appearance.preview.\(preset.rawValue).\(mode.rawValue)" - let preview = try #require(elements.first { $0.accessibilityIdentifier() == identifier }) - #expect(preview.accessibilityLabel()?.isEmpty == false) - #expect(preview.accessibilityRole() != nil) - for role in AppearanceColorRole.allCases { - let swatch = try #require( - elements.first { - $0.accessibilityIdentifier() == "\(identifier).\(role.rawValue)" - }) - #expect(swatch.accessibilityLabel()?.isEmpty == false) - #expect(swatch.accessibilityRole() != nil) - } + AppearancePaletteCard( + configuration: .init(palette: preset), preset: preset, + accessibility: .init(), select: { selections += 1 }) + ) { elements, navigation in + let identifier = "settings.appearance.preview.\(preset.rawValue)" + let previews = elements.filter { $0.accessibilityIdentifier()?.hasPrefix(identifier) == true } + #expect(previews.count == 1) + let preview = try #require(previews.first) + #expect(preview.accessibilityRole() == .button) + #expect(preview.children(navigation: false).isEmpty) + #expect(navigation.contains { $0.isEqual(preview) }) + let label = try #require(preview.accessibilityLabel()) + #expect(label.contains(preset.appearanceTitle)) + for mode in [ConfigAppearanceMode.light, .dark] { #expect(label.contains(mode.appearanceTitle)) } + for role in AppearanceColorRole.allCases { #expect(label.contains(role.appearanceTitle)) } + #expect(label.contains("#")) + let valueSelector = NSSelectorFromString("accessibilityValue") + try #require(preview.object.responds(to: valueSelector)) + #expect(preview.object.value(forKey: "accessibilityValue") as? String == "Selected") + let press = NSSelectorFromString("accessibilityPerformPress") + try #require(preview.object.responds(to: press)) + _ = preview.object.perform(press) + } + #expect(selections == 1) + } + } + + @Test(arguments: [ + "", "[appearance]\npalette = 'kiln'\n", "[appearance]\nclean-space-backdrop-color = '#123456'\n", + ]) + func focusBackdropPickerExplainsWhenAppearanceControlsItsColor(source: String) async throws { + let file = FileManager.default.temporaryDirectory.appendingPathComponent("focus-appearance-\(UUID()).toml") + try Data(source.utf8).write(to: file) + defer { + do { try FileManager.default.removeItem(at: file) } catch { Issue.record(error) } + } + let model = SettingsModel(store: ConfigStore(fileURL: file)) + await model.start() + do { + try await withAppearanceAccessibilityHost(FocusModePreferencesView(model: model)) { elements, _ in + let picker = try #require( + elements.first { + $0.accessibilityIdentifier() == "settings.focusModes.cleanSpaceColor" + }) + #expect(picker.isAccessibilityEnabled() == source.isEmpty) + if !source.isEmpty { + try #require(picker.object.responds(to: NSSelectorFromString("accessibilityHelp"))) + let help = try #require(picker.object.value(forKey: "accessibilityHelp") as? String) + #expect(help.contains("controls Clean Space")) + } + } + } catch { + await model.stop() + throw error + } + await model.stop() + } + + @Test func customColorValuesAreReadableAndResetButtonsClearTheOverrides() async throws { + let file = FileManager.default.temporaryDirectory.appendingPathComponent("appearance-colors-\(UUID()).toml") + let source = "[appearance]\nactive-border-color = '#123456'\nchip-text-color = '#ABCDEF'\n" + try Data(source.utf8).write(to: file) + defer { + do { try FileManager.default.removeItem(at: file) } catch { Issue.record(error) } + } + let model = SettingsModel(store: ConfigStore(fileURL: file)) + await model.start() + do { + try await withAppearanceAccessibilityHost(AppearancePreferencesView(model: model)) { + elements, navigation in + for (role, hex) in [(AppearanceColorRole.activeBorder, "#123456"), (.chipText, "#ABCDEF")] { + let summary = "\(role.appearanceTitle) \(hex)" + #expect( + elements.contains { element in + if element.accessibilityLabel() == summary || element.accessibilityTitle() == summary { + return true + } + guard element.object.responds(to: NSSelectorFromString("accessibilityValue")) else { + return false + } + return element.object.value(forKey: "accessibilityValue") as? String == summary + }) } + let reset = try #require( + elements.first { + $0.accessibilityIdentifier() == "settings.appearance.override.active-border-color.reset" + }) + #expect(reset.accessibilityRole() == .button) + #expect(navigation.contains { $0.isEqual(reset) }) + let press = NSSelectorFromString("accessibilityPerformPress") + try #require(reset.object.responds(to: press)) + _ = reset.object.perform(press) + } + try await waitForUI("The appearance pane clears one override") { + model.configuration.appearance.colors[.activeBorder] == nil + } + #expect(model.configuration.appearance.colors[.chipText]?.hex == "#ABCDEF") + try await withAppearanceAccessibilityHost(AppearancePreferencesView(model: model)) { elements, _ in + let reset = try #require( + elements.first { + $0.accessibilityIdentifier() == "settings.appearance.overrides.reset" + }) + let press = NSSelectorFromString("accessibilityPerformPress") + try #require(reset.object.responds(to: press)) + _ = reset.object.perform(press) + } + try await waitForUI("The appearance pane clears remaining overrides") { + model.configuration.appearance.colors.isEmpty } + } catch { + await model.stop() + throw error } + await model.stop() } @Test func recorderIsLabelledAndAcceptsKeyboardFocus() { diff --git a/Tests/ParcelUITests/SettingsTests.swift b/Tests/ParcelUITests/SettingsTests.swift index e14716c4..1855b406 100644 --- a/Tests/ParcelUITests/SettingsTests.swift +++ b/Tests/ParcelUITests/SettingsTests.swift @@ -102,6 +102,50 @@ struct SettingsTests { } } + @Test(arguments: [ + "[appearance]\nborder-radius = 10 # radius\npalette = 'tide'\n", + "appearance.border-radius = 10 # radius\nappearance.palette = 'tide'\n", + "appearance = { border-radius = 10, palette = 'tide' } # radius\n", + "appearance = { palette = 'tide', border-radius = 10 } # radius\n", + ]) + func resettingRadiusRemovesOnlyTheExplicitOverride(source: String) async throws { + try await withSettings(source: source) { model, file in + #expect(model.configuration.appearance.borderRadius == 10) + try await model.setAppearanceBorderRadius(nil) + #expect(model.configuration.appearance.borderRadius == nil) + #expect(model.configuration.appearance.palette == .tide) + let reset = try file.read() + #expect(reset.contains("# radius")) + #expect(try TOMLDocument(parsing: reset).node(forKey: ["appearance", "border-radius"]) == nil) + try await model.setAppearanceBorderRadius(10) + #expect(model.configuration.appearance.borderRadius == 10) + await #expect(throws: SettingsFailure.self) { try await model.setAppearanceBorderRadius(41) } + #expect(model.configuration.appearance.borderRadius == 10) + } + } + + @Test(arguments: [ + "[appearance]\npalette = 'kiln'\nactive-border-color = '#123456' # active\nchip-text-color = '#ABCDEF' # text\n", + "appearance = { palette = 'kiln', active-border-color = '#123456', chip-text-color = '#ABCDEF' } # custom\n", + "appearance.active-border-color = '#123456' # active\nappearance.palette = 'kiln'\nappearance.chip-text-color = '#ABCDEF' # text\n", + ]) + func resettingCustomColorsPreservesOtherRolesThenClearsAllOverrides(source: String) async throws { + try await withSettings(source: source + "[layout]\nratio = 0.6 # layout\n") { model, file in + let text = model.configuration.appearance.colors[.chipText] + try await model.resetAppearanceColors([.activeBorder]) + #expect(model.configuration.appearance.colors == [.chipText: try #require(text)]) + #expect(model.configuration.appearance.palette == .kiln) + try await model.resetAppearanceColors() + #expect(model.configuration.appearance.colors.isEmpty) + #expect(model.configuration.appearance.palette == .kiln) + #expect(model.configuration.layout.global.ratio == 0.6) + #expect(try file.read().contains("ratio = 0.6 # layout")) + let reset = try file.read() + try await model.resetAppearanceColors() + #expect(try file.read() == reset) + } + } + @Test func externalAppearanceChangesRefreshSettingsWithoutCommands() async throws { let commands = AppearanceSettingsCommands() try await withSettings(source: "# preferences\n", commands: commands) { model, file in @@ -941,6 +985,55 @@ extension AppKitTestSuite { #expect(configuration.mode == .dark) } + @Test(arguments: [0.0, 10.0, 40.0]) + func previewsShowRadiusInPointsWithoutHalvingIt(radius: Double) { + let sample = AppearancePreviewSample( + configuration: .init(borderRadius: radius), preset: .kiln, + mode: .light, accessibility: .init()) + #expect(sample.borderRadius == radius) + } + + @Test func previewCacheReusesSamplesUntilInputsOrSystemColorsChange() throws { + var resolutions = 0 + let cache = AppearancePreviewCache { configuration, preset, mode, accessibility, cleanSpaceColor in + resolutions += 1 + return AppearancePreviewSample( + configuration: configuration, preset: preset, mode: mode, + accessibility: accessibility, cleanSpaceColor: cleanSpaceColor) + } + var configuration = AppearanceConfiguration() + var options = OverlayAccessibility() + var version: UInt64 = 1 + var backdrop = ConfigCleanSpaceColor.graphite + func sample(_ mode: ConfigAppearanceMode = .light, preset: ConfigAppearancePalette = .system) + -> AppearancePreviewSample + { + cache.sample( + configuration: configuration, preset: preset, mode: mode, accessibility: options, + version: version, cleanSpaceColor: backdrop) + } + let light = sample() + let dark = sample(.dark) + for _ in 0..<10 { _ = sample(); _ = sample(.dark) } + #expect(resolutions == 2) + #expect(light.windowBackground != dark.windowBackground) + let custom = try #require(AppearanceHexColor(hex: "#123456")) + configuration.colors[.activeBorder] = custom + #expect(sample().palette.activeBorder != light.palette.activeBorder) + #expect(resolutions == 3) + options.increaseContrast = true + #expect(sample().palette.borderOpacity == 1) + #expect(resolutions == 4) + version += 1 + _ = sample() + #expect(resolutions == 5) + backdrop = .mist + #expect(sample().color(for: .cleanSpaceBackdrop) == backdrop.backdropColor.cgColor) + #expect(resolutions == 6) + _ = sample(preset: .kiln) + #expect(resolutions == 7) + } + @Test func previewsIncludeCustomRolesAndAccessibleBorderOpacity() throws { let custom = try #require(AppearanceHexColor(hex: "#123456")) let configuration = AppearanceConfiguration( diff --git a/docs/configuration.md b/docs/configuration.md index 78052389..1aafaeab 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -67,7 +67,8 @@ prefix. Motion can be disabled globally; Reduce Motion always takes precedence. `system` keeps native macOS colors. Six palettes are available: `kiln` (Parcel’s house terracotta, ochre, and teal), `tide`, `grove`, `iris`, `dusk`, and `rose`. -`mode` is `system`, `light`, or `dark` and affects only Parcel’s chrome, not apps. +`mode` is `system`, `light`, or `dark` and affects Parcel’s windows and chrome, +not other apps. Changes apply instantly without moving windows or changing layout. ```toml @@ -80,13 +81,16 @@ active-border-color = "#B65C44" ``` `border-opacity` accepts `0`–`1` (default `1`); `border-radius` accepts `0`–`40` -points (default `10`, matching the window chrome). Optional overrides use exactly +points. Omit `border-radius` to match each window’s native corner radius. Every +explicit value, including `10`, uses that radius. Optional overrides use exactly `#RRGGBB`: `active-border-color`, `inactive-border-color`, `glow-color`, `chip-background-color`, `chip-text-color`, `stack-accent-color`, and -`clean-space-backdrop-color`. Omitted roles use the palette. With `system`, a -non-default `focus-modes.clean-space-color` (`mist` or `stone`) still applies -unless an explicit backdrop override or Increase Contrast takes priority. Named -palettes replace that legacy backdrop choice. +`clean-space-backdrop-color`. Omitted roles use the palette. With `system`, +`focus-modes.clean-space-color` keeps its `graphite`, `mist`, or `stone` backdrop, +including under Increase Contrast. Named palettes and explicit backdrop overrides +control that color instead; the Focus modes picker explains when it is disabled. +Settings lists custom overrides and can reset one role or all of them. Palette +preview cards select a palette and summarize both modes for VoiceOver. Custom colors and reduced border opacity are not guaranteed to meet WCAG contrast requirements. Accessibility preferences, including Increase Contrast diff --git a/docs/parcel.schema.json b/docs/parcel.schema.json index 0ffba209..b0ee6692 100644 --- a/docs/parcel.schema.json +++ b/docs/parcel.schema.json @@ -16,7 +16,7 @@ }, "appearance" : { "additionalProperties" : true, - "description" : "System uses native colors. Appearance updates instantly without changing layout; mode affects only Parcel chrome. Accessibility preferences take priority over color overrides.", + "description" : "System uses native colors. Appearance updates instantly without changing layout; mode affects Parcel's windows and chrome, not other apps. Accessibility preferences take priority over color overrides.", "properties" : { "active-border-color" : { "description" : "Optional exact sRGB #RRGGBB override; omitted roles use the selected palette.", @@ -32,7 +32,7 @@ "type" : "number" }, "border-radius" : { - "default" : 10, + "description" : "Optional radius in points; omitted means match each window's native corner radius.", "maximum" : 40, "minimum" : 0, "type" : "number" -- knotmirror 0.0.1