-
-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathInputSourceVM.swift
More file actions
92 lines (80 loc) · 2.84 KB
/
Copy pathInputSourceVM.swift
File metadata and controls
92 lines (80 loc) · 2.84 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import AppKit
import AXSwift
import Carbon
import Combine
import Foundation
import CombineExt
@MainActor
class InputSourceVM: ObservableObject {
private struct SelectionRequest {
let inputSource: InputSource
let app: NSRunningApplication?
let allowShortcutFallback: Bool
}
let preferencesVM: PreferencesVM
private var cancelBag = CancelBag()
private let selectInputSourceSubject = PassthroughSubject<SelectionRequest, Never>()
private let inputSourceChangesSubject = PassthroughSubject<Void, Never>()
let inputSourceChangesPublisher: AnyPublisher<InputSource, Never>
init(preferencesVM: PreferencesVM) {
self.preferencesVM = preferencesVM
inputSourceChangesPublisher = inputSourceChangesSubject
.map { _ in InputSource.getCurrentInputSource() }
.removeDuplicates()
.eraseToAnyPublisher()
watchSystemNotification()
selectInputSourceSubject
.tap { [weak self] in
if let self {
$0.inputSource.select(
cJKVFixStrategy: self.preferencesVM.activeCJKVFixStrategy(for: $0.app),
allowShortcutFallback: $0.allowShortcutFallback
)
}
}
.flatMapLatest({ _ in
Publishers.MergeMany([
Just(())
.eraseToAnyPublisher(),
Timer
.delay(seconds: 0.05)
.mapToVoid()
.eraseToAnyPublisher(),
Timer
.delay(seconds: 0.15)
.mapToVoid()
.eraseToAnyPublisher(),
Timer
.delay(seconds: 0.3)
.mapToVoid()
.eraseToAnyPublisher()
])
.eraseToAnyPublisher()
})
.sink { [weak self] _ in
self?.inputSourceChangesSubject.send(())
}
.store(in: cancelBag)
}
func select(
inputSource: InputSource,
app: NSRunningApplication? = nil,
allowShortcutFallback: Bool = true
) {
selectInputSourceSubject.send(
SelectionRequest(
inputSource: inputSource,
app: app,
allowShortcutFallback: allowShortcutFallback
)
)
}
private func watchSystemNotification() {
DistributedNotificationCenter.default()
.publisher(for: Notification.Name(rawValue: kTISNotifySelectedKeyboardInputSourceChanged as String))
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in self?.inputSourceChangesSubject.send(())
}
.store(in: cancelBag)
}
}