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
62 lines (52 loc) · 1.74 KB
/
Copy pathModifierFlagsMonitor.swift
File metadata and controls
62 lines (52 loc) · 1.74 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
55
56
57
58
59
60
61
import Cocoa
import Foundation
import SwiftUI
public extension View {
func modifierFlagsMonitor(local: Bool = true) -> some View {
ModifierFlagsMonitorWrapper(local: local) { 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>, local: Bool) {
guard monitor == nil else { return }
if local {
monitor = NSEvent.addLocalMonitorForEvents(matching: [.flagsChanged]) { event in
binding.wrappedValue = event.modifierFlags
return event
}
} else {
monitor = NSEvent.addGlobalMonitorForEvents(matching: [.flagsChanged]) { event in
binding.wrappedValue = event.modifierFlags
}
}
}
func stop() {
if let monitor {
NSEvent.removeMonitor(monitor)
self.monitor = nil
}
}
}
struct ModifierFlagsMonitorWrapper<Content: View>: View {
var local = true
@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, local: local) }
.onDisappear { eventMonitor.stop() }
}
}
struct ModifierFlagsEnvironmentKey: EnvironmentKey {
static let defaultValue: NSEvent.ModifierFlags = []
}