Skip to content

Commit

Permalink
Fix issue with color values shown from palettes being slightly differ…
Browse files Browse the repository at this point in the history
…ent from the original
  • Loading branch information
sindresorhus committed Jul 3, 2024
1 parent 231ce1d commit 21be057
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Color Picker/MainScreen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ private struct ColorPaletteTip: Tip {
}

var message: Text? {
Text("To create a new color palette, click the third tab at the top of the window, click the \(Image(systemName: "ellipsis.circle")) button, and then select “New”.")
Text("Click the third tab at the top of the window, click the \(Image(systemName: "ellipsis.circle")) button, and then select “New”.")
}

var image: Image? {
Expand Down
50 changes: 49 additions & 1 deletion Color Picker/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3605,9 +3605,57 @@ extension XColor {
}


extension XColor {
/**
Returns the color space of the color if it is component-based.
The normal property throws an exception on invalid access.
*/
var colorSpaceSafe: NSColorSpace? {
type == .componentBased ? colorSpace : nil
}
}


extension XColor {
/**
Reinterprets the color as sRGB if it is in a generic RGB or generic gray color space.
Use-case: Color palettes on macOS are usually in generic RGB, while the author actually intended them to be sRGB. This corrects that.
*/
func reinterpretedAsSRGBIfGeneric() -> Self {
guard [.genericGray, .genericRGB].contains(colorSpaceSafe) else {
return self
}

// For `.genericGray`.
guard let color = usingColorSpace(.genericRGB) else {
return self
}

// swiftlint:disable no_cgfloat
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
// swiftlint:enable no_cgfloat

color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

return .init(
srgbRed: red,
green: green,
blue: blue,
alpha: alpha
)
}
}


extension NSColorPanel {
var resolvedColor: Color.Resolved {
get { color.toResolvedColor }
// Most palettes are in generic RGB color space, and the conversion to sRGB is lossy and suprising. Do what the user expects and reinterpret the values as sRGB.
get { color.reinterpretedAsSRGBIfGeneric().toResolvedColor }
set {
color = newValue.toXColor
}
Expand Down

0 comments on commit 21be057

Please sign in to comment.