forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloatingControlBarWindow.swift
More file actions
5926 lines (5469 loc) · 236 KB
/
Copy pathFloatingControlBarWindow.swift
File metadata and controls
5926 lines (5469 loc) · 236 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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Cocoa
import Combine
@preconcurrency import ObjectiveC
import OmiTheme
import SwiftUI
import VoiceTurnDomain
/// Boxes a non-Sendable completion closure so NSAnimationContext's
/// `@Sendable` completion handler can carry it across to the main actor.
private struct AnimationCompletionBox: @unchecked Sendable {
let value: () -> Void
}
private final class FloatingBarHostingView<Content: View>: NSHostingView<Content> {
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
true
}
}
private final class FloatingBarContainerView: NSView {
weak var controlBarWindow: FloatingControlBarWindow?
override func updateTrackingAreas() {
super.updateTrackingAreas()
trackingAreas.forEach(removeTrackingArea)
addTrackingArea(
NSTrackingArea(
rect: bounds,
options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect],
owner: self,
userInfo: nil
))
}
override func mouseEntered(with event: NSEvent) {
controlBarWindow?.updateNotchPointer(from: event)
}
override func mouseMoved(with event: NSEvent) {
controlBarWindow?.updateNotchPointer(from: event)
}
override func mouseExited(with event: NSEvent) {
controlBarWindow?.updateNotchPointerFromGlobalMouse()
}
override func hitTest(_ point: NSPoint) -> NSView? {
guard controlBarWindow?.acceptsMouseHit(inContentPoint: point) ?? true else {
return nil
}
return super.hitTest(point)
}
}
extension Duration {
fileprivate var millisecondsString: String {
let components = self.components
let milliseconds =
Double(components.seconds) * 1000
+ Double(components.attoseconds) / 1_000_000_000_000_000
return String(format: "%.1f", milliseconds)
}
}
/// NSPanel subclass for the floating control bar.
///
/// Using a non-activating panel lets the Ask Omi shortcut focus the floating bar
/// without surfacing the main Omi window when the app is already running.
class FloatingControlBarWindow: NSPanel, NSWindowDelegate {
private static let positionKey = "FloatingControlBarPosition"
private static let sizeKey = "FloatingControlBarSize"
private static let defaultSize = NSSize(width: 40, height: 14)
private static let minBarSize = NSSize(width: 40, height: 14)
/// Fallback physical notch dead zone. Prefer `notchHiddenCenterWidth(for:)`,
/// which reads macOS' actual top auxiliary areas for the current screen.
static let fallbackNotchHiddenCenterWidth: CGFloat = 172
static let notchHiddenCenterSafetyPadding: CGFloat = 34
static var notchHiddenCenterWidth: CGFloat {
fallbackNotchHiddenCenterWidth + notchHiddenCenterSafetyPadding
}
static let notchCompactSideWidth: CGFloat = 30
static let notchActiveSideWidth: CGFloat = 42
/// Voice owns a wider trailing lobe so the notch can show a persistent
/// stop/send affordance while a turn is capturing.
static let notchVoiceSideWidth: CGFloat = NotchVoiceControlPresentation.activeSideWidth
/// Thinking keeps the compact active lobe width: the visible state is the
/// spinning Omi mark only, without a right-side text label.
static let notchThinkingSideWidth: CGFloat = notchActiveSideWidth
static let defaultNotchChromeHeight: CGFloat = 34
static var notchChromeHeight: CGFloat { defaultNotchChromeHeight }
static let notchActivationHeight: CGFloat = 17
static let notchGlowOutsetX: CGFloat = 24
static let notchGlowOutsetBottom: CGFloat = 24
static let notchConversationBottomPadding: CGFloat = 18
static let notchInputPanelVerticalPadding: CGFloat = 46
static let notchInputPanelMinimumContentHeight: CGFloat = 40
/// Extra vertical budget added on top of the input editor when notch mode
/// renders the "Back / Omi Chat" header above the input (agent pills present).
/// Header row (32pt) + VStack top padding (8) + spacing (8) = 48pt.
static let notchChatHeaderVerticalBudget: CGFloat = 48
static let notchAgentListMaxVisibleAgents = 8
static let notchAgentListRowHeight: CGFloat = 44
static let notchAgentListRowSpacing: CGFloat = 0
static let notchAgentListVerticalPadding: CGFloat = 0
static let notchAgentListBottomMargin: CGFloat = 8
static let notchHoverMenuBottomMargin: CGFloat = 8
private static let responseStreamingResizeStep: CGFloat = 56
private static let legacyPillGlowOutsetX: CGFloat = 22
private static let legacyPillGlowOutsetY: CGFloat = 18
static func notchAgentListHeight(agentCount: Int) -> CGFloat {
let visibleCount = min(max(0, agentCount), notchAgentListMaxVisibleAgents)
guard visibleCount > 0 else { return 0 }
return notchAgentListVerticalPadding * 2
+ CGFloat(visibleCount) * notchAgentListRowHeight
+ CGFloat(max(0, visibleCount - 1)) * notchAgentListRowSpacing
+ notchAgentListBottomMargin
}
/// Height reserved for the shortcut legend + capture controls on the trailing side.
/// The panel is always present, so the hover surface always has height.
static let notchControlPanelHeight: CGFloat = 92
/// Vertical offset of the control panel inside the hover surface.
/// Spawned agents own the top of the surface (their dots live in the leading lobe and
/// their rows render full-width just under the chrome), so the panel stacks beneath them
/// rather than overlapping.
static func notchControlPanelTopOffset(agentCount: Int) -> CGFloat {
NotchAgentMenuPresentation.hasAgentRows(agentCount: agentCount)
? notchAgentListHeight(agentCount: agentCount) : 0
}
static func notchHoverMenuHeight(agentCount: Int) -> CGFloat {
guard NotchAgentMenuPresentation.shouldPresent(agentCount: agentCount) else { return 0 }
return notchControlPanelTopOffset(agentCount: agentCount)
+ notchControlPanelHeight
+ notchHoverMenuBottomMargin
}
static let expandedBarSize = NSSize(width: 210, height: 50)
/// Center gap between the two chrome lobes on displays without a notch —
/// there is no camera housing to straddle, so keep a small deliberate gap
/// instead of the phantom notch dead zone.
static let pillSurfaceCenterGapWidth: CGFloat = 56
/// Slim top inset that replaces the notch chrome band on the pill's
/// expanded surfaces (agent list, chat).
static let pillSurfaceTopPadding: CGFloat = 10
/// Pill-mode Ask Omi input panel height (top inset + editor + padding).
static var pillInputPanelHeight: CGFloat {
pillSurfaceTopPadding + notchInputPanelMinimumContentHeight + notchInputPanelVerticalPadding
}
private static let voiceBarSize = NSSize(width: 224, height: 42)
/// Readable status strip under chrome/pill for too-short PTT / mic errors.
static let pttHintRowHeight: CGFloat = 30
private static let maxBarSize = NSSize(width: 1200, height: 1000)
/// The bar must never be buried under third-party overlay apps: notch
/// companions (e.g. Clicky) park windows at .popUpMenu (101) and full-screen
/// overlays at .screenSaver (1000), so .statusBar (25) lost the notch to
/// them. Assistive-tech-high (1500) beats every common overlay level while
/// staying below the system cursor and the screen-lock shield.
static let alwaysOnTopLevel = NSWindow.Level(
rawValue: Int(CGWindowLevelForKey(.assistiveTechHighWindow))
)
/// Always-on overlay: present on every Space, pinned through Mission Control,
/// and omitted from Cmd-` cycling. Click and hover still reach the panel;
/// `.transient` would let AppKit scoop it during Space switches.
static let overlayCollectionBehavior: NSWindow.CollectionBehavior = [
.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle,
]
static let notchExpandedWidth: CGFloat = 382
static let notificationWidth: CGFloat = 508
private static let notificationHeight: CGFloat = 128
private static let notificationSpacing: CGFloat = 8
/// Vertical room for the readable PTT status banner under chrome/pill.
static var pttStatusBannerBudget: CGFloat { notificationSpacing + pttHintRowHeight }
private static let askOmiAnimationDuration: TimeInterval = 0.14
private static let askOmiSettleDelay: TimeInterval = 0.16
/// Hover-menu (agent switcher) motion. SwiftUI owns the per-frame content
/// morph; AppKit only snaps the panel once to the entering or settled size.
/// This avoids WindowServer work during the animation without reserving a
/// transparent maximum-size window over unrelated controls.
///
/// Pill mode still resizes its panel; it keeps the duration constants
/// below shared with its content transitions so both finish together.
static let notchHoverMenuExpandAnimation: Animation = .spring(response: 0.35, dampingFraction: 0.75)
static let notchHoverMenuCollapseAnimation: Animation = .spring(response: 0.3, dampingFraction: 1.0)
static let notchHoverMenuExpandDuration: TimeInterval = 0.16
static let notchHoverMenuCollapseDuration: TimeInterval = 0.10
/// How long after the collapse spring's logical completion its visual tail
/// can still hold the content's min size above the idle island height.
static let notchHoverMenuCollapseSettleTail: TimeInterval = 0.45
private static let frameNoopEpsilon: CGFloat = 0.5
private static let startupDisplayRevalidationDelays: [TimeInterval] = [0.2, 0.8, 2.0]
private static let topInset: CGFloat = 40
private static let topInsetWhenNotchModeFallsBackToPill: CGFloat = 4
/// Minimum window height when AI response first appears.
private static let minResponseHeight: CGFloat = 250
/// Base height used as the reference for 2× cap (same as current default response height).
private static let defaultBaseResponseHeight: CGFloat = 430
/// Overhead (px) added to measured scroll content to account for control bar, header, follow-up input, and padding.
private static let responseViewOverhead: CGFloat = 199
let state = FloatingControlBarState()
private var hostingView: NSHostingView<AnyView>?
private var isResizingProgrammatically = false
private var isUserDragging = false
/// Set by ResizeHandleNSView while the user is manually dragging the corner.
/// Prevents the response-height observer from fighting manual resize.
var isUserResizing = false
/// Suppresses hover resizes during close animation to prevent position drift.
private var suppressHoverResize = false
private var inputHeightCancellable: AnyCancellable?
private var responseHeightCancellable: AnyCancellable?
private var agentPillsCancellable: AnyCancellable?
private var voiceResponseGlowCancellable: AnyCancellable?
private var draggableBarCancellable: AnyCancellable?
private let cursorScreenTracker = CursorScreenTracker()
private var pttHintCancellable: AnyCancellable?
var mouseInterceptionReconciler: FloatingBarMouseInterceptionReconciler?
private var previousVoiceResponseGlowActive = false
private var resizeWorkItem: DispatchWorkItem?
var notchRetractionScheduler: DelayedActionScheduling = TaskDelayedActionScheduler()
var notchRetractionCancellation: DelayedActionCancellation?
var notchRetractionGeneration = 0
var notchRevealGeneration = 0
var notchRevealCancellation: DelayedActionCancellation?
/// Saved center point from before chat opened, used to restore position on close.
private var preChatCenter: NSPoint?
/// Token incremented each time a windowDidResignKey dismiss animation starts.
/// Checked in the completion block so a new PTT query can cancel a stale close.
private var resignKeyAnimationToken: Int = 0
/// The target origin of an in-progress close/restore animation, set in
/// closeAIConversation() and cleared when the animation settles.
/// Used by savePreChatCenterIfNeeded() to snap to the correct pill position
/// if a new PTT query fires while the restore animation is still running.
// Stores the FULL pending restore frame (origin AND size), not just the origin.
// The restore origin is computed for the glow-inflated window size; snapping to
// it with the bare collapsed size instead drifted the recorded center by one
// glow outset (~22pt left / 18pt down) on every rapid re-open cycle.
private var pendingRestoreFrame: NSRect?
/// The idle pill frame captured just before morphing into the active island
/// on a non-notch display, so the pill returns to the exact same spot.
private var savedPillFrame: NSRect?
var frameAnimationToken: Int = 0
private var pendingFrameAnimationTarget: NSRect?
private var startupDisplayRevalidationWorkItems: [DispatchWorkItem] = []
/// In-process NSMenus (bar context menus, the model picker) render at
/// .popUpMenu (101); while one is tracking, the bar drops to that level so
/// the island cannot occlude its own menus. Depth-counted because nested
/// submenus emit their own begin/end tracking notifications.
private var menuTrackingDepth = 0
private nonisolated(unsafe) var menuTrackingObservers: [NSObjectProtocol] = []
/// The bar adopts the notch-island presentation whenever it is actively
/// engaged — PTT listening, thinking, or speaking a reply — on ANY display,
/// so external monitors morph from the idle pill into the island too.
private var barWantsActiveIsland: Bool {
state.isVoicePresentationActive
}
private var notchModeEnabled: Bool {
Self.shouldUseNotchIsland(
displayHasCameraHousing: Self.screenHasCameraHousing(screenForPlacement),
hasActiveIsland: barWantsActiveIsland,
draggableBarEnabled: ShortcutSettings.shared.draggableBarEnabled
)
}
/// Hardware-only notch detection (ignores the transient active-island state) —
/// "does this display physically have a camera housing".
var usesNotchIslandForCurrentScreen: Bool {
Self.screenHasCameraHousing(screenForPlacement)
}
private var screenForPlacement: NSScreen? {
FloatingBarPlacementScreenPolicy.screenForRecentering(
barScreen: self.screen,
cursorScreen: Self.screenContainingCursor(),
mainScreen: NSScreen.main,
firstScreen: NSScreen.screens.first
)
}
private static func screenContainingCursor() -> NSScreen? {
let mouseLocation = NSEvent.mouseLocation
return NSScreen.screens.first(where: { $0.frame.contains(mouseLocation) })
}
private func screenUnderCursor() -> NSScreen? {
Self.screenContainingCursor()
}
private var usesVoiceNotchControl: Bool {
state.voiceProjection.isListening
}
private var notchSideWidth: CGFloat {
if usesVoiceNotchControl {
return Self.notchVoiceSideWidth
}
if state.showingAIConversation {
return AgentPillsManager.shared.pills.isEmpty
? Self.notchCompactSideWidth
: Self.notchActiveSideWidth
}
if AgentPillsManager.shared.pills.isEmpty && !state.isVoicePresentationActive {
return Self.notchCompactSideWidth
}
return Self.notchActiveSideWidth
}
private var notchHiddenCenterWidthForCurrentScreen: CGFloat {
Self.notchHiddenCenterWidth(for: screenForPlacement)
}
private var notchChromeHeightForCurrentScreen: CGFloat {
Self.notchChromeHeight(for: screenForPlacement)
}
private var notchInputPanelHeightForCurrentScreen: CGFloat {
Self.notchInputPanelHeight(for: screenForPlacement)
}
private func notchSize(active: Bool) -> NSSize {
let sideWidth =
active
? (usesVoiceNotchControl ? Self.notchVoiceSideWidth : Self.notchActiveSideWidth)
: Self.notchCompactSideWidth
return notchSize(sideWidth: sideWidth)
}
private func notchSize(sideWidth: CGFloat) -> NSSize {
return NSSize(
width: notchHiddenCenterWidthForCurrentScreen + sideWidth * 2, height: notchChromeHeightForCurrentScreen)
}
private func notchSize(sideWidth: CGFloat, for screen: NSScreen) -> NSSize {
NSSize(
width: Self.notchHiddenCenterWidth(for: screen) + sideWidth * 2,
height: Self.notchChromeHeight(for: screen)
)
}
private func responseGlowWindowSize(forSurfaceSize size: NSSize, usesNotchIsland: Bool) -> NSSize {
if usesNotchIsland {
return NSSize(
width: size.width + Self.notchGlowOutsetX * 2,
height: size.height + Self.notchGlowOutsetBottom
)
}
guard state.isVoiceResponseGlowActive || collapsedPillAgentGlowActive else { return size }
guard size.width <= Self.minBarSize.width + 0.5,
size.height <= Self.minBarSize.height + 0.5
else { return size }
return NSSize(
width: size.width + Self.legacyPillGlowOutsetX * 2,
height: size.height + Self.legacyPillGlowOutsetY * 2
)
}
/// Whether the collapsed pill is showing the ambient subagent status
/// tint/glow (mirrors `NotchAgentStatusGroup.aggregate`: finished agents
/// the user has viewed go quiet).
private var collapsedPillAgentGlowActive: Bool {
!notchModeEnabled
&& AgentPillsManager.shared.pills.contains {
!($0.status.isFinished && $0.viewedAt != nil)
}
}
private func responseGlowWindowSizeForCurrentScreen(forSurfaceSize size: NSSize) -> NSSize {
responseGlowWindowSize(forSurfaceSize: size, usesNotchIsland: notchModeEnabled)
}
/// Bare hover-menu surface size. `resizeAnchored` adds the transparent glow
/// outsets exactly once when converting this to an NSPanel frame.
private func notchHoverMenuSurfaceSize(agentCount: Int) -> NSSize {
NSSize(
width: max(collapsedBarSize.width, Self.notchExpandedWidth),
height: notchChromeHeightForCurrentScreen
+ Self.notchHoverMenuHeight(agentCount: agentCount)
)
}
private func notchHoverMenuSurfaceSize(agentCount: Int, for screen: NSScreen) -> NSSize {
NSSize(
width: max(notchCollapsedSize(for: screen).width, Self.notchExpandedWidth),
height: Self.notchChromeHeight(for: screen) + Self.notchHoverMenuHeight(agentCount: agentCount)
)
}
private func notchIdleOrHoverSurfaceSize() -> NSSize {
state.isNotchHoverMenuVisible
? notchHoverMenuSurfaceSize(agentCount: AgentPillsManager.shared.pills.count)
: notchCollapsedSize
}
private func notchIdleOrHoverSurfaceSize(for screen: NSScreen) -> NSSize {
state.isNotchHoverMenuVisible
? notchHoverMenuSurfaceSize(agentCount: AgentPillsManager.shared.pills.count, for: screen)
: notchCollapsedSize(for: screen)
}
/// Height of the visible notch content (chrome band, plus the open hover
/// menu sized to the current agent count).
private var notchVisibleContentHeight: CGFloat {
var height = notchChromeHeightForCurrentScreen
if state.isNotchHoverMenuVisible {
height += Self.notchHoverMenuHeight(agentCount: AgentPillsManager.shared.pills.count)
}
return height
}
/// Width of the visible notch content for the idle ↔ hover lifecycle.
private var notchVisibleContentWidth: CGFloat {
state.isNotchHoverMenuVisible
? max(notchCollapsedSize.width, Self.notchExpandedWidth)
: notchCollapsedSize.width
}
/// Horizontal transparent margin reserved for the rendered glow.
private var notchVisibleContentHorizontalOutset: CGFloat {
max(Self.notchGlowOutsetX, (frame.width - notchVisibleContentWidth) / 2)
}
private func currentResponseSurfaceHeight(usesNotchIsland: Bool? = nil) -> CGFloat {
if usesNotchIsland ?? notchModeEnabled {
return max(0, frame.height - Self.notchGlowOutsetBottom)
}
return frame.height
}
private func currentResponseSurfaceWidth(usesNotchIsland: Bool? = nil) -> CGFloat {
if usesNotchIsland ?? notchModeEnabled {
return max(0, frame.width - Self.notchGlowOutsetX * 2)
}
return frame.width
}
private var notchCollapsedSize: NSSize {
NSSize(
width: notchHiddenCenterWidthForCurrentScreen + notchSideWidth * 2, height: notchChromeHeightForCurrentScreen)
}
private func notchCollapsedSize(for screen: NSScreen) -> NSSize {
notchSize(sideWidth: notchSideWidth, for: screen)
}
private var collapsedBarSize: NSSize { notchModeEnabled ? notchCollapsedSize : Self.minBarSize }
private var expandedContentWidth: CGFloat { Self.notchExpandedWidth }
private var inputPanelHeight: CGFloat {
// Chat always mounts shared top chrome, so budget chrome height even off-notch.
let base =
(notchModeEnabled || state.showingAIConversation)
? notchInputPanelHeightForCurrentScreen
: Self.pillInputPanelHeight
let statusBanner = state.pttHintText.isEmpty ? 0 : Self.pttStatusBannerBudget
// When notch mode renders the "Back / Omi Chat" header (agent pills
// present), the input panel needs additional vertical room so the
// header + editor + padding all fit. (Codex P2 — input/send clipping.)
if !AgentPillsManager.shared.pills.isEmpty {
return base + statusBanner + Self.notchChatHeaderVerticalBudget
}
return base + statusBanner
}
var onPlayPause: (() -> Void)?
var onTogglePushToTalk: (() -> Void)?
var onAskAI: (() -> Void)?
var onHide: (() -> Void)?
var onSendQuery: ((String) -> Void)?
var onRate: ((String, Int?, ChatFeedbackReason?) -> Void)?
var onShareLink: (() async -> String?)?
override init(
contentRect: NSRect, styleMask style: NSWindow.StyleMask,
backing backingStoreType: NSWindow.BackingStoreType = .buffered, defer flag: Bool = false
) {
let initialScreen = FloatingBarPlacementScreenPolicy.screenForRecentering(
barScreen: Optional<NSScreen>.none,
cursorScreen: Self.screenContainingCursor(),
mainScreen: NSScreen.main,
firstScreen: NSScreen.screens.first
)
let initialUsesNotchIsland = FloatingControlBarWindow.shouldUseNotchIsland(
displayHasCameraHousing: FloatingControlBarWindow.screenHasCameraHousing(initialScreen),
hasActiveIsland: false,
draggableBarEnabled: ShortcutSettings.shared.draggableBarEnabled
)
let initialSize =
initialUsesNotchIsland
? NSSize(
width: FloatingControlBarWindow.notchHiddenCenterWidth(for: initialScreen)
+ FloatingControlBarWindow.notchCompactSideWidth * 2,
height: FloatingControlBarWindow.notchChromeHeight(for: initialScreen)
)
: FloatingControlBarWindow.minBarSize
let initialRect = NSRect(origin: .zero, size: initialSize)
super.init(
contentRect: initialRect,
styleMask: [.borderless, .nonactivatingPanel],
backing: backingStoreType,
defer: flag
)
self.appearance = NSAppearance(named: .vibrantDark)
self.isOpaque = false
self.backgroundColor = .clear
self.hasShadow = false
// NSPanel defaults hidesOnDeactivate to true, which orders the notch out
// when another app activates. isFloatingPanel is the overlay companion;
// re-assert always-on-top after it so AppKit cannot drop us to .floating.
self.isFloatingPanel = true
self.hidesOnDeactivate = false
self.level = Self.alwaysOnTopLevel
self.collectionBehavior = Self.overlayCollectionBehavior
self.isMovableByWindowBackground = false
self.acceptsMouseMovedEvents = true
self.delegate = self
self.minSize = initialSize
self.maxSize = FloatingControlBarWindow.maxBarSize
setupViews()
updateNotchIslandState()
registerMenuTrackingObservers()
installMouseInterceptionSync()
if ShortcutSettings.shared.draggableBarEnabled,
!notchModeEnabled,
let savedPosition = UserDefaults.standard.string(forKey: FloatingControlBarWindow.positionKey)
{
let origin = NSPointFromString(savedPosition)
// Validate that the full bar frame (not just a 14pt inset) fits inside
// some screen's visibleFrame. visibleFrame already excludes the Dock
// and menu bar on macOS, so clamping against it is what keeps the
// input field above the Dock (#6684).
let candidateFrame = NSRect(origin: origin, size: frame.size)
if let targetScreen = NSScreen.screens.first(where: { $0.visibleFrame.intersects(candidateFrame) }) {
let clamped = FloatingControlBarWindow.clamp(candidateFrame, to: targetScreen.visibleFrame)
self.setFrameOrigin(clamped.origin)
} else {
centerOnMainScreen()
}
} else {
centerOnMainScreen()
}
syncMouseInterception()
scheduleStartupDisplayRevalidation()
}
deinit {
menuTrackingObservers.forEach(NotificationCenter.default.removeObserver)
}
override func makeKeyAndOrderFront(_ sender: Any?) {
cancelPendingRetraction()
applySurfaceLevel()
super.makeKeyAndOrderFront(sender)
syncMouseInterception()
}
override func orderFrontRegardless() {
cancelPendingRetraction()
applySurfaceLevel()
super.orderFrontRegardless()
syncMouseInterception()
}
override func orderOut(_ sender: Any?) {
notchRetractionGeneration &+= 1
notchRetractionCancellation?.cancel()
notchRetractionCancellation = nil
cancelInFlightNotchReveal()
state.notchRevealProgress = FloatingBarNotchRevealPolicy.revealedProgress
super.orderOut(sender)
syncMouseInterception()
}
// MARK: - Window Level
/// Reasserts the bar's always-on-top overlay chrome, yielding only the
/// window *level* while one of our own menus is open (menus render at
/// .popUpMenu and must stay clickable). hidesOnDeactivate is written every
/// pass so a later AppKit/default restore cannot hide the notch on deactivate.
func applySurfaceLevel() {
isFloatingPanel = true
hidesOnDeactivate = false
collectionBehavior = Self.overlayCollectionBehavior
level = menuTrackingDepth > 0 ? .popUpMenu : Self.alwaysOnTopLevel
}
private func registerMenuTrackingObservers() {
let center = NotificationCenter.default
menuTrackingObservers.append(
center.addObserver(
forName: NSMenu.didBeginTrackingNotification, object: nil, queue: .main
) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
self.menuTrackingDepth += 1
self.applySurfaceLevel()
}
})
menuTrackingObservers.append(
center.addObserver(
forName: NSMenu.didEndTrackingNotification, object: nil, queue: .main
) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
self.menuTrackingDepth = max(0, self.menuTrackingDepth - 1)
self.applySurfaceLevel()
}
})
}
/// Clamp `rect` so it stays entirely inside `visible`. visibleFrame already
/// excludes the Dock and menu bar, so clamping here keeps the Floating Bar
/// off both. This also gracefully handles rects larger than the screen.
static func clamp(_ rect: NSRect, to visible: NSRect) -> NSRect {
guard visible.width > 0 && visible.height > 0 else { return rect }
var r = rect
// Clamp x so the window fits between visible.minX and visible.maxX.
let maxX = max(visible.minX, visible.maxX - r.width)
r.origin.x = min(max(r.origin.x, visible.minX), maxX)
// Clamp y so the window fits between visible.minY and visible.maxY.
let maxY = max(visible.minY, visible.maxY - r.height)
r.origin.y = min(max(r.origin.y, visible.minY), maxY)
return r
}
static func screenHasCameraHousing(_ screen: NSScreen?) -> Bool {
// Testing hook: force the non-notch (pill) presentation on notched
// hardware so the fallback surface can be exercised locally. getenv so
// values loaded from the bundle .env (BundleEnvironment) are seen too.
if let forced = getenv("OMI_FORCE_NO_NOTCH"), String(cString: forced) == "1" { return false }
// Testing hook: force the notch-island presentation on non-notch hardware
// (external display / dev machine) so notch-only UI can be exercised
// locally. Mirror of OMI_FORCE_NO_NOTCH; NO_NOTCH wins if both are set.
if let forced = getenv("OMI_FORCE_NOTCH"), String(cString: forced) == "1" { return true }
guard let screen else { return false }
if #available(macOS 12.0, *) {
if let leftArea = screen.auxiliaryTopLeftArea,
let rightArea = screen.auxiliaryTopRightArea,
!leftArea.isEmpty,
!rightArea.isEmpty
{
return true
}
return screen.safeAreaInsets.top > 0
}
return false
}
/// A physical notch is fixed to the display, so the movable-bar preference
/// always opts into the pill presentation instead.
static func shouldUseNotchIsland(
displayHasCameraHousing: Bool,
hasActiveIsland: Bool,
draggableBarEnabled: Bool
) -> Bool {
!draggableBarEnabled && (displayHasCameraHousing || hasActiveIsland)
}
static func notchChromeHeight(for screen: NSScreen?) -> CGFloat {
guard let screen else { return notchChromeHeight }
if #available(macOS 12.0, *) {
return notchChromeHeight(
topSafeAreaInset: screen.safeAreaInsets.top,
auxiliaryTopLeftArea: screen.auxiliaryTopLeftArea,
auxiliaryTopRightArea: screen.auxiliaryTopRightArea
)
}
return notchChromeHeight
}
static func notchChromeHeight(
topSafeAreaInset: CGFloat,
auxiliaryTopLeftArea: NSRect?,
auxiliaryTopRightArea: NSRect?
) -> CGFloat {
let auxiliaryHeights = [auxiliaryTopLeftArea, auxiliaryTopRightArea]
.compactMap { area -> CGFloat? in
guard let area, !area.isEmpty, area.height > 0 else { return nil }
return area.height
}
let measuredHeight = max(topSafeAreaInset, auxiliaryHeights.max() ?? 0)
guard measuredHeight > 0 else { return notchChromeHeight }
return max(notchChromeHeight, measuredHeight)
}
static func notchInputPanelHeight(for screen: NSScreen?) -> CGFloat {
notchChromeHeight(for: screen) + notchInputPanelMinimumContentHeight + notchInputPanelVerticalPadding
}
static func notchHiddenCenterWidth(for screen: NSScreen?) -> CGFloat {
guard let screen else { return notchHiddenCenterWidth }
if #available(macOS 12.0, *),
let leftArea = screen.auxiliaryTopLeftArea,
let rightArea = screen.auxiliaryTopRightArea,
!leftArea.isEmpty,
!rightArea.isEmpty
{
let measuredGap = rightArea.minX - leftArea.maxX
if measuredGap > 0 {
return max(notchHiddenCenterWidth, measuredGap + notchHiddenCenterSafetyPadding)
}
}
return notchHiddenCenterWidth
}
private func updateNotchIslandState() {
if FloatingBarPlacementScreenPolicy.shouldHoldIslandModeWhileScreenIsReassigning(
isVisible: isVisible,
barScreenMissing: self.screen == nil
) {
applySurfaceLevel()
return
}
let usesNotch = notchModeEnabled
// Leaving the idle pill for the active island on a non-notch display —
// remember the pill's exact spot so we can restore it when we return
// (otherwise the pill drifts to a recomputed top-center each cycle).
if usesNotch, !state.usesNotchIsland, !Self.screenHasCameraHousing(screenForPlacement),
!state.showingAIConversation, state.currentNotification == nil
{
savedPillFrame = frame
}
if state.usesNotchIsland != usesNotch {
state.usesNotchIsland = usesNotch
}
if !usesNotch {
state.notchRevealProgress = 1
}
applySurfaceLevel()
}
private func refreshPresentationForDraggableBarPreference() {
let wasUsingNotchIsland = state.usesNotchIsland
updateNotchIslandState()
guard wasUsingNotchIsland != state.usesNotchIsland,
let screen = screenForPlacement
else { return }
let targetFrame = frameForCurrentState(on: screen, usesNotchIsland: state.usesNotchIsland)
resizeToFrame(
targetFrame,
makeResizable: state.showingAIConversation && state.showingAIResponse,
animated: isVisible
)
}
override var canBecomeKey: Bool { true }
override var canBecomeMain: Bool { false }
/// Unhandled keys stop here. This panel has no window controller, so `super.keyDown` has no next
/// responder to pass to and answers with `noResponderFor(_:)` — the alert sound — every time the
/// user types while the input field is not first responder (hover menu open, response showing).
/// Escape and Tab are the keys the window itself acts on (Tab so Full Keyboard Access can still
/// step into the panel's controls, which `NSWindow.keyDown` used to do); everything else is
/// deliberately absorbed.
override func keyDown(with event: NSEvent) {
switch event.keyCode {
case 53: // Escape
handleEscapeKey()
case 48: // Tab
if event.modifierFlags.contains(.shift) { selectPreviousKeyView(nil) } else { selectNextKeyView(nil) }
default:
break
}
}
func handleEscapeKey() {
if FloatingBarVoicePlaybackService.shared.isSpeaking {
FloatingBarVoicePlaybackService.shared.interruptCurrentResponse()
return
}
if !state.showingAIConversation, !notchModeEnabled, state.isNotchHoverMenuVisible {
setPillAgentListVisible(false)
return
}
guard state.showingAIConversation else { return }
if !state.aiInputText.isEmpty {
state.aiInputText = ""
return
}
if state.hasVisibleConversation {
clearVisibleConversationFromUI()
} else {
closeAIConversation()
}
}
private func setupViews() {
let swiftUIView = FloatingControlBarView(
window: self,
onPlayPause: { [weak self] in self?.onPlayPause?() },
onTogglePushToTalk: { [weak self] in self?.onTogglePushToTalk?() },
onAskAI: { [weak self] in self?.handleAskAI() },
onHide: { [weak self] in self?.hideBar() },
onSendQuery: { [weak self] message in self?.onSendQuery?(message) },
onCloseAI: { [weak self] in self?.closeAIConversation() },
onEscape: { [weak self] in self?.handleEscapeKey() },
onClearVisibleConversation: { [weak self] in self?.clearVisibleConversationFromUI() },
onRate: { [weak self] messageId, rating, reason in self?.onRate?(messageId, rating, reason) },
onShareLink: { [weak self] in await self?.onShareLink?() }
).environmentObject(state)
hostingView = FloatingBarHostingView(
rootView: AnyView(
swiftUIView
.withFontScaling()
.preferredColorScheme(.dark)
.environment(\.colorScheme, .dark)
))
hostingView?.appearance = NSAppearance(named: .vibrantDark)
// CRITICAL: Use a container view instead of making NSHostingView the contentView directly.
// When NSHostingView IS the contentView of a borderless window, it tries to negotiate
// window sizing through updateWindowContentSizeExtremaIfNecessary and updateAnimatedWindowSize,
// causing re-entrant constraint updates that crash in _postWindowNeedsUpdateConstraints.
// Wrapping in a container breaks that "I own this window" relationship.
//
// sizingOptions: Remove .intrinsicContentSize so the hosting view can expand beyond
// its SwiftUI ideal size. Keep .minSize and .maxSize for proper min/max constraints.
// Setting [] removes ALL sizing info (broken). Default includes .intrinsicContentSize
// which pins the view to its ideal size (prevents expansion). [.minSize, .maxSize] is correct.
let container = FloatingBarContainerView()
container.controlBarWindow = self
container.wantsLayer = true
container.layer?.backgroundColor = NSColor.clear.cgColor
self.contentView = container
if let hosting = hostingView {
hosting.sizingOptions = [.minSize, .maxSize]
hosting.wantsLayer = true
hosting.layer?.backgroundColor = NSColor.clear.cgColor
hosting.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(hosting)
NSLayoutConstraint.activate([
hosting.leadingAnchor.constraint(equalTo: container.leadingAnchor),
hosting.trailingAnchor.constraint(equalTo: container.trailingAnchor),
hosting.topAnchor.constraint(equalTo: container.topAnchor),
hosting.bottomAnchor.constraint(equalTo: container.bottomAnchor),
])
}
NotificationCenter.default.addObserver(
forName: .floatingBarDragDidStart, object: nil, queue: .main
) { [weak self] _ in
Task { @MainActor in
self?.isUserDragging = true
self?.state.isDragging = true
}
}
NotificationCenter.default.addObserver(
forName: .floatingBarDragDidEnd, object: nil, queue: .main
) { [weak self] _ in
Task { @MainActor in
self?.isUserDragging = false
self?.state.isDragging = false
}
}
// Re-validate position when monitors are connected/disconnected
NotificationCenter.default.addObserver(
forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main
) { [weak self] _ in
Task { @MainActor in
self?.validatePositionOnScreenChange(reason: "screen_parameters_changed")
self?.cursorScreenTracker.sync()
}
}
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.activeSpaceDidChangeNotification, object: nil, queue: .main
) { [weak self] _ in
Task { @MainActor in
self?.performSpacesTransitionGrowIn()
}
}
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didWakeNotification, object: nil, queue: .main
) { [weak self] _ in
Task { @MainActor in
self?.restoreDurableBarIfAppKitOrderedItOut()
self?.validatePositionOnScreenChange(reason: "workspace_did_wake")
}
}
draggableBarCancellable = ShortcutSettings.shared.$draggableBarEnabled
.dropFirst()
.sink { [weak self] _ in
Task { @MainActor in
self?.refreshPresentationForDraggableBarPreference()
}
}
// Follow cursor across monitors — poll mouse position to move bar instantly
cursorScreenTracker.start { [weak self] in self?.checkCursorScreen() }
observeNotchAgentPills()
observeVoiceResponseGlow()
observePttHint()
}
// Internal so the regression test can exercise the same workspace-transition
// path that the NSWorkspace observer invokes.
func performSpacesTransitionGrowIn() {
restoreDurableBarIfAppKitOrderedItOut()
let previousUsesNotchIsland = state.usesNotchIsland
updateNotchIslandState()
// Do not replay the reveal "pop" on Space changes; preserve chat size while
// non-chat surfaces recover their canonical frame from this callback.
state.notchRevealProgress = FloatingBarNotchRevealPolicy.revealedProgress
let targetFrame = defaultFrameForCurrentState()
guard
FloatingBarPlacementScreenPolicy.shouldReconcileFrameAfterSpaceChange(
isVisible: isVisible,
showingAIConversation: state.showingAIConversation,
islandModeChanged: previousUsesNotchIsland != state.usesNotchIsland,
frameChanged: !Self.framesEquivalent(frame, targetFrame),
barScreenMissing: self.screen == nil
)
else { return }
resizeToFrame(targetFrame, makeResizable: styleMask.contains(.resizable), animated: false)
}
private func defaultFrameForCurrentState() -> NSRect {
let size: NSSize
if state.showingAIConversation {
let height = max(inputPanelHeight, frame.height)
size = NSSize(width: expandedContentWidth, height: height)
} else {
size = closedSurfaceSize(usesNotchIsland: notchModeEnabled)
}
let windowSize = responseGlowWindowSizeForCurrentScreen(forSurfaceSize: size)
return NSRect(origin: defaultTopCenteredOrigin(for: windowSize), size: windowSize)
}
private func currentSurfaceSize(
usesNotchIsland: Bool,
frameIncludesVoiceGlow: Bool? = nil
) -> NSSize {
if state.showingAIConversation {
let defaultWidth = Self.notchExpandedWidth
let width = max(defaultWidth, currentResponseSurfaceWidth(usesNotchIsland: usesNotchIsland))
// Chat always mounts shared top chrome, so budget chrome height even
// on non-notch displays (pillSurfaceTopPadding alone would clip).
let panelHeight = notchInputPanelHeightForCurrentScreen
let statusBanner = state.pttHintText.isEmpty ? 0 : Self.pttStatusBannerBudget
let reservedGlowOutset = usesNotchIsland ? Self.notchGlowOutsetBottom : 0
let contentHeight = max(panelHeight + statusBanner, frame.height - reservedGlowOutset)
return NSSize(width: width, height: contentHeight)
}
return closedSurfaceSize(usesNotchIsland: usesNotchIsland)
}
private func currentSurfaceSizeForCurrentScreen(frameIncludesVoiceGlow: Bool? = nil) -> NSSize {
currentSurfaceSize(usesNotchIsland: notchModeEnabled, frameIncludesVoiceGlow: frameIncludesVoiceGlow)
}
/// The mounted notification card's own surface: chrome band, the gap under
/// it, and the card body. Single authority — every caller that needs to know
/// how big a card is (sizing, resizing, PTT and status-banner unions) reads
/// it here rather than re-deriving `notificationWidth` locally.
private func notificationSurfaceSize(usesNotchIsland: Bool, screen: NSScreen? = nil) -> NSSize {
let barHeight: CGFloat
if usesNotchIsland {
barHeight = screen.map { Self.notchChromeHeight(for: $0) } ?? notchChromeHeightForCurrentScreen
} else {
barHeight = state.isHoveringBar ? Self.expandedBarSize.height : Self.minBarSize.height
}
return NSSize(
width: Self.notificationWidth,
height: barHeight + Self.notificationSpacing + Self.notificationHeight
)
}
/// Shared closed-conversation size: a mounted notification card wins over
/// the listening/thinking island so Interject PTT cannot crush the card.
private func collapsedChromeSurfaceSize(usesNotchIsland: Bool, screen: NSScreen? = nil) -> NSSize {
let notificationSize = notificationSurfaceSize(usesNotchIsland: usesNotchIsland, screen: screen)
let listeningSize: NSSize
if usesNotchIsland {
listeningSize =
screen.map {
notchSize(
sideWidth: usesVoiceNotchControl ? Self.notchVoiceSideWidth : Self.notchActiveSideWidth,
for: $0
)
}
?? notchSize(active: true)
} else {
listeningSize = Self.voiceBarSize
}
let thinkingSize: NSSize
if usesNotchIsland {
thinkingSize =
screen.map { notchSize(sideWidth: Self.notchThinkingSideWidth, for: $0) }
?? notchSize(sideWidth: Self.notchThinkingSideWidth)
} else {
thinkingSize = Self.minBarSize
}
let idleSize: NSSize
if usesNotchIsland {
idleSize = screen.map { notchIdleOrHoverSurfaceSize(for: $0) } ?? notchIdleOrHoverSurfaceSize()
} else {
idleSize = Self.minBarSize
}
return FloatingControlBarGeometry.collapsedSurfaceSize(
hasMountedNotification: state.currentNotification != nil,
isVoiceListening: state.isVoiceListening,
isThinking: state.isThinking || state.isVoiceResponseWaiting,
notificationSize: notificationSize,
listeningSize: listeningSize,
thinkingSize: thinkingSize,
idleSize: idleSize
)
}
/// The whole closed-conversation surface: the notification card, the PTT
/// status banner, and the idle/listening/thinking island *composed*, never
/// substituted for one another. The banner stacks under the chrome and above
/// the card, so a card that is up while a "too short" hint fires needs both