Skip to content

Commit

Permalink
Add TitlebarClickAwareWindow class (#1)
Browse files Browse the repository at this point in the history
NSWindow subclass honoring the titlebar double click action
  • Loading branch information
McNight authored Jun 5, 2024
1 parent d1ae68c commit c48d5d5
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import AppKit

private extension NSWindow {
/// Key of double click action. It can be customized in macOS System Settings app within the Dock subsettings.
static let actionOnDoubleClickKey: String = "AppleActionOnDoubleClick"
/// Value of zoom action for the ``actionOnDoubleClickKey`` key typically set by the macOS System Settings app.
static let zoomActionOnDoubleClickValue: String = "Maximize"
/// Value of minimize action for the ``actionOnDoubleClickKey`` key typically set by the macOS System Settings app.
static let miniaturizeActionOnDoubleClickValue: String = "Minimize"
}

/// Simple NSWindow subclass honoring the titlebar double click action from the macOS System Settings app.
open class TitlebarClickAwareWindow: NSWindow {
override open func mouseDown(with event: NSEvent) {
if event.clickCount > 1, isEventLocationEligible(event.locationInWindow) {
zoomOrMiniaturize(self)
}
super.mouseDown(with: event)
}
}

private extension TitlebarClickAwareWindow {
func isEventLocationEligible(_ location: CGPoint) -> Bool {
guard let windowFrame = contentView?.frame else {
return false
}
var titleBarRect = contentLayoutRect
titleBarRect.origin.y += contentLayoutRect.height
titleBarRect.size.height = windowFrame.height - contentLayoutRect.height
return titleBarRect.contains(location)
}

func zoomOrMiniaturize(_ sender: Any?) {
let actionOnDoubleClickValue = UserDefaults.standard.string(forKey: Self.actionOnDoubleClickKey)

switch actionOnDoubleClickValue {
case Self.zoomActionOnDoubleClickValue:
zoom(sender)
case Self.miniaturizeActionOnDoubleClickValue:
miniaturize(sender)
default:
zoom(sender)
}
}
}

0 comments on commit c48d5d5

Please sign in to comment.