Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(fix: #9) Grayscale Selection When Not Focused #16

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
FastestMolasses marked this conversation as resolved.
Show resolved Hide resolved
return super.resignFirstResponder()
}

Expand Down
Loading