4 Commits
Author SHA1 Message Date
acheronfail 5c7e1b61d7 version 1.1.0 2018-05-25 11:39:33 +10:00
acheronfail 57da81bc29 feat: support for colorspaces; improvements to color extraction;
This commit adds support for color spaces - now the app should display the *exact* colors of the pixels on your screen. If you'd like to use other color spaces, those can be chosen from within the app's menu.
This also improves the calculation logic for retrieving the correct values from an NSColor (before the fence-post error was returning *very very* slightly incorrect values). Since colors on macOS are represented as Float values, there's only so much precision we can have.
We also now use a custom bitmap context to extract the color from the CGImage, this is to ensure the color we extract is in the correct color space.

Fixes #12
2018-05-25 11:37:27 +10:00
acheronfail 86c4b29ed5 fix: sometimes hex values would be shorter than 6 characters 2018-05-23 22:06:48 +10:00
acheronfail 88f3465f27 fix: preview crosshair now wraps the center pixel better 2018-05-22 19:37:50 +10:00
9 changed files with 275 additions and 128 deletions
+37 -15
View File
@@ -69,6 +69,7 @@ extension AppDelegate: NSMenuDelegate {
buildRecentPicks()
contextMenu.addItem(.separator())
buildColorSpaceItem()
buildColorFormatsMenu()
buildMagnificationItem()
buildConcentrationMenu()
@@ -81,6 +82,30 @@ extension AppDelegate: NSMenuDelegate {
contextMenu.addItem(withTitle: "Quit \(APP_NAME)", action: #selector(quitApplication), keyEquivalent: "")
}
// A menu that allows choosing what color space the picker will use.
private func buildColorSpaceItem() {
let submenu = NSMenu()
let defaultItem = submenu.addItem(withTitle: "Default (infer from screen)", action: #selector(setColorSpace(_:)), keyEquivalent: "")
defaultItem.state = PPState.shared.colorSpace == nil ? .on : .off
submenu.addItem(.separator())
for (title, name) in PPColor.colorSpaceNames {
let item = submenu.addItem(withTitle: title, action: #selector(setColorSpace(_:)), keyEquivalent: "")
item.representedObject = name
item.state = PPState.shared.colorSpace == name ? .on : .off
}
let item = contextMenu.addItem(withTitle: "Color Space", action: nil, keyEquivalent: "")
item.submenu = submenu
}
// If the selected color space is nil, then the preview will just infer the color space from
// the screen the picker is currently on.
@objc private func setColorSpace(_ sender: NSMenuItem) {
PPState.shared.colorSpace = sender.representedObject as? String
}
// A menu which allows the magnification level of the picker to be adjusted.
private func buildMagnificationItem() {
let submenu = NSMenu()
for i in stride(from: 4, through: 24, by: 2) {
@@ -98,6 +123,7 @@ extension AppDelegate: NSMenuDelegate {
}
}
// Simple launch app at login menu item.
private func buildLaunchAtLoginItem() {
let item = contextMenu.addItem(withTitle: "Launch \(APP_NAME) at Login", action: #selector(launchAtLogin(_:)), keyEquivalent: "")
item.state = LaunchAtLogin.isEnabled ? .on : .off
@@ -132,7 +158,7 @@ extension AppDelegate: NSMenuDelegate {
copyToPasteboard(stringValue: value)
}
}
// Simply creates a circle NSImage with the given size and color.
private func circleImage(withSize size: CGFloat, color: NSColor) -> NSImage {
let image = NSImage(size: NSSize(width: size, height: size))
@@ -142,7 +168,7 @@ extension AppDelegate: NSMenuDelegate {
image.unlockFocus()
return image
}
// A slider to change the float precision.
private func buildFloatPrecisionSlider() {
contextMenu.addItem(withTitle: "Float Precision (\(PPState.shared.floatPrecision))", action: nil, keyEquivalent: "")
@@ -161,23 +187,23 @@ extension AppDelegate: NSMenuDelegate {
item.view!.autoresizingMask = .width
item.view!.addSubview(slider)
}
// Called when the slider is updated.
@objc private func sliderUpdate(_ sender: NSSlider) {
let newValue = UInt(sender.intValue)
// Update slider title.
if let item = contextMenu.item(withTitle: "Float Precision (\(PPState.shared.floatPrecision))") {
item.title = "Float Precision (\(newValue))"
}
// Update state.
PPState.shared.floatPrecision = newValue
// Update recent picks list with new precision.
updateMenuItems()
}
// Build a submenu with each case in the PPColor enum.
// TODO: with Swift 4.2, we shouldn't need to resort to the hacky "iterateEnum" approach.
private func buildColorFormatsMenu() {
@@ -191,16 +217,14 @@ extension AppDelegate: NSMenuDelegate {
let item = contextMenu.addItem(withTitle: "Color Format", action: nil, keyEquivalent: "")
item.submenu = submenu
}
// Set the selected format as the default.
@objc private func selectFormat(_ sender: NSMenuItem) {
if let format = sender.representedObject as? PPColor {
PPState.shared.chosenFormat = format
sender.menu?.items.forEach({ $0.state = .off })
sender.state = .on
}
}
// Builds and adds the concentration modifier submenu.
private func buildConcentrationMenu() {
let submenu = NSMenu()
@@ -213,16 +237,14 @@ extension AppDelegate: NSMenuDelegate {
let item = contextMenu.addItem(withTitle: "Concentration Modifier", action: nil, keyEquivalent: "")
item.submenu = submenu
}
// Set the chosen modifier to toggle "concentrationMode".
@objc private func selectModifier(_ sender: NSMenuItem) {
if let modifier = sender.representedObject as? NSEvent.ModifierFlags {
PPState.shared.concentrationModeModifier = modifier
sender.menu?.items.forEach({ $0.state = .off })
sender.state = .on
}
}
// Builds and adds the MASShortcutView to be used in the menu.
// Uses a custom view to handle events correctly (since it's inside a NSMenu).
private func buildShortcutMenuItem() {
@@ -231,7 +253,7 @@ extension AppDelegate: NSMenuDelegate {
let shortcutView = MASShortcutView()
shortcutView.shortcutValue = PPState.shared.activatingShortcut
shortcutView.shortcutValueChange = { PPState.shared.activatingShortcut = $0?.shortcutValue }
let item = contextMenu.addItem(withTitle: "Shortcut", action: nil, keyEquivalent: "")
item.view = PPMenuShortcutView(shortcut: shortcutView)
}
+2 -2
View File
@@ -17,9 +17,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0.2</string>
<string>1.1.0</string>
<key>CFBundleVersion</key>
<string>3</string>
<string>4</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.utilities</string>
<key>LSMinimumSystemVersion</key>
+10
View File
@@ -26,6 +26,16 @@ extension NSColor {
return nil
}
// Creates an NSImage with the given size and color.
func image(withSize size: NSSize) -> NSImage {
let image = NSImage(size: size)
image.lockFocus()
self.set()
NSRect(origin: NSPoint.zero, size: size).fill()
image.unlockFocus()
return image
}
// Returns either black or white, whichever will contrast the most with the given color.
// See https://stackoverflow.com/a/3943023/5552584
func bestContrastingColor() -> NSColor {
@@ -15,7 +15,7 @@ class PPOverlayController: NSWindowController {
// Outlets relating to the picker's info box.
@IBOutlet weak var infoPanel: PPOverlayPanel!
@IBOutlet weak var infoBox: NSBox!
@IBOutlet weak var infoWrapper: NSView!
@IBOutlet weak var infoFormatField: NSTextField!
@IBOutlet weak var infoDetailField: NSTextField!
@@ -25,7 +25,7 @@ class PPOverlayController: NSWindowController {
var concentrationMode: Bool = false {
didSet {
if isEnabled {
panelSize = concentrationMode ? 300 : 150
panelSize = concentrationMode ? PPOverlayController.panelSizeLarge : PPOverlayController.panelSizeNormal
overlayPanel.activate(withSize: panelSize, infoPanel: infoPanel)
wrapper.layer?.cornerRadius = PPState.shared.paschaModeEnabled ? 0 : panelSize / 2
CGAssociateMouseAndMouseCursorPosition(boolean_t(truncating: concentrationMode ? 0 : 1))
@@ -33,9 +33,10 @@ class PPOverlayController: NSWindowController {
}
}
// The size of the pixel picker.
// TODO: use constants rather than hard-coded values.
private var panelSize: CGFloat = 150
// The current and different sizes of the pixel picker.
private static let panelSizeNormal: CGFloat = 150
private static let panelSizeLarge: CGFloat = 300
private var panelSize: CGFloat = PPOverlayController.panelSizeNormal
// The app that was last active before the picker was activated. We keep track
// of this in order to fully restore first responder status after picking a pixel.
@@ -61,6 +62,11 @@ class PPOverlayController: NSWindowController {
}
override func awakeFromNib() {
// Setup the info window.
infoWrapper.wantsLayer = true
infoWrapper.layer?.cornerRadius = 8
infoWrapper.layer?.backgroundColor = NSColor.black.cgColor
// For some reason if we don't listen for events this way we miss the escape key.
NSEvent.addLocalMonitorForEvents(matching: [.keyDown]) {
if self.isEnabled { self.keyDown(with: $0) }
@@ -209,7 +215,7 @@ class PPOverlayController: NSWindowController {
// Updates the info panel with the correct colors and text.
func updateInfoPanel(_ color: NSColor, _ contrastingColor: NSColor) {
infoBox.fillColor = color.alphaComponent == 0 ? NSColor.black : color
infoWrapper.layer?.backgroundColor = color.cgColor
infoFormatField.textColor = contrastingColor
infoDetailField.textColor = contrastingColor
infoFormatField.stringValue = PPState.shared.chosenFormat.rawValue
@@ -232,8 +238,11 @@ class PPOverlayController: NSWindowController {
overlayPanel.activate(withSize: panelSize, infoPanel: infoPanel)
}
// Center the mouse in the picker window.
overlayPanel.setFrameOrigin(NSPoint(x: point.x - (panelSize / 2), y: point.y - (panelSize / 2)))
let normalisedPoint = NSPoint(x: round(point.x * 2) / 2, y: round(point.y * 2) / 2)
if let screenShot = getScreenShot(aroundPoint: normalisedPoint) {
// Calculate a zoomed rect which will crop the screenshot we took.
let magnification = CGFloat(PPState.shared.magnificationLevel)
let zoomReciprocal: CGFloat = 1.0 / (concentrationMode ? magnification * 2.5 : magnification)
@@ -244,28 +253,115 @@ class PPOverlayController: NSWindowController {
// Ensure preview size is an odd number (so there's a middle pixel).
let zoomedSize = floor(ensureOdd(currentSize * zoomReciprocal))
let middle = zoomedSize / 2
let croppedRect = CGRect(x: x, y: y, width: zoomedSize, height: zoomedSize)
let zoomedImage: CGImage = screenShot.cropping(to: croppedRect)!
let pixelSize = panelSize / zoomedSize
let middlePosition = zoomedSize / 2
// Extract the middle pixel color from the zoomed image.
let bitmap = NSBitmapImageRep(cgImage: zoomedImage)
bitmap.colorSpaceName = .calibratedRGB
if let colorAtPixel = bitmap.colorAt(x: Int(middle), y: Int(middle)) {
let contrastingColor = colorAtPixel.bestContrastingColor()
// Convert the preview to the correct color space, and update the overlay.
preview.layer?.contents = NSImage(cgImage: zoomedImage, size: NSSize(width: panelSize, height: panelSize))
preview.updateCrosshair(panelSize / zoomedSize, middle, contrastingColor.cgColor)
wrapper.update(contrastingColor.cgColor)
updateInfoPanel(colorAtPixel, contrastingColor)
// Save color under pixel (used when copied).
lastHighlightedColor = colorAtPixel
// User has chosen a custom color space.
if let colorSpace = getChosenColorSpace(point) {
if colorSpace == zoomedImage.colorSpace {
return updatePreview(zoomedImage, pixelSize, middlePosition)
} else if let image = zoomedImage.copy(colorSpace: colorSpace) {
return updatePreview(image, pixelSize, middlePosition)
}
}
// No custom color space chosen, so use the screen's one.
if let colorSpace = getScreenColorSpace(point) {
if colorSpace == zoomedImage.colorSpace {
return updatePreview(zoomedImage, pixelSize, middlePosition)
} else if let image = zoomedImage.copy(colorSpace: colorSpace) {
return updatePreview(image, pixelSize, middlePosition)
}
}
// If that also didn't work, then just return the image in its default color space.
return updatePreview(zoomedImage, pixelSize, middlePosition)
}
}
private func updatePreview(_ image: CGImage, _ pixelSize: CGFloat, _ middlePosition: CGFloat) {
// Extract the middle pixel color from the prepared image.
let colorAtPixel = image.colorAt(x: Int(middlePosition), y: Int(middlePosition))
let contrastingColor = colorAtPixel.bestContrastingColor()
preview.layer?.contents = image
preview.updateCrosshair(pixelSize, middlePosition, contrastingColor.cgColor)
wrapper.update(contrastingColor.cgColor)
updateInfoPanel(colorAtPixel, contrastingColor)
// Save color under pixel (used when copied).
lastHighlightedColor = colorAtPixel
}
private func getScreenColorSpace(_ point: NSPoint) -> CGColorSpace? {
return getScreenFromPoint(point)?.colorSpace?.cgColorSpace
}
// Gets the colorspace in which to display the preview and retreive color values.
private func getChosenColorSpace(_ point: NSPoint) -> CGColorSpace? {
if let name = PPState.shared.colorSpace, let colorSpace = CGColorSpace(name: name as CFString) {
return colorSpace
}
// Center the mouse in the picker window.
overlayPanel.setFrameOrigin(NSPoint(x: normalisedPoint.x - (panelSize / 2), y: normalisedPoint.y - (panelSize / 2)))
return nil
}
}
extension CGImage {
// In order to get the color at a given pixel from a CGImage, we need to convert the CGImage's
// data to a bitmap and draw it. We do so via a CGContext, and then manually extract the data at
// the desired pixel.
func colorAt(x: Int, y: Int) -> NSColor {
assert(0 <= x && x < self.width)
assert(0 <= y && y < self.height)
let bitmapBytesPerRow = width * 4
let bitmapByteCount = bitmapBytesPerRow * Int(self.height)
// Allocate memory for image data. This is the destination in memory where any drawing to
// the bitmap context will be rendered.
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
let bitmapData = malloc(bitmapByteCount)
// Since we manually allocate memeory for the data, we must ensure that the same memory is
// freed after we've used it.
defer { free(bitmapData) }
// Create the bitmap context.
let context = CGContext(
data: bitmapData,
width: self.width,
height: self.height,
bitsPerComponent: 8,
bytesPerRow: bitmapBytesPerRow,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: bitmapInfo.rawValue
)
// Extract the pixel data from the right offset.
if context != nil {
// First, we draw the image data onto the context we created.
let rect = CGRect(x: 0, y: 0, width: self.width, height: self.height)
context!.draw(self, in: rect)
// Then we extract the data at the right spot.
let data = context!.data!
let offset = 4 * (y * width + x)
let a = CGFloat(data.load(fromByteOffset: offset, as: UInt8.self)) / 255.0
let r = CGFloat(data.load(fromByteOffset: offset + 1, as: UInt8.self)) / 255.0
let g = CGFloat(data.load(fromByteOffset: offset + 2, as: UInt8.self)) / 255.0
let b = CGFloat(data.load(fromByteOffset: offset + 3, as: UInt8.self)) / 255.0
return NSColor(red: r, green: g, blue: b, alpha: a)
}
// Creating the context failed, so return a default color instead.
// Hopefully, this should never happen.
Log.error?.message("Failed to create CGContext!")
return NSColor.black
}
}
@@ -3,7 +3,6 @@
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14109"/>
<capability name="box content view" minToolsVersion="7.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
@@ -21,10 +20,10 @@
</customObject>
<customObject id="ECQ-9M-Pkg" customClass="PPOverlayController" customModule="PixelPicker" customModuleProvider="target">
<connections>
<outlet property="infoBox" destination="rpe-Xh-gaO" id="BYW-qP-HLd"/>
<outlet property="infoDetailField" destination="Re2-GH-fyd" id="K03-75-cf9"/>
<outlet property="infoFormatField" destination="1fa-UE-yMM" id="Nan-fO-kbu"/>
<outlet property="infoPanel" destination="OMO-LB-w57" id="GGj-Y6-LfU"/>
<outlet property="infoWrapper" destination="HED-rR-FDP" id="21H-Tc-c4W"/>
<outlet property="overlayPanel" destination="gZA-A3-IZ5" id="DUd-MU-oD4"/>
<outlet property="preview" destination="oj3-ml-2qo" id="xLc-pu-U90"/>
<outlet property="window" destination="gZA-A3-IZ5" id="GLv-sO-WxM"/>
@@ -35,7 +34,7 @@
<windowStyleMask key="styleMask" utility="YES" nonactivatingPanel="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="196" y="132" width="101" height="101"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1178"/>
<rect key="screenRect" x="0.0" y="0.0" width="1680" height="1028"/>
<view key="contentView" id="acW-WA-gq2" customClass="PPOverlayWrapper" customModule="PixelPicker" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="101" height="101"/>
<autoresizingMask key="autoresizingMask"/>
@@ -56,50 +55,35 @@
<window title="Window" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" restorable="NO" oneShot="NO" showsToolbarButton="NO" visibleAtLaunch="NO" frameAutosaveName="" animationBehavior="default" id="OMO-LB-w57" customClass="PPOverlayPanel" customModule="PixelPicker" customModuleProvider="target">
<windowStyleMask key="styleMask" utility="YES" nonactivatingPanel="YES"/>
<rect key="contentRect" x="926" y="538" width="100" height="50"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1178"/>
<rect key="screenRect" x="0.0" y="0.0" width="1680" height="1028"/>
<view key="contentView" id="HED-rR-FDP">
<rect key="frame" x="0.0" y="0.0" width="100" height="50"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<box boxType="custom" borderType="none" cornerRadius="4" title="Box" translatesAutoresizingMaskIntoConstraints="NO" id="rpe-Xh-gaO">
<rect key="frame" x="0.0" y="0.0" width="100" height="50"/>
<view key="contentView" id="g1f-dN-SYl">
<rect key="frame" x="0.0" y="0.0" width="100" height="50"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="1fa-UE-yMM">
<rect key="frame" x="-2" y="28" width="104" height="17"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Label" id="RkG-Wy-Shq">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Re2-GH-fyd">
<rect key="frame" x="-2" y="5" width="104" height="14"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Label" id="IYd-1Y-7cd">
<font key="font" metaFont="smallSystem"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
</subviews>
<constraints>
<constraint firstItem="1fa-UE-yMM" firstAttribute="top" secondItem="g1f-dN-SYl" secondAttribute="top" constant="5" id="OMX-Uf-gxc"/>
<constraint firstAttribute="trailing" secondItem="1fa-UE-yMM" secondAttribute="trailing" id="YWA-wF-wWD"/>
<constraint firstItem="Re2-GH-fyd" firstAttribute="leading" secondItem="g1f-dN-SYl" secondAttribute="leading" id="def-Ev-ONx"/>
<constraint firstItem="1fa-UE-yMM" firstAttribute="leading" secondItem="g1f-dN-SYl" secondAttribute="leading" id="j0J-F5-ipt"/>
<constraint firstAttribute="bottom" secondItem="Re2-GH-fyd" secondAttribute="bottom" constant="5" id="ktF-UW-gVI"/>
<constraint firstAttribute="trailing" secondItem="Re2-GH-fyd" secondAttribute="trailing" id="t9s-4R-bFb"/>
</constraints>
</view>
</box>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="1fa-UE-yMM">
<rect key="frame" x="-2" y="25" width="104" height="17"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Label" id="RkG-Wy-Shq">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Re2-GH-fyd">
<rect key="frame" x="-2" y="8" width="104" height="14"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Label" id="IYd-1Y-7cd">
<font key="font" metaFont="smallSystem"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
</subviews>
<constraints>
<constraint firstItem="rpe-Xh-gaO" firstAttribute="leading" secondItem="HED-rR-FDP" secondAttribute="leading" id="Buc-en-Way"/>
<constraint firstItem="rpe-Xh-gaO" firstAttribute="top" secondItem="HED-rR-FDP" secondAttribute="top" id="NrK-e2-suw"/>
<constraint firstAttribute="bottom" secondItem="rpe-Xh-gaO" secondAttribute="bottom" id="WSu-Ro-a4K"/>
<constraint firstAttribute="trailing" secondItem="rpe-Xh-gaO" secondAttribute="trailing" id="myM-UI-QfA"/>
<constraint firstItem="1fa-UE-yMM" firstAttribute="leading" secondItem="HED-rR-FDP" secondAttribute="leading" id="23z-pW-nAx"/>
<constraint firstItem="1fa-UE-yMM" firstAttribute="top" secondItem="HED-rR-FDP" secondAttribute="top" constant="8" id="G1j-j5-iWY"/>
<constraint firstItem="Re2-GH-fyd" firstAttribute="leading" secondItem="HED-rR-FDP" secondAttribute="leading" id="aZf-QY-Lpd"/>
<constraint firstAttribute="bottom" secondItem="Re2-GH-fyd" secondAttribute="bottom" constant="8" id="amm-jV-oWa"/>
<constraint firstAttribute="trailing" secondItem="1fa-UE-yMM" secondAttribute="trailing" id="flM-Te-2qj"/>
<constraint firstAttribute="trailing" secondItem="Re2-GH-fyd" secondAttribute="trailing" id="jWO-5f-uxW"/>
</constraints>
</view>
<point key="canvasLocation" x="236" y="230"/>
@@ -31,10 +31,9 @@ class PPOverlayPreview: NSView, CALayerDelegate {
func updateCrosshair(_ pixelSize: CGFloat, _ middle: CGFloat, _ color: CGColor) {
let pos: CGFloat = (pixelSize * middle) - (pixelSize / 2)
let pixelRect = NSMakeRect(pos, pos, pixelSize, pixelSize)
let outerRect = pixelRect.insetBy(dx: -1, dy: -1)
crosshair.path = CGPath(rect: outerRect, transform: nil)
crosshair.path = CGPath(rect: pixelRect, transform: nil)
crosshair.strokeColor = color
setNeedsDisplay(outerRect)
setNeedsDisplay(pixelRect)
}
}
+57 -44
View File
@@ -5,42 +5,30 @@
import SwiftyJSON
// This allows us to iterate over the raw values of an enum.
// TODO: use `CaseIterable` when Swift 4.2 comes out
func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) }
if next.hashValue != i { return nil }
i += 1
return next
}
}
// Each time the user picks a pixel we save it as the format and the color.
struct PPPickedColor {
let color: NSColor
let format: PPColor
init(color: NSColor, format: PPColor) {
self.color = color
self.format = format
}
init?(fromJSON json: JSON) {
guard
let formatString = json["format"].string,
let format = PPColor(rawValue: formatString),
let color = NSColor.deserialize(fromJson: json["color"])
else { return nil }
self.init(color: color, format: format)
}
var asString: String {
return format.asString(withColor: color)
}
var asJSON: JSON {
return [
"color": NSColor.serialize(self.color),
@@ -91,10 +79,10 @@ enum PPColor: String {
let f = self.insertFloatPrecisionFormatter
let c = colorInCorrectColorSpace(passedColor)
switch self {
case .genericHex: return self.formatAsHex(c, "%2X")
case .genericHex: return self.formatAsHex(c, "%06x")
case .generic8Bit: return self.formatAs8Bit(c, "%u, %u, %u")
case .genericDecimal: return self.formatAsDecimal(c, f("%f, %f, %f"), .rgb)
case .cssHex: return self.formatAsHex(c, "#%2X")
case .cssHex: return self.formatAsHex(c, "#%06x")
case .cssRgb: return self.formatAs8Bit(c, "rgb(%u, %u, %u)")
case .cssRgba: return self.formatAs8Bit(c, "rgba(%u, %u, %u, 1)")
case .cssHsl: return self.formatAsHSL(c, "hsl(%u, %u%%, %u%%)")
@@ -119,8 +107,8 @@ enum PPColor: String {
case .javaRgba: return self.formatAs8Bit(c, "new Color(%u, %u, %u, 255)")
case .androidRgb: return self.formatAs8Bit(c, "Color.rgb(%u, %u, %u)")
case .androidArgb: return self.formatAs8Bit(c, "Color.argb(255, %u, %u, %u)")
case .androidXmlRgb: return self.formatAsHex(c, "<color name=\"color_name\">#%2X</color>")
case .androidXmlArgb: return self.formatAsHex(c, "<color name=\"color_name\">#ff%2X</color>")
case .androidXmlRgb: return self.formatAsHex(c, "<color name=\"color_name\">#%06x</color>")
case .androidXmlArgb: return self.formatAsHex(c, "<color name=\"color_name\">#ff%06x</color>")
case .cgColorRgb: return self.formatAsDecimal(c, f("CGColorCreateGenericRGB(%f, %f, %f, 1.000)"), .rgb)
case .openGlRgb: return self.formatAsDecimal(c, f("glColor3f(%f, %f, %f)"), .rgb)
case .openGlRgba: return self.formatAsDecimal(c, f("glColor4f(%f, %f, %f, 1.000)"), .rgb)
@@ -136,7 +124,7 @@ enum PPColor: String {
case .androidXmlRgb: fallthrough
case .androidXmlArgb: fallthrough
case .cgColorRgb: fallthrough
case .genericHex: return self.formatAsHex(color, "%2X")
case .genericHex: return self.formatAsHex(color, "%06x")
// CSS HSL is a unique format.
case .cssHsl: fallthrough
case .cssHsla: return self.formatAsHSL(color, "%u, %u%%, %u%%")
@@ -170,17 +158,17 @@ enum PPColor: String {
case .objCUIColorHsb: return self.formatAsDecimal(color, self.insertFloatPrecisionFormatter("%f, %f, %f"), .rgb)
}
}
// Returns the PPColor that sits after this one.
func next() -> PPColor {
return next(withArray: iterateEnum(PPColor.self).map({ $0 }))
}
// Same as next() but backwards.
func previous() -> PPColor {
return next(withArray: iterateEnum(PPColor.self).reversed())
}
// Finds the next element after this element in the given array.
// This method should only be passed the result of iterateEnum(PPColor.self).
private func next(withArray array: [PPColor]) -> PPColor {
@@ -192,26 +180,26 @@ enum PPColor: String {
return array.first!
}
// A tiny enum that describes which components should be used when formatting.
private enum Components {
case rgb
case hsb
}
// Replaces "%f" with "%.3f" (if "3" is the current precision level).
private func insertFloatPrecisionFormatter(_ input: String) -> String {
return input.replacingOccurrences(of: "%f", with: String(format: "%%.%uf", PPState.shared.floatPrecision))
}
// Formats the colors as a hex value, eg: "D3504E".
private func formatAsHex(_ color: NSColor, _ template: String) -> String {
let a = Int(color.redComponent * 255) << 16
let b = Int(color.greenComponent * 255) << 8
let c = Int(color.blueComponent * 255) << 0
return String(format: template, a | b | c)
let r = min(Int(color.redComponent * 0x100), 0x0ff) << 16
let g = min(Int(color.greenComponent * 0x100), 0x0ff) << 8
let b = min(Int(color.blueComponent * 0x100), 0x0ff) << 0
return String(format: template, (r | g | b))
}
// Formats the color as decimal values, eg: "0.145, 0.361, 0.722".
private func formatAsDecimal(_ color: NSColor, _ template: String, _ cmp: Components) -> String {
let a = cmp == .rgb ? color.redComponent : color.hueComponent
@@ -219,23 +207,23 @@ enum PPColor: String {
let c = cmp == .rgb ? color.blueComponent : color.brightnessComponent
return String(format: template, a, b, c)
}
// Formats the color as 8-bit values, eg: "158, 198, 117".
private func formatAs8Bit(_ color: NSColor, _ template: String) -> String {
let a = Int(color.redComponent * 255)
let b = Int(color.greenComponent * 255)
let c = Int(color.blueComponent * 255)
return String(format: template, a, b, c)
let r = min(Int(color.redComponent * 0x100), 0x0ff)
let g = min(Int(color.greenComponent * 0x100), 0x0ff)
let b = min(Int(color.blueComponent * 0x100), 0x0ff)
return String(format: template, r, g, b)
}
// Special formatter since CSS uses a unique style here, eg: "35, 79%, 47%".
private func formatAsHSL(_ color: NSColor, _ template: String) -> String {
let a = Int(color.hueComponent * 360)
let b = Int(color.saturationComponent * 100)
let c = Int(color.brightnessComponent * 100)
return String(format: template, a, b, c)
let h = min(Int(color.hueComponent * 360), 359)
let s = Int(color.saturationComponent * 100)
let b = Int(color.brightnessComponent * 100)
return String(format: template, h, s, b)
}
// Returns a new color in the correct colorspace for the format.
private func colorInCorrectColorSpace(_ color: NSColor) -> NSColor {
switch self {
@@ -253,4 +241,29 @@ enum PPColor: String {
return color
}
}
// Available CGColorSpaces that can be chosen.
// NOTE: the commented out color spaces don't work at all on my screens, they may work for other
// screens, but here they're left out since they're probably not common/necessary. If you're
// reading this and you want to use them, make an issue on GitHub and then we can test them.
static let colorSpaceNames = [
// ("Generic CMYK", CGColorSpace.genericCMYK as String),
("Generic XYZ", CGColorSpace.genericXYZ as String),
("Generic RGB Linear", CGColorSpace.genericRGBLinear as String),
// ("Generic Gray Gamma 2.2", CGColorSpace.genericGrayGamma2_2 as String),
("ACESCG Linear", CGColorSpace.acescgLinear as String),
("Adobe RGB 1998", CGColorSpace.adobeRGB1998 as String),
("DCIP3", CGColorSpace.dcip3 as String),
("Display P3", CGColorSpace.displayP3 as String),
// ("Linear Gray", CGColorSpace.linearGray as String),
("Linear sRGB", CGColorSpace.linearSRGB as String),
// ("Extended Linear Gray", CGColorSpace.extendedLinearGray as String),
("Extended Linear sRGB", CGColorSpace.extendedLinearSRGB as String),
// ("Extended Gray", CGColorSpace.extendedGray as String),
("Extended sRGB", CGColorSpace.extendedSRGB as String),
("ITUR 2020", CGColorSpace.itur_2020 as String),
("ITUR 709", CGColorSpace.itur_709 as String),
("ROMM RGB", CGColorSpace.rommrgb as String),
("sRGB", CGColorSpace.sRGB as String)
]
}
+12 -1
View File
@@ -24,7 +24,6 @@ import CleanroomLogger
let defaults: UserDefaults = UserDefaults.standard
// Whether the picker should be square or not.
// TODO: implement shortcut
var paschaModeEnabled: Bool = false
// The shortcut that activates the pixel picker.
@@ -38,6 +37,11 @@ import CleanroomLogger
// The currently chosen format.
var chosenFormat: PPColor = .genericHex
// The name of the chosen color space. If this is nil, then the picker will attempt to get the
// color space of the screen the picker is currently on (and if that fails, fall back to the
// default color space of the screenshot).
var colorSpace: String? = nil
// How precise floats should be when copied.
var floatPrecision: UInt = 3
@@ -101,6 +105,12 @@ import CleanroomLogger
activatingShortcut = shortcut
}
}
case "colorSpace":
// Check for the presence of the color space in our list. If it's found, then we
// can use it (safeguard against bogus input).
if let _ = PPColor.colorSpaceNames.index(where: { $0.1 == value.string }) {
colorSpace = value.string
}
case "chosenFormat":
chosenFormat = PPColor(rawValue: value.stringValue) ?? .genericHex
case "magnificationLevel":
@@ -143,6 +153,7 @@ import CleanroomLogger
"concentrationModeModifier": concentrationModeModifier.rawValue,
"activatingShortcut": shortcutData,
"magnificationLevel": magnificationLevel,
"colorSpace": colorSpace ?? "",
"chosenFormat": chosenFormat.rawValue,
"floatPrecision": floatPrecision,
"recentPicks": recentPicks.map({ $0.asJSON })
+12
View File
@@ -8,6 +8,18 @@ import CleanroomLogger
let APP_NAME = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String
let APPLE_INTERFACE_STYLE = "AppleInterfaceStyle"
// This allows us to iterate over the raw values of an enum.
// TODO: use `CaseIterable` when Swift 4.2 comes out
func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) }
if next.hashValue != i { return nil }
i += 1
return next
}
}
// Copies the given string to the clipboard.
func copyToPasteboard(stringValue value: String) {
NSPasteboard.general.declareTypes([.string], owner: nil)