-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
UserModesBezelController.swift
69 lines (58 loc) · 2.17 KB
/
UserModesBezelController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import AppKit
import Combine
import SwiftUI
@MainActor
final class UserModesBezelController {
@MainActor
static let shared = UserModesBezelController()
private var windowController: NSWindowController
private var window: NotificationPanel<CurrentUserModesView>
private var debouncer: DebounceManager<[UserMode]>?
private var subscription: AnyCancellable?
private init() {
let content = CurrentUserModesView(publisher: UserSpace.shared.userModesPublisher)
let window = NotificationPanel(
animationBehavior: .utilityWindow,
styleMask: [
.borderless,
.nonactivatingPanel
],
content: content
)
self.window = window
self.windowController = NSWindowController(window: window)
debouncer = DebounceManager(for: .milliseconds(250)) { [weak self] userModes in
self?.publish(userModes)
}
windowController.showWindow(nil)
subscription = NotificationCenter.default
.publisher(for: NSApplication.didChangeScreenParametersNotification)
.debounce(for: .milliseconds(250), scheduler: DispatchQueue.main)
.sink { [weak self] _ in
guard let self, let contentView = window.contentView else { return }
self.resizeAndAlignWindow(to: contentView.fittingSize, animate: false)
}
}
func show(_ userModes: [UserMode]) {
debouncer?.send(userModes)
}
func hide() {
debouncer?.send([])
}
// MARK: Private methods
private func publish(_ userModes: [UserMode]) {
guard let contentView = window.contentView else { return }
UserSpace.shared.userModesPublisher.publish(userModes)
DispatchQueue.main.async {
self.resizeAndAlignWindow(to: contentView.fittingSize, animate: true)
}
}
private func resizeAndAlignWindow(to contentSize: CGSize, animate: Bool) {
guard let screen = NSScreen.main else { return }
let screenFrame = screen.frame
let newWindowOriginX = screenFrame.maxX - contentSize.width
let newWindowOriginY = screenFrame.minY
let newWindowFrame = NSRect(x: newWindowOriginX, y: newWindowOriginY, width: contentSize.width, height: contentSize.height)
window.setFrame(newWindowFrame, display: true, animate: animate)
}
}