-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapperViewModel.swift
More file actions
792 lines (695 loc) · 30.5 KB
/
Copy pathMapperViewModel.swift
File metadata and controls
792 lines (695 loc) · 30.5 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
import AppKit
import KeyPathCore
import SwiftUI
// MapperActionTypes (AppLaunchInfo, AppConditionInfo, SystemActionInfo)
// are defined in MapperActionTypes.swift
// MARK: - Mapper View Model
@Observable
@MainActor
class MapperViewModel {
var inputLabel: String = "A"
var outputLabel: String = "A"
var shiftedOutputLabel: String?
/// Whether the current shifted output is the system default (not a custom override)
var isShiftedOutputDefault = false
var isRecordingInput = false
var isRecordingOutput = false
var isRecordingShiftedOutput = false
var isSaving = false
var statusMessage: String?
var statusIsError = false
private var statusDismissTask: Task<Void, Never>?
var currentLayer: String = "base"
var availableLayers: [String] = ["base", "nav"]
/// Selected app for launch action (nil = normal key output)
var selectedApp: AppLaunchInfo?
/// Selected system action (nil = normal key output)
var selectedSystemAction: SystemActionInfo?
/// Selected URL for web URL mapping (nil = normal key output)
var selectedURL: String? {
didSet {
if selectedURL != oldValue {
selectedURLFavicon = nil
}
}
}
/// Favicon for the selected URL
var selectedURLFavicon: NSImage?
/// Whether the URL input dialog is visible
var showingURLDialog = false
/// Text input for URL dialog
var urlInputText = ""
/// Selected folder path for folder-open mapping (nil = normal key output)
var selectedFolder: (path: String, name: String?)?
/// Selected script path for script-run mapping (nil = normal key output)
var selectedScript: (path: String, name: String?)?
// MARK: - Output-Type Picker (Overlay) Navigation State
/// Which page the overlay output-type picker is showing.
///
/// The picker is an iPhone-style drill-down — the root list and each
/// sub-list (System Action / Launch App / Go to Layer) are separate pages
/// that slide over one another inside a *stable* popover frame. This
/// deliberately replaced inline expansion: growing the popover's height
/// forced the hoisted window-anchored layer to re-measure and reposition on
/// every toggle, which fought SwiftUI's preference/position machinery and
/// left the expandable rows unresponsive. Swapping pages in a fixed frame
/// avoids all of that.
///
/// It lives on the view model (not `@State` on the view) because the picker
/// is rendered in that detached hoisted layer; `@State` mutated from there
/// does not propagate back, whereas this shared `@Observable` reference does.
enum OutputPickerPage: Equatable {
case root
case systemActions
case launchApps
case layers
}
var outputPickerPage: OutputPickerPage = .root
/// Selected layer name for "Go to Layer" output (nil = not a layer output).
var selectedLayerOutput: String?
/// Filter text for the Launch App sub-page's known-apps list. Lives here
/// (not `@State` on the view) because the picker popover is hoisted; a
/// `TextField` bound to view `@State` from that detached layer wouldn't
/// propagate. Cleared each time the picker opens.
var launchAppSearchText: String = ""
/// Key code of the captured input (for overlay-style rendering)
/// Default to 0 (A key) so the default state shows the A key selected
var inputKeyCode: UInt16? = 0
/// Apps that have a mapping for the currently selected input key
var appsWithCurrentKeyMapping: [AppKeymap] = []
// MARK: - Device Condition
/// Selected device condition (nil = all keyboards)
var selectedDeviceCondition: DeviceConditionInfo?
// MARK: - App Condition (Delegated to AppConditionManager)
/// Manager for app condition (precondition) selection
var appConditionManager = AppConditionManager()
/// Legacy accessor for selectedAppCondition
var selectedAppCondition: AppConditionInfo? {
get { appConditionManager.selectedAppCondition }
set {
appConditionManager.selectedAppCondition = newValue
if newValue != nil {
clearShiftedOutput()
}
}
}
// MARK: - Advanced Behavior (Delegated to AdvancedBehaviorManager)
/// Manager for advanced key behaviors (hold, tap-dance, timing)
/// Views should access advanced behavior properties through this manager.
var advancedBehavior = AdvancedBehaviorManager()
/// Legacy accessors for backward compatibility during migration
/// These delegate to advancedBehavior and will be removed once views are updated
var showAdvanced: Bool {
get { advancedBehavior.showAdvanced }
set { advancedBehavior.showAdvanced = newValue }
}
var holdAction: String {
get { advancedBehavior.holdAction }
set { advancedBehavior.holdAction = newValue }
}
var doubleTapAction: String {
get { advancedBehavior.doubleTapAction }
set { advancedBehavior.doubleTapAction = newValue }
}
var macroBehavior: MacroBehavior? {
get { advancedBehavior.macroBehavior }
set { advancedBehavior.macroBehavior = newValue }
}
var tappingTerm: Int {
get { advancedBehavior.tappingTerm }
set { advancedBehavior.tappingTerm = newValue }
}
var isRecordingHold: Bool {
get { advancedBehavior.isRecordingHold }
set { advancedBehavior.isRecordingHold = newValue }
}
var isRecordingDoubleTap: Bool {
get { advancedBehavior.isRecordingDoubleTap }
set { advancedBehavior.isRecordingDoubleTap = newValue }
}
var isRecordingComboOutput: Bool {
get { advancedBehavior.isRecordingComboOutput }
set { advancedBehavior.isRecordingComboOutput = newValue }
}
var isRecordingMacro: Bool {
get { advancedBehavior.isRecordingMacro }
set { advancedBehavior.isRecordingMacro = newValue }
}
var comboOutput: String {
get { advancedBehavior.comboOutput }
set { advancedBehavior.comboOutput = newValue }
}
var comboKeys: [String] {
get { advancedBehavior.comboKeys }
set { advancedBehavior.comboKeys = newValue }
}
/// Hold behavior type - use AdvancedBehaviorManager's type
typealias HoldBehaviorType = AdvancedBehaviorManager.HoldBehaviorType
var holdBehavior: HoldBehaviorType {
get { advancedBehavior.holdBehavior }
set { advancedBehavior.holdBehavior = newValue }
}
var customTapKeysText: String {
get { advancedBehavior.customTapKeysText }
set { advancedBehavior.customTapKeysText = newValue }
}
var tapDanceSteps: [(label: String, action: String, isRecording: Bool)] {
get { advancedBehavior.tapDanceSteps }
set { advancedBehavior.tapDanceSteps = newValue }
}
static let tapDanceLabels = AdvancedBehaviorManager.tapDanceLabels
var showTimingAdvanced: Bool {
get { advancedBehavior.showTimingAdvanced }
set { advancedBehavior.showTimingAdvanced = newValue }
}
var tapTimeout: Int {
get { advancedBehavior.tapTimeout }
set { advancedBehavior.tapTimeout = newValue }
}
var holdTimeout: Int {
get { advancedBehavior.holdTimeout }
set { advancedBehavior.holdTimeout = newValue }
}
var showConflictDialog: Bool {
get { advancedBehavior.showConflictDialog }
set { advancedBehavior.showConflictDialog = newValue }
}
typealias ConflictType = AdvancedBehaviorManager.ConflictType
var pendingConflictType: ConflictType? {
get { advancedBehavior.pendingConflictType }
set { advancedBehavior.pendingConflictType = newValue }
}
var pendingConflictField: String {
get { advancedBehavior.pendingConflictField }
set { advancedBehavior.pendingConflictField = newValue }
}
/// Default KeySequence for A key - used as initial value so save works without capturing input first
static let defaultAKeySequence = KeySequence(
keys: [KeyPress(baseKey: "a", modifiers: [], keyCode: 0)],
captureMode: .single
)
@ObservationIgnored var inputSequence: KeySequence? = MapperViewModel.defaultAKeySequence
@ObservationIgnored var outputSequence: KeySequence? = MapperViewModel.defaultAKeySequence
@ObservationIgnored var shiftedOutputSequence: KeySequence?
@ObservationIgnored var keyboardCapture: KeyboardCapture?
@ObservationIgnored var simpleKeyCaptureMonitor: Any?
@ObservationIgnored var simpleKeyCaptureToken: UUID?
@ObservationIgnored var multiTapFinalizeTimer: Timer?
@ObservationIgnored var multiTapPendingSequence: KeySequence?
@ObservationIgnored var multiTapUpdateHandler: ((String) -> Void)?
@ObservationIgnored var multiTapFinalizeHandler: ((String) -> Void)?
@ObservationIgnored var multiTapStopHandler: (() -> Void)?
@ObservationIgnored var kanataManager: RuntimeCoordinator?
var rulesManager: RuleCollectionsManager? {
kanataManager?.rulesManager
}
@ObservationIgnored var finalizeTimer: Timer?
/// ID of the last saved custom rule (for clearing/deleting)
@ObservationIgnored var lastSavedRuleID: UUID?
/// Original key context from overlay click (for reset after clear)
@ObservationIgnored var originalInputKey: String?
@ObservationIgnored var originalOutputKey: String?
@ObservationIgnored var originalShiftedOutputKey: String?
@ObservationIgnored var originalAppIdentifier: String?
@ObservationIgnored var originalSystemActionIdentifier: String?
@ObservationIgnored var originalURL: String?
/// Original layer from overlay click
@ObservationIgnored var originalLayer: String?
/// State saved before starting output recording (for restore on cancel)
@ObservationIgnored var savedOutputLabel: String?
@ObservationIgnored var savedOutputSequence: KeySequence?
@ObservationIgnored var savedShiftedOutputLabel: String?
@ObservationIgnored var savedShiftedOutputSequence: KeySequence?
@ObservationIgnored var savedSelectedApp: AppLaunchInfo?
@ObservationIgnored var savedSelectedSystemAction: SystemActionInfo?
@ObservationIgnored var savedMacroBehavior: MacroBehavior?
/// Delay before finalizing a sequence capture (allows for multi-key sequences)
@ObservationIgnored let sequenceFinalizeDelay: TimeInterval = 0.8
var canSave: Bool {
inputSequence != nil && (outputSequence != nil || selectedApp != nil || selectedSystemAction != nil || selectedURL != nil)
}
var hasShiftedOutputConfigured: Bool {
shiftedOutputSequence != nil
}
/// Whether the current input key has a standard shift symbol (e.g., 1→!, ;→:)
var defaultShiftSymbol: String? {
LabelMetadata.forLabel(inputLabel).shiftSymbol
}
var shiftedOutputBlockingReason: String? {
if selectedAppCondition != nil {
return "Shift output is only available for rules that apply everywhere."
}
if selectedApp != nil || selectedSystemAction != nil || selectedURL != nil {
return "Shift output works only with keystroke output."
}
if advancedBehavior.hasAdvancedConfig {
return "Shift output isn't available with hold, combo, or multi-tap behaviors."
}
return nil
}
var canUseShiftedOutput: Bool {
shiftedOutputBlockingReason == nil
}
var isIdentityKeystrokeMapping: Bool {
guard selectedApp == nil,
selectedSystemAction == nil,
selectedURL == nil,
!advancedBehavior.hasAdvancedConfig,
let inputKanata = currentInputKanataString(),
let outputSequence
else {
return false
}
let outputKanata = convertSequenceToKanataFormat(outputSequence)
return inputKanata.caseInsensitiveCompare(outputKanata) == .orderedSame
}
func configure(kanataManager: RuntimeCoordinator) {
self.kanataManager = kanataManager
Task {
await refreshAvailableLayers()
}
}
/// Set the current layer
func setLayer(_ layer: String) {
currentLayer = layer
AppLogger.shared.log("🗂️ [MapperViewModel] Layer set to: \(layer)")
// Post notification for other views to update
NotificationCenter.default.post(
name: .kanataLayerChanged,
object: nil,
userInfo: ["layer": layer]
)
}
/// Update input from a key click in the overlay (used by mapper drawer)
func setInputFromKeyClick(
keyCode: UInt16,
inputLabel: String,
outputLabel: String,
appIdentifier: String? = nil,
systemActionIdentifier: String? = nil,
urlIdentifier: String? = nil,
shiftedOutputKey: String? = nil
) {
// Stop any active recording
stopRecording()
// Update input
inputKeyCode = keyCode
self.inputLabel = formatKeyForDisplay(inputLabel)
inputSequence = KeySequence(
keys: [KeyPress(baseKey: inputLabel, modifiers: [], keyCode: Int64(keyCode))],
captureMode: .single
)
// Clear previous selections first (including app/device conditions - revert to "Everywhere")
selectedApp = nil
selectedSystemAction = nil
selectedURL = nil
selectedAppCondition = nil
selectedDeviceCondition = nil
clearShiftedOutput()
// Set output based on action type
if let appId = appIdentifier, let appInfo = appLaunchInfo(for: appId) {
selectedApp = appInfo
self.outputLabel = appInfo.name
outputSequence = nil
AppLogger.shared.log("🖱️ [MapperViewModel] Key click - app launch: \(inputLabel) -> \(appInfo.name)")
} else if let urlId = urlIdentifier {
selectedURL = urlId
self.outputLabel = extractDomain(from: urlId)
outputSequence = nil
AppLogger.shared.log("🖱️ [MapperViewModel] Key click - URL: \(inputLabel) -> \(urlId)")
} else if let systemId = systemActionIdentifier, let systemAction = SystemActionInfo.find(byOutput: systemId) {
selectedSystemAction = systemAction
self.outputLabel = systemAction.name
outputSequence = nil
AppLogger.shared.log("🖱️ [MapperViewModel] Key click - system action: \(inputLabel) -> \(systemAction.name)")
} else if let systemAction = SystemActionInfo.find(byOutput: outputLabel) {
// Fallback path: some callers pass only a display label (e.g., "Notification Center")
// before the layer metadata has a concrete systemActionIdentifier.
selectedSystemAction = systemAction
self.outputLabel = systemAction.name
outputSequence = nil
AppLogger.shared.log("🖱️ [MapperViewModel] Key click - system action (fallback): \(inputLabel) -> \(systemAction.name)")
} else {
// Regular key mapping
self.outputLabel = formatKeyForDisplay(outputLabel)
outputSequence = KeySequence(
keys: [KeyPress(baseKey: outputLabel, modifiers: [], keyCode: 0)],
captureMode: .single
)
AppLogger.shared.log("🖱️ [MapperViewModel] Key click - key mapping: \(inputLabel) -> \(outputLabel)")
}
applyShiftedOutputPreset(shiftedOutputKey)
// If no custom shifted output was loaded, pre-populate with system default
if !hasShiftedOutputConfigured, let defaultShift = defaultShiftSymbol {
shiftedOutputLabel = defaultShift
shiftedOutputSequence = KeySequence(
keys: [KeyPress(baseKey: defaultShift, modifiers: [], keyCode: 0)],
captureMode: .single
)
isShiftedOutputDefault = true
}
// Update list of apps that have mappings for this key
Task { await updateAppsWithMapping() }
// Clear previous behavior (will be loaded separately via loadBehaviorFromExistingRule)
advancedBehavior.holdAction = ""
advancedBehavior.doubleTapAction = ""
advancedBehavior.macroBehavior = nil
advancedBehavior.comboKeys = []
advancedBehavior.comboOutput = ""
advancedBehavior.holdBehavior = .basic
advancedBehavior.tapTimeout = 200
advancedBehavior.holdTimeout = 200
advancedBehavior.customTapKeysText = ""
}
/// Load behavior from existing custom rule for the current input key
/// Call this after setInputFromKeyClick to restore hold/tap-dance settings
func loadBehaviorFromExistingRule(kanataManager: RuntimeCoordinator) {
guard let keyCode = inputKeyCode else { return }
let inputKey = OverlayKeyboardView.keyCodeToKanataName(keyCode)
// Look up existing rule
guard let existingRule = kanataManager.getCustomRule(forInput: inputKey) else {
// No custom rule — populate default shift symbol if available
if !hasShiftedOutputConfigured, let defaultShift = defaultShiftSymbol {
shiftedOutputLabel = defaultShift
shiftedOutputSequence = KeySequence(
keys: [KeyPress(baseKey: defaultShift, modifiers: [], keyCode: 0)],
captureMode: .single
)
isShiftedOutputDefault = true
}
AppLogger.shared.log("📖 [MapperViewModel] No existing behavior for input '\(inputKey)'")
return
}
applyShiftedOutputPreset(existingRule.shiftedOutput)
// If a custom shifted output was loaded, mark it as non-default
if hasShiftedOutputConfigured {
isShiftedOutputDefault = false
} else if let defaultShift = defaultShiftSymbol {
// No custom shift in rule — populate default
shiftedOutputLabel = defaultShift
shiftedOutputSequence = KeySequence(
keys: [KeyPress(baseKey: defaultShift, modifiers: [], keyCode: 0)],
captureMode: .single
)
isShiftedOutputDefault = true
}
guard let behavior = existingRule.behavior else {
AppLogger.shared.log("📖 [MapperViewModel] No existing behavior for input '\(inputKey)'")
return
}
switch behavior {
case let .dualRole(dualRole):
advancedBehavior.holdAction = dualRole.holdActionString
advancedBehavior.tapTimeout = dualRole.tapTimeout
advancedBehavior.holdTimeout = dualRole.holdTimeout
// Determine hold behavior type from flags
if dualRole.activateHoldOnOtherKey {
advancedBehavior.holdBehavior = .triggerEarly
} else if dualRole.quickTap {
advancedBehavior.holdBehavior = .quickTap
} else if !dualRole.customTapKeys.isEmpty {
advancedBehavior.holdBehavior = .customKeys
advancedBehavior.customTapKeysText = dualRole.customTapKeys.joined(separator: " ")
} else {
advancedBehavior.holdBehavior = .basic
}
AppLogger.shared.log("📖 [MapperViewModel] Loaded dualRole behavior for '\(inputKey)': hold='\(dualRole.holdAction)'")
case let .tapOrTapDance(tapBehavior):
switch tapBehavior {
case .tap:
AppLogger.shared.log("📖 [MapperViewModel] Loaded tap behavior for '\(inputKey)'")
case let .tapDance(tapDance):
// Load timing
advancedBehavior.tapTimeout = tapDance.windowMs
// Load tap-dance steps
// First step (index 0) is single tap - already loaded in outputLabel
if tapDance.steps.count > 1 {
advancedBehavior.doubleTapAction = tapDance.steps[1].actionString
}
// Load additional steps into tapDanceSteps array (triple tap, quad tap, etc.)
if tapDance.steps.count > 2 {
advancedBehavior.tapDanceSteps = tapDance.steps.dropFirst(2).map { step in
(label: step.label, action: step.actionString, isRecording: false)
}
}
AppLogger.shared.log("📖 [MapperViewModel] Loaded tapDance behavior for '\(inputKey)': \(tapDance.steps.count) steps, windowMs=\(tapDance.windowMs)")
}
case let .macro(macro):
advancedBehavior.macroBehavior = macro
AppLogger.shared.log("📖 [MapperViewModel] Loaded macro behavior for '\(inputKey)'")
case let .chord(chord):
// Load chord: remove the input key from the keys list (it's implicit)
advancedBehavior.comboKeys = chord.keys.filter { $0.lowercased() != inputKey.lowercased() }
advancedBehavior.comboOutput = chord.outputString
advancedBehavior.comboTimeout = chord.timeout
AppLogger.shared.log("📖 [MapperViewModel] Loaded chord behavior for '\(inputKey)': keys=\(chord.keys), output='\(chord.outputString)'")
}
}
/// Update the list of apps that have a mapping for the currently selected input key
func updateAppsWithMapping() async {
guard let keyCode = inputKeyCode else {
appsWithCurrentKeyMapping = []
return
}
let inputKey = OverlayKeyboardView.keyCodeToKanataName(keyCode)
appsWithCurrentKeyMapping = await AppKeymapStore.shared.getAppsWithMapping(forInputKey: inputKey)
}
/// Apply preset values from overlay click
func applyPresets(
input: String,
output: String,
layer: String? = nil,
inputKeyCode: UInt16? = nil,
appIdentifier: String? = nil,
systemActionIdentifier: String? = nil,
urlIdentifier: String? = nil,
shiftedOutput: String? = nil
) {
// Stop any active recording
stopRecording()
// Store original context for reset after clear
originalInputKey = input
originalOutputKey = output
originalShiftedOutputKey = shiftedOutput
originalAppIdentifier = appIdentifier
originalSystemActionIdentifier = systemActionIdentifier
originalURL = urlIdentifier
originalLayer = layer
// Clear any previously saved rule ID since we're starting fresh
lastSavedRuleID = nil
selectedApp = nil
selectedSystemAction = nil
selectedURL = nil
clearShiftedOutput()
// Set the layer
if let layer {
currentLayer = layer
}
// Set the input label and sequence
inputLabel = formatKeyForDisplay(input)
// Create simple key sequences for the presets
// Use provided keyCode if available (from overlay), otherwise 0 as placeholder
let keyCodeToUse = inputKeyCode ?? 0
inputSequence = KeySequence(
keys: [KeyPress(baseKey: input, modifiers: [], keyCode: Int64(keyCodeToUse))],
captureMode: .single
)
if let appIdentifier, let appInfo = appLaunchInfo(for: appIdentifier) {
selectedApp = appInfo
outputLabel = appInfo.name
outputSequence = nil
AppLogger.shared.log("🗺️ [MapperViewModel] Preset output is app launch: \(appInfo.name)")
} else if let urlIdentifier {
selectedURL = urlIdentifier
outputLabel = extractDomain(from: urlIdentifier)
outputSequence = nil
AppLogger.shared.log("🗺️ [MapperViewModel] Preset output is URL: \(urlIdentifier)")
} else if let systemActionIdentifier,
let systemAction = SystemActionInfo.find(byOutput: systemActionIdentifier)
{
// It's a system action/media key - set selectedSystemAction for SF Symbol rendering
selectedSystemAction = systemAction
outputLabel = systemAction.name
outputSequence = nil
AppLogger.shared.log("🗺️ [MapperViewModel] Preset output is system action: \(systemAction.name)")
} else if let systemAction = SystemActionInfo.find(byOutput: output) {
// Fallback: resolve by output label
selectedSystemAction = systemAction
outputLabel = systemAction.name
outputSequence = nil
AppLogger.shared.log("🗺️ [MapperViewModel] Preset output is system action: \(systemAction.name)")
} else {
// Regular key mapping
outputLabel = formatKeyForDisplay(output)
outputSequence = KeySequence(
keys: [KeyPress(baseKey: output, modifiers: [], keyCode: 0)],
captureMode: .single
)
}
applyShiftedOutputPreset(shiftedOutput)
// Store the keyCode for proper keycap rendering
if let inputKeyCode {
self.inputKeyCode = inputKeyCode
}
statusMessage = nil
statusIsError = false
AppLogger.shared.log("📝 [MapperViewModel] Applied presets: \(input) → \(output) [layer: \(currentLayer)] [inputKeyCode: \(keyCodeToUse)]")
}
/// Format a kanata key name for display (e.g., "leftmeta" -> "⌘")
/// Uses the centralized KeyDisplayFormatter utility.
func formatKeyForDisplay(_ key: String) -> String {
AppLogger.shared.log("🔤 [MapperViewModel] formatKeyForDisplay input: '\(key)'")
let result = KeyDisplayFormatter.format(key)
AppLogger.shared.log("🔤 [MapperViewModel] formatKeyForDisplay output: '\(result)'")
return result
}
func formattedSequenceForDisplay(_ sequence: String) -> String {
sequence
.split(separator: " ")
.map { formatKeyForDisplay(String($0)) }
.joined(separator: " ")
}
func applyShiftedOutputPreset(_ shiftedOutput: String?) {
guard let shiftedOutput = shiftedOutput?.trimmingCharacters(in: .whitespacesAndNewlines),
!shiftedOutput.isEmpty
else {
clearShiftedOutput()
return
}
originalShiftedOutputKey = shiftedOutput
shiftedOutputLabel = formattedSequenceForDisplay(shiftedOutput)
shiftedOutputSequence = KeySequence(
keys: [KeyPress(baseKey: shiftedOutput, modifiers: [], keyCode: 0)],
captureMode: .single
)
isShiftedOutputDefault = false
}
/// Show a success status message that auto-dismisses after a delay
/// Show a success status message that auto-dismisses after a delay
func showTransientStatus(_ message: String, duration: Duration = .seconds(2)) {
statusDismissTask?.cancel()
statusMessage = message
statusIsError = false
statusDismissTask = Task { @MainActor in
try? await Task.sleep(for: duration)
guard !Task.isCancelled else { return }
withAnimation(.easeOut(duration: 0.3)) {
statusMessage = nil
}
}
}
func clearShiftedOutput() {
shiftedOutputLabel = nil
shiftedOutputSequence = nil
originalShiftedOutputKey = nil
isRecordingShiftedOutput = false
isShiftedOutputDefault = false
}
func currentShiftedOutputKanataString() -> String? {
// Don't save system default shift as a custom rule
guard !isShiftedOutputDefault else { return nil }
guard let shiftedOutputSequence else { return nil }
let kanata = convertSequenceToKanataFormat(shiftedOutputSequence)
return kanata.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : kanata
}
func toggleInputRecording() {
if isRecordingInput {
stopRecording()
} else {
// Stop output recording if active
if isRecordingOutput || isRecordingShiftedOutput {
stopRecording()
}
startInputRecording()
}
}
func toggleOutputRecording() {
if isRecordingOutput {
stopRecording()
} else {
// Stop input recording if active
if isRecordingInput || isRecordingShiftedOutput {
stopRecording()
}
startOutputRecording()
}
}
func toggleShiftedOutputRecording() {
if isRecordingShiftedOutput {
stopRecording()
} else {
if isRecordingInput || isRecordingOutput {
stopRecording()
}
startShiftedOutputRecording()
}
}
func toggleHoldRecording() {
// Check for conflict: if tap-dance is set, show conflict dialog
if checkHoldConflict() {
pendingConflictType = .holdVsTapDance
pendingConflictField = "hold"
showConflictDialog = true
return
}
if isRecordingHold {
isRecordingHold = false
stopSimpleKeyCapture()
} else {
// Stop any other recording
stopRecording()
isRecordingHold = true
startSimpleKeyCapture { [weak self] keyName in
self?.holdAction = keyName
self?.isRecordingHold = false
}
}
}
func toggleDoubleTapRecording() {
// Clear macro if needed
if macroBehavior?.isValid == true {
macroBehavior = nil
}
// Check for conflict: if hold is set, show conflict dialog
if advancedBehavior.checkTapDanceConflict() {
pendingConflictType = .holdVsTapDance
pendingConflictField = "doubleTap"
showConflictDialog = true
return
}
if isRecordingDoubleTap {
isRecordingDoubleTap = false
stopMultiTapSequenceCapture(finalize: true)
} else {
// Stop any other recording
stopRecording()
stopAllRecording()
isRecordingDoubleTap = true
startMultiTapSequenceCapture(
onUpdate: { [weak self] action in
self?.doubleTapAction = action
},
onFinalize: { [weak self] action in
self?.doubleTapAction = action
},
onStop: { [weak self] in
self?.isRecordingDoubleTap = false
}
)
}
}
func toggleComboOutputRecording() {
if isRecordingComboOutput {
isRecordingComboOutput = false
stopSimpleKeyCapture()
} else {
// Stop any other recording
stopRecording()
isRecordingComboOutput = true
startSimpleKeyCapture { [weak self] keyName in
self?.comboOutput = keyName
self?.isRecordingComboOutput = false
}
}
}
}