Skip to content

Commit

Permalink
(fix: #9) Grayscale Selection When Not Focused (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
thecoolwinter authored Feb 5, 2024
1 parent fad3087 commit cf4ee3b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
17 changes: 17 additions & 0 deletions Sources/CodeEditTextView/Extensions/NSColor+Greyscale.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//
// NSColor+Greyscale.swift
// CodeEditTextView
//
// Created by Khan Winter on 2/2/24.
//

import AppKit

extension NSColor {
var grayscale: NSColor {
guard let color = self.usingColorSpace(.deviceRGB) else { return self }
// linear relative weights for grayscale: https://en.wikipedia.org/wiki/Grayscale
let gray = 0.299 * color.redComponent + 0.587 * color.greenComponent + 0.114 * color.blueComponent
return NSColor(white: gray, alpha: color.alphaComponent)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,12 @@ public class TextSelectionManager: NSObject {
/// - context: The context to draw in.
private func drawSelectedRange(in rect: NSRect, for textSelection: TextSelection, context: CGContext) {
context.saveGState()
context.setFillColor(selectionBackgroundColor.cgColor)

let fillColor = (textView?.isFirstResponder ?? false)
? selectionBackgroundColor.cgColor
: selectionBackgroundColor.grayscale.cgColor

context.setFillColor(fillColor)

let fillRects = getFillRects(in: rect, for: textSelection)

Expand Down
2 changes: 2 additions & 0 deletions Sources/CodeEditTextView/TextView/TextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -314,12 +314,14 @@ public class TextView: NSView, NSTextContent {
open override func becomeFirstResponder() -> Bool {
isFirstResponder = true
selectionManager.cursorTimer.resetTimer()
needsDisplay = true
return super.becomeFirstResponder()
}

open override func resignFirstResponder() -> Bool {
isFirstResponder = false
selectionManager.removeCursors()
needsDisplay = true
return super.resignFirstResponder()
}

Expand Down

0 comments on commit cf4ee3b

Please sign in to comment.