forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModifierFlagsMonitor.swift
More file actions
55 lines (45 loc) · 1.44 KB
/
ModifierFlagsMonitor.swift
File metadata and controls
55 lines (45 loc) · 1.44 KB
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
import Cocoa
import Foundation
import SwiftUI
public extension View {
func modifierFlagsMonitor() -> some View {
ModifierFlagsMonitorWrapper { self }
}
}
public extension EnvironmentValues {
var modifierFlags: NSEvent.ModifierFlags {
get { self[ModifierFlagsEnvironmentKey.self] }
set { self[ModifierFlagsEnvironmentKey.self] = newValue }
}
}
final class ModifierFlagsMonitor {
private var monitor: Any?
deinit { stop() }
func start(binding: Binding<NSEvent.ModifierFlags>) {
guard monitor == nil else { return }
monitor = NSEvent.addLocalMonitorForEvents(matching: [.flagsChanged]) { event in
binding.wrappedValue = event.modifierFlags
return event
}
}
func stop() {
if let monitor {
NSEvent.removeMonitor(monitor)
self.monitor = nil
}
}
}
struct ModifierFlagsMonitorWrapper<Content: View>: View {
@ViewBuilder let content: () -> Content
@State private var modifierFlags: NSEvent.ModifierFlags = []
@State private var eventMonitor = ModifierFlagsMonitor()
var body: some View {
content()
.environment(\.modifierFlags, modifierFlags)
.onAppear { eventMonitor.start(binding: $modifierFlags) }
.onDisappear { eventMonitor.stop() }
}
}
struct ModifierFlagsEnvironmentKey: EnvironmentKey {
static let defaultValue: NSEvent.ModifierFlags = []
}