oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

1#if os(macOS)
2 import AppKit
3 import Combine
4 import OSLog
5 import SwiftUI
6
7 /// The mini window's decisions, for a "sometimes" (2026-10-05, Paul:
8 /// "Sometimes I can't click the mini window"): every press, what was
9 /// under it, what it was taken as, and whether bringing the call forward
10 /// worked. `log show --predicate 'subsystem == "net.amadan.oficina.calls"
11 /// && category == "mini"' --info`.
12 enum MiniLog {
13 static let logger = Logger(subsystem: "net.amadan.oficina.calls", category: "mini")
14 }
15
16 extension View {
17 /// Puts the call into a small floating window while the person is in
18 /// another app, and back into this view when they return. Apply it to
19 /// the root of the call window: that window is the one it hides.
20 public func miniWindow(for model: CallsModel) -> some View {
21 modifier(MiniWindowModifier(model: model))
22 }
23 }
24
25 private struct MiniWindowModifier: ViewModifier {
26 @ObservedObject var model: CallsModel
27 @StateObject private var controller = MiniWindowController()
28
29 func body(content: Content) -> some View {
30 content.background(
31 WindowReader { window in controller.attach(model: model, mainWindow: window) })
32 }
33 }
34
35 extension NSScreen {
36 /// The key a mini window position is remembered under on this
37 /// display: its CGDirectDisplayID, which stays the same across
38 /// launches and rearrangements for the same monitor.
39 var callsDisplayKey: String {
40 (deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)
41 .map { "\($0.uint32Value)" } ?? "main"
42 }
43 }
44
45 /// Watches the app come and go, asks MiniWindowPolicy what that means,
46 /// and moves the windows it says to. It holds no rules of its own:
47 /// where the window goes is MiniWindowCallMemory's, and how big it is
48 /// MiniWindowRules'.
49 @MainActor final class MiniWindowController: ObservableObject {
50 private(set) var policy = MiniWindowPolicy()
51 private let preferences: MiniWindowPreferences
52 /// Collapsed or not, and ⌥-dropped positions: this call's alone.
53 var memory = MiniWindowCallMemory()
54 private weak var model: CallsModel?
55 private weak var mainWindow: NSWindow?
56 private var observers: [NSObjectProtocol] = []
57 private var joining: AnyCancellable?
58 private(set) var panel: MiniWindowPanel?
59
60 init(preferences: MiniWindowPreferences = MiniWindowPreferences()) {
61 self.preferences = preferences
62 let center = NotificationCenter.default
63 let events: [(Notification.Name, @MainActor (MiniWindowController) -> Void)] = [
64 (NSApplication.didResignActiveNotification, { $0.resignedActive() }),
65 (NSApplication.didBecomeActiveNotification, { $0.apply($0.policy.becameActive()) }),
66 (NSApplication.willHideNotification, { $0.apply($0.policy.willHide()) }),
67 (NSApplication.didUnhideNotification, { $0.policy.didUnhide() }),
68 // A display unplugged, rearranged or changed resolution.
69 (NSApplication.didChangeScreenParametersNotification, { $0.relayout() }),
70 ]
71 observers = events.map { name, handle in
72 center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
73 MainActor.assumeIsolated {
74 guard let self else { return }
75 handle(self)
76 }
77 }
78 }
79 // Another app coming forward can bring its own floating windows
80 // over this one, and a Space change or a full-screen app can leave
81 // it behind: put it back in front, taking clicks, each time.
82 let workspace = NSWorkspace.shared.notificationCenter
83 for name in [
84 NSWorkspace.activeSpaceDidChangeNotification, NSWorkspace.didActivateApplicationNotification,
85 ] {
86 observers.append(
87 workspace.addObserver(forName: name, object: nil, queue: .main) { [weak self] note in
88 MainActor.assumeIsolated { self?.panel?.reassert(because: note.name.rawValue) }
89 })
90 }
91 }
92
93 deinit {
94 for observer in observers {
95 NotificationCenter.default.removeObserver(observer)
96 NSWorkspace.shared.notificationCenter.removeObserver(observer)
97 }
98 }
99
100 func attach(model: CallsModel, mainWindow: NSWindow?) {
101 if let mainWindow { self.mainWindow = mainWindow }
102 guard self.model !== model else { return }
103 self.model = model
104 joining = model.$joining.removeDuplicates().sink { [weak self] joining in
105 guard let self else { return }
106 // A call starting or ending is a new call as far as the
107 // mini window's memory goes.
108 self.memory = MiniWindowCallMemory()
109 if !joining { self.apply(self.policy.callEnded()) }
110 }
111 }
112
113 private func resignedActive() {
114 // One turn of the run loop first: a ⌘H or a quick switch straight
115 // back should not flash a window up and down again.
116 DispatchQueue.main.async { [weak self] in
117 guard let self, !NSApp.isActive, !NSApp.isHidden else { return }
118 let window = self.mainWindow
119 self.apply(
120 self.policy.resignedActive(
121 .init(
122 enabled: self.preferences.enabled,
123 inCall: self.model?.joining ?? false,
124 mainWindowVisible: window?.isVisible ?? false,
125 mainWindowMiniaturized: window?.isMiniaturized ?? false,
126 mainWindowFullScreen: window?.styleMask.contains(.fullScreen) ?? false)))
127 }
128 }
129
130 func apply(_ action: MiniWindowPolicy.Action) {
131 switch action {
132 case .none: break
133 case .show(let hideMain):
134 guard let model else { return }
135 // Never two: a panel left behind by a show without a restore would
136 // sit over the new one, its clicks going to a window nobody sees.
137 if let stale = panel {
138 MiniLog.logger.info("show: dismissing a panel still up")
139 stale.dismiss()
140 }
141 let panel = MiniWindowPanel(
142 call: model.call,
143 actions: MiniWindowActions(
144 leave: { [weak model] in model?.leave() },
145 open: { [weak self] in self?.bringCallForward() },
146 moved: { [weak self] option in self?.dropped(option: option) },
147 resized: { [weak self] in self?.resized() },
148 collapse: { [weak self] in self?.collapse() },
149 expand: { [weak self] in self?.expand(pulled: false) },
150 tabReleased: { [weak self] in self?.tabReleased() }))
151 self.panel = panel
152 layout(panel, on: mainWindow?.screen ?? NSScreen.main)
153 panel.reassert(because: "show")
154 if hideMain, let mainWindow { Self.conceal(mainWindow, true) }
155 case .restore(let activate):
156 panel?.dismiss()
157 panel = nil
158 guard let mainWindow else { return }
159 Self.conceal(mainWindow, false)
160 // Forward unless the person came back by clicking another of this
161 // app's windows, such as chat in its own window: that one keeps focus.
162 if activate, NSApp.keyWindow == nil || NSApp.keyWindow === mainWindow {
163 mainWindow.makeKeyAndOrderFront(nil)
164 }
165 }
166 }
167
168 /// A click on the mini window: the call, forward. Since macOS 14 an
169 /// app's request to activate itself is a request the system may turn
170 /// down, and a click in a non-activating panel does not activate the
171 /// app by itself, so a refusal left the person clicking a window that
172 /// did nothing. Asked for twice, the second time as the running
173 /// application, and if the app is still not active the call window is
174 /// put back and brought in front anyway, so a click always shows the
175 /// call. Every step is logged.
176 func bringCallForward() {
177 MiniLog.logger.info(
178 "open: activating (active=\(NSApp.isActive), frontmost=\(NSWorkspace.shared.frontmostApplication?.bundleIdentifier ?? "none", privacy: .public))"
179 )
180 if #available(macOS 14, *) { NSApp.activate() } else { NSApp.activate(ignoringOtherApps: true) }
181 DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
182 guard let self, self.panel != nil else { return }
183 if NSApp.isActive { return }
184 MiniLog.logger.info("open: not active after 0.25 s; asking again as the running application")
185 NSRunningApplication.current.activate(options: [.activateAllWindows])
186 DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
187 guard let self, self.panel != nil else { return }
188 if NSApp.isActive { return }
189 MiniLog.logger.error("open: activation refused twice; showing the call window in front regardless")
190 self.apply(self.policy.becameActive())
191 self.mainWindow?.orderFrontRegardless()
192 }
193 }
194 }
195
196 /// Hides the call window by making it transparent and letting clicks
197 /// through, not by ordering it out. SwiftUI treats an ordered-out
198 /// `Window` as closed: the view's onDisappear runs, which leaves the
199 /// call, and the app then quits for want of a window. Transparent, the
200 /// window keeps its frame, its Space, its place in the stacking order
201 /// and all of its state, so putting it back is exactly as it was.
202 private static func conceal(_ window: NSWindow, _ hidden: Bool) {
203 window.alphaValue = hidden ? 0 : 1
204 window.ignoresMouseEvents = hidden
205 }
206
207 /// Puts the window where this call's memory and the preferences say,
208 /// at the remembered size, on `screen` — as a tab if it was collapsed.
209 private func layout(_ panel: MiniWindowPanel, on screen: NSScreen?) {
210 guard let screen else { return }
211 let visible = screen.visibleFrame
212 let size = MiniWindowRules.size(width: preferences.width, in: visible)
213 let frame = memory.frame(
214 size: size, in: visible, display: screen.callsDisplayKey, preferences: preferences)
215 if memory.collapsed {
216 panel.collapse(to: MiniWindowTab.dock(frame, in: visible).1, expanded: frame)
217 } else {
218 panel.expand(to: frame, animated: false)
219 }
220 }
221
222 /// The displays changed under a window that is up: put it back where
223 /// its placement says on whichever screen it is now on, clamped.
224 private func relayout() {
225 guard let panel else { return }
226 layout(panel, on: panel.screen ?? NSScreen.main)
227 }
228
229 private var screen: NSScreen? { panel?.screen ?? NSScreen.main }
230
231 /// A drag of the window ended. Where it settles is the call memory's
232 /// decision: a corner, where it was dropped, or where it was dropped
233 /// for this call only when ⌥ was held.
234 private func dropped(option: Bool) {
235 guard let panel, let screen else { return }
236 let frame = memory.dropped(
237 panel.frame, in: screen.visibleFrame, display: screen.callsDisplayKey, option: option,
238 preferences: preferences)
239 settle(panel, at: frame, in: screen.visibleFrame)
240 }
241
242 private func resized() {
243 guard let panel, !panel.collapsed, let screen else { return }
244 preferences.width = panel.frame.width
245 let frame = memory.resized(
246 panel.frame, in: screen.visibleFrame, display: screen.callsDisplayKey,
247 preferences: preferences)
248 settle(panel, at: frame, in: screen.visibleFrame)
249 }
250
251 /// Slides the window to where it settles, over 0.2 s (none with
252 /// Reduce Motion), and when a corner took it, a tick on a Force Touch
253 /// trackpad: the feel of a magnet catching.
254 private func settle(_ panel: MiniWindowPanel, at frame: CGRect, in visible: CGRect) {
255 let moved = frame != panel.frame
256 if moved, MiniWindowCorner.allCases.contains(where: { $0.frame(size: frame.size, in: visible) == frame }) {
257 NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now)
258 }
259 panel.expand(to: frame, animated: moved)
260 }
261
262 private func collapse() {
263 guard let panel, let screen else { return }
264 memory.collapsed = true
265 panel.collapse(
266 to: MiniWindowTab.dock(panel.frame, in: screen.visibleFrame).1, expanded: panel.frame)
267 }
268
269 /// Back out of the tab: clicked, to where it was; pulled out, to where
270 /// it was let go, settling as any other drag does.
271 private func expand(pulled: Bool) {
272 guard let panel, let screen else { return }
273 memory.collapsed = false
274 let visible = screen.visibleFrame
275 let size = MiniWindowRules.size(width: panel.expandedFrame.width, in: visible)
276 guard pulled else {
277 panel.expand(
278 to: MiniWindowRules.clamp(
279 CGRect(origin: panel.expandedFrame.origin, size: size), into: visible),
280 animated: false)
281 return
282 }
283 let out = MiniWindowTab.expanded(from: panel.frame, size: size, in: visible)
284 let frame = memory.dropped(
285 out, in: visible, display: screen.callsDisplayKey,
286 option: NSEvent.modifierFlags.contains(.option), preferences: preferences)
287 panel.expand(to: frame, animated: false)
288 }
289
290 private func tabReleased() {
291 guard let panel, let screen else { return }
292 switch MiniWindowTab.release(panel.frame, in: screen.visibleFrame) {
293 case .dock(_, let frame): panel.move(to: frame, animated: true)
294 case .expand: expand(pulled: true)
295 }
296 }
297 }
298
299 /// What the window's controls and surface ask the controller to do.
300 struct MiniWindowActions {
301 var leave: () -> Void = {}
302 var open: () -> Void = {}
303 /// A drag of the expanded window ended; whether ⌥ was held.
304 var moved: (_ option: Bool) -> Void = { _ in }
305 var resized: () -> Void = {}
306 var collapse: () -> Void = {}
307 /// The tab was clicked.
308 var expand: () -> Void = {}
309 /// A drag of the tab ended.
310 var tabReleased: () -> Void = {}
311 }
312
313 /// The floating window, expanded or collapsed to a tab. Non-activating,
314 /// so clicking its controls does not drag the whole app forward;
315 /// clicking anywhere else does, on purpose, because that is how you get
316 /// back to the call. The tab is the same window at a different size, so
317 /// it floats, follows Spaces and stays out of screen captures by the
318 /// very same settings.
319 final class MiniWindowPanel: NSPanel {
320 let content: MiniWindowContent
321 /// Where the expanded window was, while it is a tab.
322 private(set) var expandedFrame: CGRect
323 var collapsed: Bool { content.collapsed }
324
325 init(call: Call, actions: MiniWindowActions) {
326 content = MiniWindowContent(call: call)
327 expandedFrame = CGRect(origin: .zero, size: MiniWindowRules.size)
328 super.init(
329 contentRect: NSRect(origin: .zero, size: MiniWindowRules.size),
330 styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
331 isReleasedWhenClosed = false
332 isFloatingPanel = true
333 level = .floating
334 hidesOnDeactivate = false
335 // Key only when something in it needs the keyboard (VoiceOver, or
336 // Full Keyboard Access). Clicking Mute must not take the keyboard
337 // from the app the person is typing in.
338 becomesKeyOnlyIfNeeded = true
339 // Every Space, and over a full-screen app, because the whole point
340 // is that it follows the person to wherever they went.
341 collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle]
342 // Never in anyone's screen capture, including this app's own shared
343 // screen: nobody in the call needs to see themselves in a corner.
344 sharingType = .none
345 backgroundColor = .clear
346 isOpaque = false
347 hasShadow = true
348 title = "Calls mini window"
349 let hosting = MiniWindowHostingView(
350 rootView: MiniCallView(content: content, actions: actions))
351 // The window's size is the controller's to set; SwiftUI's idea of
352 // an ideal size must not pin it.
353 hosting.sizingOptions = []
354 hosting.hover = content
355 contentView = hosting
356 }
357
358 /// Borderless windows cannot be key by default, which would leave the
359 /// window's controls out of reach of the keyboard altogether.
360 override var canBecomeKey: Bool { true }
361
362 /// In front, at its level, visible and taking the mouse: what a click
363 /// on it needs, put back whenever something may have changed it.
364 func reassert(because reason: String) {
365 if ignoresMouseEvents || alphaValue < 1 || level != .floating {
366 MiniLog.logger.info(
367 "reassert (\(reason, privacy: .public)): mouse ignored=\(self.ignoresMouseEvents), alpha=\(self.alphaValue), level=\(self.level.rawValue)"
368 )
369 }
370 ignoresMouseEvents = false
371 alphaValue = 1
372 level = .floating
373 orderFrontRegardless()
374 (contentView as? MiniWindowHostingView)?.syncHover()
375 }
376
377 /// Every press, logged with what it landed on, before AppKit sends it
378 /// there.
379 override func sendEvent(_ event: NSEvent) {
380 if event.type == .leftMouseDown, let content = contentView {
381 let hit = content.hitTest(content.convert(event.locationInWindow, from: nil))
382 MiniLog.logger.info(
383 "mouse down at \(Int(event.locationInWindow.x)),\(Int(event.locationInWindow.y)) in \(Int(self.frame.width))x\(Int(self.frame.height)) (\(self.collapsed ? "tab" : "window", privacy: .public)) on \(hit.map { String(describing: type(of: $0)) } ?? "nothing", privacy: .public); app active=\(NSApp.isActive), key=\(self.isKeyWindow), clicks=\(event.clickCount)"
384 )
385 }
386 super.sendEvent(event)
387 }
388
389 func expand(to frame: CGRect, animated: Bool) {
390 content.collapsed = false
391 expandedFrame = frame
392 move(to: frame, animated: animated)
393 }
394
395 func collapse(to tab: CGRect, expanded: CGRect) {
396 expandedFrame = expanded
397 content.hovering = false
398 content.collapsed = true
399 move(to: tab, animated: false)
400 }
401
402 func move(to frame: CGRect, animated: Bool) {
403 if animated, !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
404 NSAnimationContext.runAnimationGroup { context in
405 context.duration = 0.2
406 animator().setFrame(frame, display: true)
407 }
408 } else {
409 setFrame(frame, display: true)
410 }
411 }
412
413 /// Takes the video out before the window goes, so every renderer this
414 /// window added to a track is removed from it now and not whenever the
415 /// hosting view happens to be released. The call window's own
416 /// renderers are separate objects and are untouched.
417 func dismiss() {
418 content.call = nil
419 contentView?.layoutSubtreeIfNeeded()
420 contentView?.displayIfNeeded()
421 orderOut(nil)
422 contentView = nil
423 close()
424 }
425 }
426
427 @MainActor final class MiniWindowContent: ObservableObject {
428 @Published var call: Call?
429 @Published var hovering = false
430 @Published var collapsed = false
431 init(call: Call) { self.call = call }
432 }
433
434 /// Takes the first click even though the app is not active — otherwise
435 /// the first click on Mute would only wake the window — and tracks the
436 /// pointer the same way, since SwiftUI's hover follows the key window.
437 private final class MiniWindowHostingView: NSHostingView<MiniCallView> {
438 weak var hover: MiniWindowContent?
439 private var tracking: NSTrackingArea?
440
441 override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
442
443 override func updateTrackingAreas() {
444 super.updateTrackingAreas()
445 if let tracking { removeTrackingArea(tracking) }
446 let area = NSTrackingArea(
447 rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect],
448 owner: self)
449 addTrackingArea(area)
450 tracking = area
451 }
452
453 /// A window that appears under the pointer, or moves under it, gets no
454 /// mouseEntered, and its controls would stay hidden until the pointer
455 /// left and came back: hover follows where the pointer is instead.
456 func syncHover() {
457 guard let window else { return }
458 let inside = window.frame.contains(NSEvent.mouseLocation)
459 if hover?.hovering != inside { hover?.hovering = inside }
460 }
461
462 override func mouseMoved(with event: NSEvent) {
463 super.mouseMoved(with: event)
464 if hover?.hovering == false { hover?.hovering = true }
465 }
466
467 override func mouseEntered(with event: NSEvent) {
468 super.mouseEntered(with: event)
469 hover?.hovering = true
470 }
471
472 override func mouseExited(with event: NSEvent) {
473 super.mouseExited(with: event)
474 hover?.hovering = false
475 }
476 }
477
478 struct MiniCallView: View {
479 @ObservedObject var content: MiniWindowContent
480 let actions: MiniWindowActions
481 @Environment(\.accessibilityReduceMotion) private var reduceMotion
482
483 var body: some View {
484 Group {
485 if content.collapsed, let call = content.call {
486 MiniTabView(call: call, actions: actions)
487 } else {
488 ZStack {
489 if let call = content.call {
490 MiniCallStage(
491 call: call, arrangement: call.arrangement, speakerNow: call.levels.speaker,
492 showingControls: showingControls, actions: actions)
493 CallToast(call: call).padding(8)
494 .frame(maxHeight: .infinity, alignment: .top)
495 } else {
496 Color.black
497 }
498 }
499 .frame(maxWidth: .infinity, maxHeight: .infinity)
500 .background(
501 MiniWindowSurface(
502 mode: .window, click: { _ in actions.open() }, dropped: actions.moved,
503 resized: actions.resized)
504 )
505 .clipShape(RoundedRectangle(cornerRadius: 16))
506 }
507 }
508 .animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: showingControls)
509 .tint(CallsAppearance.accent)
510 }
511
512 /// VoiceOver users get the controls all the time: hover is not a thing
513 /// a screen reader does.
514 private var showingControls: Bool {
515 content.hovering || NSWorkspace.shared.isVoiceOverEnabled
516 }
517 }
518
519 private struct MiniCallStage: View {
520 @ObservedObject var call: Call
521 @ObservedObject var arrangement: CallArrangement
522 @ObservedObject var speakerNow: SpeakerNow
523 let showingControls: Bool
524 let actions: MiniWindowActions
525 @Environment(\.fixtureFeeds) private var fixtureFeeds
526
527 /// What Speaker view's stage shows (0.4.0): what the person pinned,
528 /// or else the newest shared screen, since a person who shares is
529 /// asking to be looked at, or else whoever is speaking, or before
530 /// anyone has, the first person in the viewer's order. Nobody else
531 /// there: your own camera, since a window of nothing reads as a
532 /// broken one. The same whichever layout the call window is in.
533 private var subject: StageItem? {
534 let item = arrangement.stage(active: speakerNow.peer, screens: call.screens)
535 if case .camera(let peer) = item, peer == arrangement.me { return nil }
536 return item
537 }
538
539 /// The people still connecting who are not the one on show.
540 private var offStage: [String] {
541 var shown: String?
542 if case .camera(let peer) = subject { shown = peer }
543 return call.connectingPeers.filter { $0 != shown }.sorted()
544 }
545
546 var body: some View {
547 ZStack {
548 Group {
549 switch subject {
550 case .screen(let peer):
551 MacVideoTile(
552 track: call.remoteScreens[peer], label: screenCaption(call.name(of: peer)),
553 screen: true)
554 case .camera(let peer):
555 // On the stage: fitted with its backdrop when its shape and
556 // the window's differ, as on the call window's stage.
557 MacVideoTile(
558 track: call.remoteTracks[peer], label: call.name(of: peer),
559 muted: call.isMuted(peer), cameraOff: call.isCameraOff(peer),
560 lowBandwidth: call.isLowBandwidth(peer),
561 videoPaused: call.isVideoPaused(peer) ? call.videoPausedWords(peer) : nil,
562 audio: call.tileAudio(peer), fixtureVideo: fixtureFeeds[peer])
563 case nil:
564 MacVideoTile(
565 track: call.localTrack, label: "You", mirrored: true, cameraOff: call.cameraOff,
566 placeholder: call.selfPlaceholder, audio: call.selfAudio)
567 }
568 }
569 // The tile is a picture, not a target: clicks and drags go through
570 // to the surface underneath.
571 .allowsHitTesting(false)
572 VStack {
573 HStack(spacing: 8) {
574 // With the controls up, the Mute button says it; at the
575 // smallest width there is no room for both.
576 if call.muted, !showingControls {
577 Label("Muted", systemImage: "mic.slash.fill").labelStyle(.iconOnly)
578 .font(.callout.bold()).foregroundStyle(.white)
579 .padding(8).callOverlaySurface(Circle())
580 .accessibilityLabel("Your microphone is muted")
581 // A mark, not a control: a press on it is a press on the
582 // window (MiniWindowGesture), not swallowed by SwiftUI.
583 .allowsHitTesting(false)
584 }
585 Spacer()
586 // Spec §15.24, for the people this window is not showing: the
587 // one it shows says it on its own tile. Top right, clear of
588 // the tile's Muted badge.
589 ConnectingDot(names: offStage.map { call.name(of: $0) })
590 // Its names are in VoiceOver's label; a press goes through.
591 .allowsHitTesting(false)
592 if showingControls {
593 Button("Collapse to a tab", glyph: "arrow.down.right.and.arrow.up.left") {
594 actions.collapse()
595 }
596 .buttonStyle(CallActionStyle(color: Color(white: 0.3), emphasized: true))
597 .help("Collapse to a tab at the edge of the screen")
598 Button(
599 call.muted ? "Unmute microphone" : "Mute microphone",
600 glyph: call.muted ? "mic.slash.fill" : "mic.fill"
601 ) { call.mute() }
602 .buttonStyle(
603 CallActionStyle(
604 color: call.muted
605 ? Color(red: 0.65, green: 0.30, blue: 0.02) : CallsAppearance.accent,
606 emphasized: true)
607 )
608 .help(call.muted ? "Unmute microphone" : "Mute microphone")
609 Button(
610 "Leave meeting", glyph: "phone.down.fill", role: .destructive,
611 action: actions.leave
612 )
613 .buttonStyle(CallActionStyle(color: .red, emphasized: true))
614 .help("Leave meeting")
615 }
616 }
617 Spacer()
618 }.padding(10)
619 }
620 }
621 }
622
623 /// The mini window collapsed: whether your microphone is on, and who
624 /// the call is with. Click it to open the mini window again, drag it out
625 /// to open it there, double-click it for the whole call.
626 ///
627 /// A small waveform shows while someone else is speaking, with the
628 /// speaking glow behind it following the loudest of them, from the
629 /// receive meters (spec §15.20), which read five times a second — quick
630 /// enough to follow speech, where the five-second audio readout was not.
631 struct MiniTabView: View {
632 @ObservedObject var call: Call
633 let actions: MiniWindowActions
634
635 private var others: [String] {
636 let me = call.state?.peer
637 return (call.state?.peers ?? []).filter { $0.peer != me }.map(\.name)
638 }
639 private var caption: String { MiniWindowTab.caption(others: others) }
640
641 var body: some View {
642 HStack(spacing: 8) {
643 Image(systemName: call.muted ? "mic.slash.fill" : "mic.fill")
644 .font(.callout.bold())
645 .foregroundStyle(.white)
646 .frame(width: 26, height: 26)
647 .background(
648 call.muted ? Color(red: 0.65, green: 0.30, blue: 0.02) : CallsAppearance.accent,
649 in: Circle())
650 // Spec §15.24: someone is still connecting and cannot hear you
651 // yet. A dot only — the tab has no room for words; its
652 // accessibility label and the window, opened, say who.
653 .overlay(alignment: .topTrailing) {
654 if !call.connectingPeers.isEmpty {
655 Circle().fill(ConnectingDot.colour).frame(width: 8, height: 8)
656 .overlay(Circle().strokeBorder(Color.black.opacity(0.35), lineWidth: 1))
657 .offset(x: 2, y: -2)
658 .help(call.connectingPeers.sorted().map { ConnectingWords.connecting(call.name(of: $0)) }.joined(separator: "\n"))
659 }
660 }
661 Text(caption).font(.callout.weight(.medium)).lineLimit(1).truncationMode(.tail)
662 .foregroundStyle(.white)
663 Spacer(minLength: 0)
664 SpeakingGlyph(speaking: call.levels.anyoneSpeaking, glow: call.levels.othersGlow)
665 }
666 // Nothing in the tab is a control of its own: every press on it,
667 // on the microphone, the names or the waveform included, is the
668 // surface's, so a click always opens and a drag always moves. Until
669 // 2026-10-05 a press on the names or a mark went to SwiftUI, which
670 // had nothing to do with it, and was lost (CallsInterop
671 // --mini-clicks).
672 .allowsHitTesting(false)
673 .padding(.horizontal, 7)
674 .frame(width: MiniWindowTab.size.width, height: MiniWindowTab.size.height)
675 .background(
676 MiniWindowSurface(
677 mode: .tab,
678 click: { count in count >= 2 ? actions.open() : actions.expand() },
679 dropped: { _ in actions.tabReleased() }, resized: {})
680 )
681 // The call's glass, borderless, as over the picture.
682 .callOverlaySurface(Capsule())
683 .clipShape(Capsule())
684 .accessibilityElement(children: .ignore)
685 .accessibilityAddTraits(.isButton)
686 .accessibilityLabel(
687 (["Calls, \(caption)"] + call.connectingPeers.sorted().map { ConnectingWords.connecting(call.name(of: $0)) })
688 .joined(separator: ". "))
689 .accessibilityValue(call.muted ? "Microphone muted" : "Microphone on")
690 .accessibilityHint("Shows the mini window.")
691 .accessibilityAction { actions.expand() }
692 .accessibilityAction(named: "Return to the call window") { actions.open() }
693 .accessibilityAction(named: call.muted ? "Unmute microphone" : "Mute microphone") {
694 call.mute()
695 }
696 .accessibilityAction(named: "Leave meeting") { actions.leave() }
697 }
698 }
699
700 /// The mini window's whole say on spec §15.24: a small ear on the glass
701 /// while someone it is not showing is connecting and cannot hear you yet,
702 /// with their names in its tooltip and for VoiceOver. Nothing at all
703 /// otherwise.
704 struct ConnectingDot: View {
705 /// A warm amber, light enough to tell from the muted microphone's
706 /// brown on the tab.
707 static let colour = Color(red: 1, green: 0.78, blue: 0.42)
708 let names: [String]
709 var body: some View {
710 if !names.isEmpty {
711 let words = names.map(ConnectingWords.connecting).joined(separator: "\n")
712 Image(systemName: "ear")
713 .font(.callout.bold()).foregroundStyle(.white)
714 .frame(width: 32, height: 32)
715 .callOverlaySurface(Circle(), rim: false)
716 .overlay(alignment: .topTrailing) {
717 Circle().fill(Self.colour).frame(width: 7, height: 7)
718 }
719 .help(words)
720 .accessibilityElement(children: .ignore)
721 .accessibilityLabel(words)
722 .accessibilityIdentifier("connectingDot")
723 }
724 }
725 }
726
727 /// The window's background: a click, a drag that moves the window, and
728 /// — for the expanded window — a drag from an edge or corner that
729 /// resizes it. Handled here rather than with isMovableByWindowBackground
730 /// so the three can be told apart.
731 private struct MiniWindowSurface: NSViewRepresentable {
732 enum Mode { case window, tab }
733 let mode: Mode
734 /// A click, with its click count.
735 let click: (Int) -> Void
736 /// A move ended; whether ⌥ was held when it did.
737 let dropped: (Bool) -> Void
738 let resized: () -> Void
739
740 func makeNSView(context: Context) -> SurfaceView { SurfaceView() }
741 func updateNSView(_ view: SurfaceView, context: Context) {
742 view.mode = mode
743 view.click = click
744 view.dropped = dropped
745 view.resized = resized
746 }
747
748 final class SurfaceView: NSView {
749 var mode = Mode.window
750 var click: (Int) -> Void = { _ in }
751 var dropped: (Bool) -> Void = { _ in }
752 var resized: () -> Void = {}
753 private var tracking: NSTrackingArea?
754
755 override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
756 // The tab is described by its SwiftUI view, which has the actions.
757 override func isAccessibilityElement() -> Bool { mode == .window }
758 override func accessibilityRole() -> NSAccessibility.Role? { .button }
759 override func accessibilityLabel() -> String? { "Return to the call window" }
760 override func accessibilityPerformPress() -> Bool {
761 click(1)
762 return true
763 }
764
765 private func handle(at point: NSPoint) -> MiniWindowResize.Handle {
766 guard mode == .window else { return [] }
767 return MiniWindowResize.handle(at: point, in: bounds.size)
768 }
769
770 // The resize cursor at the edges, whether or not Calls is the
771 // active app — it usually is not, while this window is up.
772 override func updateTrackingAreas() {
773 super.updateTrackingAreas()
774 if let tracking { removeTrackingArea(tracking) }
775 let area = NSTrackingArea(
776 rect: .zero, options: [.mouseMoved, .mouseEnteredAndExited, .activeAlways, .inVisibleRect],
777 owner: self)
778 addTrackingArea(area)
779 tracking = area
780 }
781
782 override func mouseMoved(with event: NSEvent) {
783 Self.cursor(for: handle(at: convert(event.locationInWindow, from: nil))).set()
784 }
785
786 override func mouseExited(with event: NSEvent) { NSCursor.arrow.set() }
787
788 private static func cursor(for handle: MiniWindowResize.Handle) -> NSCursor {
789 let horizontal = !handle.isDisjoint(with: [.left, .right])
790 let vertical = !handle.isDisjoint(with: [.top, .bottom])
791 if #available(macOS 15, *) {
792 let position: NSCursor.FrameResizePosition? =
793 switch (handle.contains(.top), handle.contains(.bottom), handle.contains(.left), handle.contains(.right)) {
794 case (true, _, true, _): .topLeft
795 case (true, _, _, true): .topRight
796 case (_, true, true, _): .bottomLeft
797 case (_, true, _, true): .bottomRight
798 case (true, _, _, _): .top
799 case (_, true, _, _): .bottom
800 case (_, _, true, _): .left
801 case (_, _, _, true): .right
802 default: nil
803 }
804 if let position { return .frameResize(position: position, directions: .all) }
805 return .arrow
806 }
807 switch (horizontal, vertical) {
808 case (true, false): return .resizeLeftRight
809 case (false, true): return .resizeUpDown
810 case (true, true): return .crosshair
811 default: return .arrow
812 }
813 }
814
815 override func mouseDown(with event: NSEvent) {
816 guard let window else { return }
817 let surface: MiniWindowGesture.Surface = mode == .window ? .window : .tab
818 let start = window.convertPoint(toScreen: event.locationInWindow)
819 let startFrame = window.frame
820 let grabbed = MiniWindowGesture.grab(
821 at: convert(event.locationInWindow, from: nil), in: bounds.size, surface: surface)
822 let visible = window.screen?.visibleFrame ?? startFrame
823 var dragging = false
824 while let next = window.nextEvent(matching: [.leftMouseDragged, .leftMouseUp]) {
825 let now = Self.screenLocation(of: next)
826 let dx = now.x - start.x
827 let dy = now.y - start.y
828 if !dragging, MiniWindowGesture.dragged(dx: dx, dy: dy) { dragging = true }
829 if dragging {
830 if grabbed.isEmpty {
831 window.setFrameOrigin(NSPoint(x: startFrame.minX + dx, y: startFrame.minY + dy))
832 } else {
833 window.setFrame(
834 MiniWindowResize.frame(
835 from: startFrame, dragging: grabbed, dx: dx, dy: dy, in: visible),
836 display: true)
837 }
838 }
839 if next.type == .leftMouseUp { break }
840 }
841 let outcome = MiniWindowGesture.outcome(
842 grabbed: grabbed, dragged: dragging, clickCount: event.clickCount,
843 option: NSEvent.modifierFlags.contains(.option) || event.modifierFlags.contains(.option))
844 MiniLog.logger.info("\(surface.rawValue, privacy: .public) press: \(String(describing: outcome), privacy: .public)")
845 switch outcome {
846 case .click(let count): click(count)
847 case .move(let option): dropped(option)
848 case .resize: resized()
849 }
850 }
851
852 /// Where the pointer is for an event of a drag. The window moves
853 /// under the pointer as it is dragged, so a real event's position in
854 /// the window is stale by the time it is read: the pointer's own
855 /// location is used. An event made with no window (CallsInterop's
856 /// --mini-clicks) carries screen coordinates and is read as it is.
857 static func screenLocation(of event: NSEvent) -> CGPoint {
858 event.windowNumber == 0 && event.window == nil ? event.locationInWindow : NSEvent.mouseLocation
859 }
860 }
861 }
862
863 /// The mini window's two faces, for CallsInterop's offline snapshots.
864 /// The views themselves stay internal; this is the only way in.
865 @MainActor public enum MiniWindowSnapshot {
866 public static func window(call: Call, hovering: Bool) -> some View {
867 let content = MiniWindowContent(call: call)
868 content.hovering = hovering
869 return MiniCallView(content: content, actions: MiniWindowActions())
870 }
871
872 public static func tab(call: Call) -> some View {
873 let content = MiniWindowContent(call: call)
874 content.collapsed = true
875 return MiniCallView(content: content, actions: MiniWindowActions())
876 }
877 }
878
879 /// Finds the NSWindow a SwiftUI view is in, once it is in one.
880 private struct WindowReader: NSViewRepresentable {
881 let found: (NSWindow?) -> Void
882
883 func makeNSView(context: Context) -> ReaderView {
884 let view = ReaderView()
885 view.found = found
886 return view
887 }
888 func updateNSView(_ view: ReaderView, context: Context) {
889 view.found = found
890 if let window = view.window { found(window) }
891 }
892
893 final class ReaderView: NSView {
894 var found: (NSWindow?) -> Void = { _ in }
895 override func viewDidMoveToWindow() {
896 super.viewDidMoveToWindow()
897 if let window { found(window) }
898 }
899 }
900 }
901#endif
902