-
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add TitlebarClickAwareWindow class (#1)
NSWindow subclass honoring the titlebar double click action
- Loading branch information
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
File renamed without changes.
45 changes: 45 additions & 0 deletions
45
Sources/WindowTreatment/Window subclasses/TitlebarClickAwareWindow.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |