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 SwiftUI
4
5 /// The controls in the call bar, for keyboard focus: while one has it,
6 /// the bar stays up.
7 enum CallControlID: Hashable {
8 case mute, camera, share, devices, layout, link, chat, leave
9 }
10
11 /// The full-window call: the picture edge to edge, to the very top of
12 /// the window, with the traffic lights, the controls and the panels over
13 /// it, and — for a meeting someone named — its title, centred where the
14 /// window's title would be (CallTitle). There is no title bar: a strip across the top drags
15 /// the window instead. The controls and the traffic lights come with the
16 /// pointer and go 3 s after it stops, or 1.5 s after it leaves the
17 /// window (see ControlsVisibility for what keeps them up). Notices that
18 /// matter stay whatever the controls do.
19 extension MacCallView {
20 /// Room kept clear at the top for the title bar's traffic lights.
21 static let titleBarHeight: CGFloat = 32
22 /// Height of the floating bar with its margin below: what the
23 /// filmstrip and a tile's name move up by while the bar shows. The
24 /// floating self view stays put and the bar makes room for it instead
25 /// (SelfViewBarLayout).
26 static let barReserve: CGFloat = 44 + 20 + 16
27 static let panelWidth: CGFloat = 320
28 static let tileBackdrop = Color(white: 0.13)
29 /// Where the traffic lights sit, from the window's top-left corner:
30 /// the pointer over them holds the controls (and them) up, and the
31 /// title keeps to the right of it.
32 static let windowButtonsArea = CGRect(x: 0, y: 0, width: 80, height: titleBarHeight)
33
34 var immersive: some View {
35 GeometryReader { geometry in
36 let size = geometry.size
37 ZStack {
38 Color.black
39 if let fixtureBackdrop {
40 fixtureBackdrop.view.accessibilityHidden(true).movesWindow()
41 } else {
42 fullWindowStage(in: size).movesWindow()
43 }
44 if !grid, selfFloats { selfView(in: size) }
45 topShade
46 // Above the picture, below the title and everything else: what
47 // is left of the strip once they have their clicks drags.
48 WindowDragStrip()
49 .frame(height: Self.titleBarHeight)
50 .frame(maxHeight: .infinity, alignment: .top)
51 topOverlay
52 panels(in: size)
53 bar(in: size)
54 }
55 .coordinateSpace(name: "call")
56 .frame(width: size.width, height: size.height)
57 }
58 .ignoresSafeArea()
59 .background(
60 CallWindowChrome(
61 title: CallTitle.window(title: call.title),
62 buttonsVisible: chrome.visible,
63 fade: ControlsVisibility.fadeDuration(showing: chrome.visible, reduceMotion: reduceMotion)))
64 .background(
65 CallWindowActivity(
66 moved: { point in
67 chrome.pointerMoved()
68 chrome.set(
69 .pointerOverControls,
70 chrome.visible
71 && (barFrame.contains(point) || Self.windowButtonsArea.contains(point)))
72 },
73 exited: { chrome.pointerExited() },
74 activity: { chrome.activity() },
75 menuTracking: { menuTracking = $0 },
76 sheet: { sheetShowing = $0 })
77 )
78 .animation(fade, value: chrome.visible)
79 .onAppear { updateHolds() }
80 .onChange(of: showingDevices) { updateHolds() }
81 .onChange(of: showingChat) { updateHolds() }
82 .onChange(of: showingLayout) { updateHolds() }
83 .onChange(of: showingMore) { updateHolds() }
84 .onChange(of: menuTracking) { updateHolds() }
85 .onChange(of: sheetShowing) { updateHolds() }
86 .onChange(of: voiceOver) { updateHolds() }
87 .onChange(of: focusedControl) { _, now in
88 chrome.set(.keyboardFocus, now != nil)
89 }
90 .onChange(of: chrome.state.hidesPointer) { _, hide in
91 // Hidden until it moves, which is also what brings the controls
92 // back: AppKit shows it again on the first movement by itself.
93 if hide, chrome.pinned == nil { NSCursor.setHiddenUntilMouseMoves(true) }
94 }
95 }
96
97 private var fade: Animation {
98 ControlsVisibility.fade(showing: chrome.visible, reduceMotion: reduceMotion)
99 }
100
101 /// A shade down from the top edge while the controls show, so the
102 /// traffic lights and the title read over a bright picture.
103 private var topShade: some View {
104 // Dark enough through the title bar's strip for a named meeting's
105 // title, white, over a white picture (4.5:1), then fading.
106 LinearGradient(
107 stops: [
108 .init(color: .black.opacity(0.72), location: 0),
109 .init(color: .black.opacity(0.62), location: Self.titleBarHeight / 112),
110 .init(color: .black.opacity(0), location: 1),
111 ], startPoint: .top, endPoint: .bottom
112 )
113 .frame(height: 112)
114 .frame(maxHeight: .infinity, alignment: .top)
115 .opacity(chrome.visible ? 1 : 0)
116 .allowsHitTesting(false)
117 .accessibilityHidden(true)
118 }
119
120 private func updateHolds() {
121 chrome.set(
122 .menuOpen, showingDevices || showingChat || showingLayout || showingMore || menuTracking)
123 chrome.set(.alert, sheetShowing)
124 chrome.set(.voiceOver, voiceOver)
125 }
126
127 /// How far up a name at the bottom of the stage sits, clear of the bar.
128 private var lift: CGFloat { chrome.visible ? Self.barReserve - 8 : 0 }
129
130 // MARK: Stage
131
132 @ViewBuilder private func fullWindowStage(in size: CGSize) -> some View {
133 Group {
134 if grid {
135 fullWindowGrid(in: size)
136 } else {
137 speakerStage(in: size)
138 }
139 }
140 .coordinateSpace(name: arrangeSpace)
141 .onPreferenceChange(TileFramesKey.self) { tileFrames = $0 }
142 }
143
144 /// Speaker view: the stage fills the whole window, edge to edge, as
145 /// FaceTime's does, and everyone else is a filmstrip floating over its
146 /// bottom, in this viewer's order (2026-10-05: until then the stage
147 /// stopped above the filmstrip, leaving a black band across the
148 /// window behind it and the bar). The filmstrip rises clear of the bar
149 /// while the controls show, as the self view does, and settles to the
150 /// window's edge when they go. The stage's name sits at the window's
151 /// bottom left, just above the filmstrip (`StageLabel`). In a call of
152 /// two there is no filmstrip: the other person fills the window and
153 /// you float in a corner, as since 0.3.4.
154 private func speakerStage(in size: CGSize) -> some View {
155 let strip = selfFloats ? [] : filmstrip
156 let thumb = Self.filmstripTile(in: size)
157 let band = strip.isEmpty ? 0 : thumb.height + 2 * Self.filmstripPadding
158 let stageLift = max(StageLabel.lift(bar: lift, band: band), selfClearance(in: size))
159 return ZStack(alignment: .bottom) {
160 Group {
161 if let focused {
162 macTile(focused, cornerRadius: 0, compact: true, labelLift: stageLift, onStage: true)
163 .overlay(alignment: .bottomTrailing) {
164 if arrangement.pinned == focused {
165 PinBadge(title: itemTitle(focused)) {
166 withAnimation(panelAnimation) { arrangement.pin(nil) }
167 }
168 .padding(8).padding(.bottom, stageLift)
169 }
170 }
171 } else {
172 ContentUnavailableView(
173 "Waiting for others", systemImage: "person.2",
174 description: Text("Your meeting is ready. Others will appear here when they join.")
175 )
176 .foregroundStyle(.white.opacity(0.85))
177 .environment(\.colorScheme, .dark)
178 .frame(maxWidth: .infinity, maxHeight: .infinity)
179 }
180 }
181 .frame(maxWidth: .infinity, maxHeight: .infinity)
182 .animation(fade, value: chrome.visible)
183 if !strip.isEmpty {
184 filmstripView(strip, tile: thumb, width: size.width)
185 .padding(.bottom, chrome.visible ? Self.barReserve - 8 : 0)
186 .animation(fade, value: chrome.visible)
187 }
188 }
189 }
190
191 /// How far the stage's name rises to sit 8 pt above a self view in
192 /// the bottom left, where it would otherwise be under it; 0 anywhere
193 /// else. (The name is 8 pt in from the stage's bottom left.)
194 private func selfClearance(in size: CGSize) -> CGFloat {
195 guard !grid, selfFloats, PiPCorner(rawValue: pipCorner) == .bottomLeading else { return 0 }
196 return size.height - selfBarLayout(in: size).selfView(barShown: chrome.visible).minY
197 }
198
199 /// Room above and below the filmstrip's tiles.
200 static let filmstripPadding: CGFloat = 8
201
202 /// A filmstrip tile's size: a sixth of the window's height, between
203 /// 72 and 120 pt tall, at 16:9. At the smallest window (760 × 540)
204 /// that is 86 pt, and five of them fit across without scrolling.
205 static func filmstripTile(in size: CGSize) -> CGSize {
206 let height = min(120, max(72, (size.height / 6).rounded()))
207 return CGSize(width: (height * 16 / 9).rounded(), height: height)
208 }
209
210 /// The filmstrip: centred while it fits, scrolling sideways once it
211 /// does not.
212 private func filmstripView(_ strip: [StageItem], tile: CGSize, width: CGFloat) -> some View {
213 ScrollView(.horizontal) {
214 HStack(spacing: 8) {
215 ForEach(strip, id: \.self) { item in
216 macTile(item, cornerRadius: 8, compact: true, backdrop: Self.tileBackdrop, iconOnly: true)
217 .frame(width: tile.width, height: tile.height)
218 .modifier(arrangeable(item, tapToPin: true))
219 }
220 }
221 .padding(.horizontal, 12).padding(.vertical, Self.filmstripPadding)
222 .frame(minWidth: width)
223 // The click that brings the window forward pins too, as it does
224 // on the picture; it does not reach through a scroll view unless
225 // the content asks again.
226 .takesActivatingClicks()
227 }
228 .scrollIndicators(.automatic)
229 .accessibilityElement(children: .contain)
230 .accessibilityLabel("Filmstrip")
231 .accessibilityIdentifier("filmstrip")
232 }
233
234 /// Every tile as large as it can be without scrolling, until there are
235 /// so many that they would be too small to see, when it scrolls.
236 @ViewBuilder private func fullWindowGrid(in size: CGSize) -> some View {
237 let items = gridItems
238 let count = items.count
239 let area = CGSize(width: size.width - 8, height: size.height - 8)
240 let columns = GridFit.columns(count: count, in: area, aspect: 16 / 9)
241 let fitted = GridFit.tile(count: count, columns: columns, in: area, aspect: 16 / 9)
242 let tile = fitted.width >= 200 ? fitted : CGSize(width: 200, height: 200 * 9 / 16)
243 let across =
244 fitted.width >= 200
245 ? columns : max(1, Int((area.width + 4) / (tile.width + 4)))
246 let rows = (count + across - 1) / across
247 let gridHeight = CGFloat(rows) * tile.height + CGFloat(max(rows - 1, 0)) * 4
248 // The last row's names clear the bar while it shows: lifted by as
249 // much of the bar as reaches over them (the grid is centred).
250 let below = max(0, (size.height - 8 - gridHeight) / 2) + 4
251 let lastLift = max(0, lift - below)
252 let firstOfLastRow = (rows - 1) * across
253 ScrollView {
254 LazyVGrid(
255 columns: Array(repeating: GridItem(.fixed(tile.width), spacing: 4), count: across),
256 spacing: 4
257 ) {
258 ForEach(Array(items.enumerated()), id: \.element) { index, item in
259 macTile(
260 item, cornerRadius: 6, compact: true,
261 labelLift: index >= firstOfLastRow ? lastLift : 0, backdrop: Self.tileBackdrop
262 )
263 .frame(width: tile.width, height: tile.height)
264 .modifier(arrangeable(item, tapToPin: false))
265 }
266 }
267 .padding(4)
268 .frame(minHeight: size.height)
269 }
270 .scrollIndicators(.never)
271 }
272
273 // MARK: Self view
274
275 /// You, small and floating: dragged anywhere, settling in the nearest
276 /// corner, 16 pt in from the window's edges and staying there whether
277 /// the controls show or not — the bar keeps clear of you
278 /// (SelfViewBarLayout) — and clear of an open chat. Muted shows on it
279 /// whether or not the controls do.
280 private func selfView(in size: CGSize) -> some View {
281 let pip = selfViewSize(in: size)
282 let frame = selfBarLayout(in: size).selfView(barShown: chrome.visible)
283 return MacVideoTile(
284 track: call.localTrack, label: "You", muted: call.muted, mirrored: true,
285 cameraOff: call.cameraOff, placeholder: call.selfPlaceholder, cornerRadius: 10,
286 compact: true, backdrop: Self.tileBackdrop, audio: call.selfAudio,
287 fixtureVideo: fixtureFeeds["me"], shaped: { selfShape = $0 }
288 )
289 .frame(width: pip.width, height: pip.height)
290 .shadow(color: .black.opacity(0.35), radius: 8, y: 3)
291 .background(
292 GeometryReader { tile in
293 Color.clear
294 .onAppear { CallBarProbe.selfView = tile.frame(in: .global) }
295 .onChange(of: tile.frame(in: .global)) { _, now in CallBarProbe.selfView = now }
296 }
297 )
298 .onDisappear { CallBarProbe.selfView = .zero }
299 .position(x: frame.midX + pipDrag.width, y: frame.midY + pipDrag.height)
300 .gesture(
301 DragGesture()
302 .onChanged { pipDrag = $0.translation }
303 .onEnded { drag in
304 let dropped = CGPoint(
305 x: frame.midX + drag.translation.width, y: frame.midY + drag.translation.height)
306 let headed = CGPoint(
307 x: frame.midX + drag.predictedEndTranslation.width,
308 y: frame.midY + drag.predictedEndTranslation.height)
309 withAnimation(reduceMotion ? nil : .spring(duration: 0.3)) {
310 pipCorner = PiPLayout.corner(droppedAt: dropped, predicted: headed, in: size).rawValue
311 pipDrag = .zero
312 }
313 }
314 )
315 .animation(reduceMotion ? nil : .easeOut(duration: 0.2), value: frame)
316 .accessibilityActions {
317 ForEach(PiPCorner.allCases, id: \.self) { place in
318 Button(place.moveTitle) { pipCorner = place.rawValue }
319 }
320 }
321 }
322
323 private func selfViewSize(in size: CGSize) -> CGSize {
324 PiPLayout.size(in: size, touch: false, shape: selfShape ?? fixtureFeeds["me"].map(VideoShape.of))
325 }
326
327 /// The bar and the floating self view, placed together: the bar
328 /// keeps clear of you rather than you of it. The title bar's strip,
329 /// with the traffic lights and any title in it, is the only thing at
330 /// the top, so a self view goes below it; an open chat keeps it to
331 /// the chat's left.
332 func selfBarLayout(in size: CGSize) -> SelfViewBarLayout {
333 SelfViewBarLayout.layout(
334 window: size, selfView: !grid && selfFloats ? selfViewSize(in: size) : nil,
335 corner: PiPCorner(rawValue: pipCorner) ?? .bottomTrailing, top: Self.titleBarHeight,
336 trailing: showingChat ? Self.panelWidth + 12 : 0, controls: barControls)
337 }
338
339 // MARK: Title and notices
340
341 private var notices: [CallNotice] {
342 CallNotices.notices(
343 phase: call.noticePhase, status: call.status, sharingScreen: call.sharingScreen,
344 screenNote: call.screenNote, floor: call.floor, screenRecovery: call.screenRecovery)
345 }
346
347 private var topOverlay: some View {
348 // No pill (2026-10-02, Paul approved): how the call is going is the
349 // notices' to say, and the title — only one someone chose — is
350 // plain text centred in the title bar's strip, level with the
351 // traffic lights, as a window's title is. The strip's dark shade
352 // (topShade) keeps it legible over a bright picture, and it fades
353 // with the controls and the traffic lights.
354 ZStack(alignment: .top) {
355 if let shown = CallTitle.shown(title: call.title, named: call.named) {
356 Text(shown)
357 .font(.system(size: 13, weight: .semibold))
358 .foregroundStyle(.white)
359 .shadow(color: .black.opacity(0.45), radius: 2, y: 1)
360 .lineLimit(1).truncationMode(.tail)
361 // Clear of the traffic lights on the left and the same on the
362 // right, so it stays centred on the window.
363 .padding(.horizontal, Self.windowButtonsArea.maxX + 8)
364 .frame(maxWidth: .infinity)
365 .frame(height: Self.titleBarHeight)
366 .opacity(chrome.visible ? 1 : 0)
367 .allowsHitTesting(false)
368 .accessibilityHidden(!chrome.visible)
369 .accessibilityAddTraits(.isHeader)
370 .accessibilityIdentifier("callTitle")
371 }
372
373 VStack(spacing: 8) {
374 ForEach(notices.filter { $0.important && !dismissedNotices.contains($0.id) }) {
375 notice in
376 noticeView(notice)
377 }
378 ForEach(call.state?.waiting ?? []) { peer in
379 HStack(spacing: 12) {
380 Label("\(peer.name) is waiting", systemImage: "person.badge.clock")
381 Button("Let in") { call.admit(peer.peer) }.buttonStyle(.borderedProminent)
382 }
383 .modifier(NoticeSurface())
384 }
385 // A notice that is not urgent — the relay warning — goes with
386 // the controls; it lived in the pill until the pill went.
387 ForEach(notices.filter { !$0.important }) { notice in
388 noticeView(notice)
389 .opacity(chrome.visible ? 1 : 0)
390 .allowsHitTesting(chrome.visible)
391 .accessibilityHidden(!chrome.visible)
392 }
393 }
394 .padding(.horizontal, 90)
395 .padding(.top, Self.titleBarHeight + 6)
396 }
397 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
398 }
399
400 @ViewBuilder private func noticeView(_ notice: CallNotice) -> some View {
401 HStack(spacing: 12) {
402 switch notice.kind {
403 case .sharing:
404 Label(notice.text, systemImage: "rectangle.on.rectangle")
405 .foregroundStyle(CallOverlay.alertText).bold()
406 case .screenRecovering:
407 Label(notice.text, systemImage: "arrow.clockwise")
408 case .connecting, .reconnecting, .waitingToJoin:
409 // Drawn rather than AppKit's spinner, which stays dark-on-dark
410 // on this surface in a light-appearance app.
411 Image(systemName: "arrow.triangle.2.circlepath")
412 .symbolEffect(.pulse, isActive: !reduceMotion)
413 .accessibilityHidden(true)
414 Text(notice.text)
415 case .full:
416 Label(notice.text, systemImage: "person.3.fill")
417 Button("Try joining again") { call.retryJoin() }
418 case .ended:
419 Label(notice.text, systemImage: "phone.down")
420 if let rejoin {
421 Button("Join again", action: rejoin).buttonStyle(.borderedProminent)
422 .accessibilityIdentifier("joinAgain")
423 }
424 case .problem, .floor:
425 Label(notice.text, systemImage: "exclamationmark.triangle.fill")
426 }
427 if let action = notice.action {
428 NoticeActionButton(action) { call.perform(action) }
429 }
430 if notice.dismissible {
431 Button("Dismiss", systemImage: "xmark") { dismissedNotices.insert(notice.id) }
432 .labelStyle(.iconOnly).buttonStyle(.borderless)
433 .help("Dismiss")
434 }
435 }
436 .modifier(NoticeSurface())
437 .accessibilityElement(children: .contain)
438 }
439
440 // MARK: Panels
441
442 @ViewBuilder private func panels(in size: CGSize) -> some View {
443 let top = Self.titleBarHeight + 8
444 // Below the title, which shows while a panel is open.
445 let devicesTop = Self.titleBarHeight + 40
446 // 12 pt clear of the bar, level with a self view risen beside chat.
447 let bottom = Self.barReserve + SelfViewBarLayout.rise
448 if showingDevices {
449 VStack(spacing: 0) {
450 HStack {
451 Text("Devices").font(.headline)
452 Spacer()
453 Button("Hide devices", systemImage: "xmark") {
454 withAnimation(panelAnimation) { showingDevices = false }
455 }
456 .labelStyle(.iconOnly).buttonStyle(.borderless).help("Hide devices")
457 }.padding(.horizontal, 16).padding(.top, 14)
458 // Its own height when that fits, scrolling when it does not.
459 ScrollView {
460 DevicePanel(call: call)
461 .background(
462 GeometryReader { panel in
463 Color.clear
464 .onAppear { devicesHeight = panel.size.height }
465 .onChange(of: panel.size.height) { _, now in devicesHeight = now }
466 })
467 }
468 .frame(height: max(80, min(devicesHeight, size.height - devicesTop - bottom - 44)))
469 }
470 .frame(width: Self.panelWidth)
471 // Read, not glanced at, and over video: opaque and dark, with the
472 // dark appearance's full-contrast labels, whatever the system's
473 // appearance (a light material over a picture was grey on grey).
474 // It is not part of the controls' fade: it holds them up while
475 // open (`.menuOpen`) and carries no opacity of its own.
476 .foregroundStyle(.white)
477 .background(CallOverlay.panelFill, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
478 .environment(\.colorScheme, .dark)
479 .shadow(color: .black.opacity(0.35), radius: 14, y: 4)
480 .accessibilityIdentifier("devicesPanel")
481 .padding(.leading, 16).padding(.bottom, bottom)
482 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
483 .transition(panelTransition(edge: .bottom))
484 }
485 if showingChat {
486 VStack(spacing: 14) {
487 HStack {
488 Text("Chat").font(.headline)
489 Spacer()
490 Button("Open chat in a window", systemImage: "arrow.up.forward.app") {
491 showingChat = false
492 chatWindow.open(call: call)
493 }.help("Open chat in a separate window")
494 Button("Hide chat", systemImage: "xmark") {
495 withAnimation(panelAnimation) { showingChat = false }
496 }
497 .help("Hide chat")
498 }.labelStyle(.iconOnly).buttonStyle(.borderless)
499 ChatView(call: call, draft: chatWindow.draft)
500 }
501 .padding(16).frame(width: Self.panelWidth)
502 .frame(maxHeight: .infinity)
503 .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16))
504 .shadow(color: .black.opacity(0.25), radius: 12, y: 4)
505 .padding(.top, top).padding(.trailing, 12).padding(.bottom, bottom)
506 .frame(maxWidth: .infinity, alignment: .trailing)
507 .transition(panelTransition(edge: .trailing))
508 }
509 }
510
511 /// Panels slide in from their edge; with Reduce Motion they only fade.
512 private func panelTransition(edge: Edge) -> AnyTransition {
513 reduceMotion ? .opacity : .move(edge: edge).combined(with: .opacity)
514 }
515
516 // MARK: Bar
517
518 /// The bar: centred on the window and whole at every width
519 /// (CallBarFit), its width set from the window's rather than left to
520 /// whatever its row asks for — tightening, then moving the least used
521 /// controls into ⋯, before anything could reach past an edge — and
522 /// narrowed to keep clear of a self view resting in a bottom corner
523 /// (SelfViewBarLayout).
524 private func bar(in size: CGSize) -> some View {
525 let fit = selfBarLayout(in: size).bar
526 return controls(fullWindow: true, fit: fit)
527 .padding(fit.spacing.padding)
528 .frame(width: fit.width)
529 // One glass pane, no edge, the buttons sitting on it.
530 .callOverlaySurface(Capsule())
531 .shadow(color: .black.opacity(0.25), radius: 12, y: 4)
532 .background(
533 GeometryReader { bar in
534 Color.clear
535 .onAppear {
536 barFrame = bar.frame(in: .named("call"))
537 CallBarProbe.pane = bar.frame(in: .global)
538 }
539 .onChange(of: bar.frame(in: .named("call"))) { _, now in barFrame = now }
540 .onChange(of: bar.frame(in: .global)) { _, now in CallBarProbe.pane = now }
541 }
542 )
543 .padding(.bottom, CallBarFit.margin)
544 .frame(width: size.width, height: size.height, alignment: .bottom)
545 .opacity(chrome.visible ? 1 : 0)
546 .allowsHitTesting(chrome.visible)
547 // Hidden from sight but never from VoiceOver, which holds the bar
548 // up anyway; hidden from the keyboard's Tab, which brings it back.
549 .accessibilityHidden(!chrome.visible)
550 }
551 }
552
553 extension PiPCorner {
554 var moveTitle: String {
555 switch self {
556 case .topLeading: "Move self view to top left"
557 case .topTrailing: "Move self view to top right"
558 case .bottomLeading: "Move self view to bottom left"
559 case .bottomTrailing: "Move self view to bottom right"
560 }
561 }
562 }
563
564 /// A notice over the picture: a capsule of the overlay's borderless
565 /// glass, with white text and dark-appearance controls, whatever the
566 /// system's.
567 struct NoticeSurface: ViewModifier {
568 func body(content: Content) -> some View {
569 content.font(.callout).foregroundStyle(.white)
570 .environment(\.colorScheme, .dark)
571 .padding(.horizontal, 14).padding(.vertical, 8)
572 // Without Liquid Glass: its lit rim is the faint light edge Paul
573 // saw round the sharing notice (2026-09-28), and no overlay has
574 // an edge since 0.3.7.
575 .callOverlaySurface(Capsule(), rim: false)
576 .shadow(color: .black.opacity(0.25), radius: 8, y: 2)
577 }
578 }
579
580 /// The call window's own chrome while the full-window call shows: no
581 /// title bar — transparent, no title, the content under it to the very
582 /// top — and the traffic lights over the picture, fading with the
583 /// controls. Everything is put back when the call leaves the window or
584 /// changes to Classic, and none of it touches full screen or a panel.
585 ///
586 /// SwiftUI keeps its own idea of the window's title bar and can put it
587 /// back while the call is up (0.3.4 showed an opaque bar over the call);
588 /// so while this view is in the window it watches those properties and
589 /// sets them again whenever something else changes them.
590 ///
591 /// The window's title is the meeting's while the call is in it, named
592 /// or not (CallTitle.window): hidden on screen with the rest of the
593 /// title bar, it is still what the Window menu, Mission Control and
594 /// VoiceOver read. It is put back with everything else.
595 struct CallWindowChrome: NSViewRepresentable {
596 var title: String
597 var buttonsVisible: Bool
598 var fade: TimeInterval
599
600 func makeNSView(context: Context) -> ChromeView { ChromeView() }
601 func updateNSView(_ view: ChromeView, context: Context) {
602 view.setTitle(title)
603 view.setButtons(visible: buttonsVisible, fade: fade)
604 }
605 static func dismantleNSView(_ view: ChromeView, coordinator: ()) { view.release() }
606
607 final class ChromeView: NSView {
608 private weak var styled: NSWindow?
609 private var saved: (transparent: Bool, title: NSWindow.TitleVisibility, full: Bool, separator: NSTitlebarSeparatorStyle, text: String)?
610 private var title = ""
611 private var watches: [NSKeyValueObservation] = []
612 private var observers: [NSObjectProtocol] = []
613 private var buttonsVisible = true
614
615 override func viewDidMoveToWindow() {
616 super.viewDidMoveToWindow()
617 guard let window, !(window is NSPanel) else {
618 release()
619 return
620 }
621 guard styled !== window else { return }
622 release()
623 styled = window
624 saved = (
625 window.titlebarAppearsTransparent, window.titleVisibility,
626 window.styleMask.contains(.fullSizeContentView), window.titlebarSeparatorStyle,
627 window.title
628 )
629 apply(to: window)
630 if !title.isEmpty { window.title = title }
631 showButtons(animated: false)
632 watches = [
633 window.observe(\.titlebarAppearsTransparent) { [weak self] window, _ in
634 MainActor.assumeIsolated { self?.apply(to: window) }
635 },
636 window.observe(\.styleMask) { [weak self] window, _ in
637 MainActor.assumeIsolated { self?.apply(to: window) }
638 },
639 // SwiftUI writes the scene's own title ("Calls") back now and
640 // then; the meeting's goes back over it.
641 window.observe(\.title) { [weak self] window, _ in
642 MainActor.assumeIsolated {
643 guard let self, window === self.styled, !self.title.isEmpty, window.title != self.title
644 else { return }
645 window.title = self.title
646 }
647 },
648 ]
649 let center = NotificationCenter.default
650 observers = [
651 NSWindow.didEnterFullScreenNotification, NSWindow.didExitFullScreenNotification,
652 NSWindow.didBecomeKeyNotification, NSWindow.didResizeNotification,
653 ].map { name in
654 center.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
655 MainActor.assumeIsolated { self?.showButtons(animated: false) }
656 }
657 }
658 }
659
660 /// Hidden title bar, content to the top. Only what differs is set,
661 /// so the watches that call this do not call it again.
662 private func apply(to window: NSWindow) {
663 guard window === styled else { return }
664 if !window.titlebarAppearsTransparent { window.titlebarAppearsTransparent = true }
665 if window.titleVisibility != .hidden { window.titleVisibility = .hidden }
666 if !window.styleMask.contains(.fullSizeContentView) {
667 window.styleMask.insert(.fullSizeContentView)
668 }
669 if window.titlebarSeparatorStyle != .none { window.titlebarSeparatorStyle = .none }
670 }
671
672 func setTitle(_ text: String) {
673 title = text
674 if let window = styled, window.title != text { window.title = text }
675 }
676
677 func setButtons(visible: Bool, fade: TimeInterval) {
678 guard visible != buttonsVisible else { return }
679 buttonsVisible = visible
680 NSAnimationContext.runAnimationGroup { context in
681 context.duration = fade
682 context.timingFunction = CAMediaTimingFunction(name: .easeOut)
683 showButtons(animated: true)
684 }
685 }
686
687 /// The traffic lights, shown or hidden with the controls; always
688 /// shown in full screen, where the system reveals them with the menu
689 /// bar, and when the call lets the window go.
690 private func showButtons(animated: Bool) {
691 guard let window = styled else { return }
692 let fullScreen = window.styleMask.contains(.fullScreen)
693 let alpha: CGFloat = buttonsVisible || fullScreen ? 1 : 0
694 for kind in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] {
695 guard let button = window.standardWindowButton(kind) else { continue }
696 if animated { button.animator().alphaValue = alpha } else { button.alphaValue = alpha }
697 }
698 }
699
700 /// Puts the window back as it was found.
701 func release() {
702 watches.forEach { $0.invalidate() }
703 watches = []
704 observers.forEach(NotificationCenter.default.removeObserver)
705 observers = []
706 guard let window = styled, let saved else { return }
707 styled = nil
708 self.saved = nil
709 for kind in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] {
710 window.standardWindowButton(kind)?.alphaValue = 1
711 }
712 window.titlebarAppearsTransparent = saved.transparent
713 window.titleVisibility = saved.title
714 window.titlebarSeparatorStyle = saved.separator
715 window.title = saved.text
716 if !saved.full { window.styleMask.remove(.fullSizeContentView) }
717 }
718
719 override func viewWillMove(toWindow next: NSWindow?) {
720 super.viewWillMove(toWindow: next)
721 if next !== styled { release() }
722 }
723
724 override func hitTest(_ point: NSPoint) -> NSView? { nil }
725 }
726 }
727
728 /// The strip across the top of the full-window call that stands in for
729 /// the title bar it replaces: dragging it moves the window, and a double
730 /// click does what the person's "double-click a window's title bar"
731 /// setting says (zoom, minimise, or nothing).
732 struct WindowDragStrip: NSViewRepresentable {
733 func makeNSView(context: Context) -> StripView { StripView() }
734 func updateNSView(_ view: StripView, context: Context) {}
735
736 final class StripView: NSView {
737 override var mouseDownCanMoveWindow: Bool { true }
738 override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
739
740 override func mouseDown(with event: NSEvent) {
741 guard let window else { return }
742 if event.clickCount == 2 {
743 TitleBarDoubleClick.current().perform(on: window)
744 } else {
745 window.performDrag(with: event)
746 }
747 }
748 }
749 }
750
751 /// What a double click on a title bar does, from System Settings ›
752 /// Desktop & Dock: "Double-click a window's title bar to…".
753 enum TitleBarDoubleClick: Equatable {
754 case zoom, minimize, none
755
756 static func current(_ defaults: UserDefaults = .standard) -> TitleBarDoubleClick {
757 from(action: defaults.string(forKey: "AppleActionOnDoubleClick"),
758 miniaturize: defaults.object(forKey: "AppleMiniaturizeOnDoubleClick") as? Bool)
759 }
760
761 /// "Maximize" (zoom) is the default, and "Fill" zooms too; the older
762 /// boolean says minimise when the newer key is absent.
763 static func from(action: String?, miniaturize: Bool?) -> TitleBarDoubleClick {
764 switch action {
765 case "Minimize": return .minimize
766 case "None": return .none
767 case nil: return miniaturize == true ? .minimize : .zoom
768 default: return .zoom
769 }
770 }
771 }
772
773 /// What the call window's pointer and keyboard are doing, for the
774 /// controls' visibility: the pointer moving (with where, in the view's
775 /// own top-left coordinates) and leaving, Tab pressed, a menu tracking
776 /// anywhere in the app, a sheet on the window. Tracks the pointer even
777 /// while the app is not active, as a video player does.
778 struct CallWindowActivity: NSViewRepresentable {
779 var moved: (CGPoint) -> Void
780 var exited: () -> Void
781 /// Tab pressed, or a click: the person is here.
782 var activity: () -> Void
783 var menuTracking: (Bool) -> Void
784 var sheet: (Bool) -> Void
785
786 func makeNSView(context: Context) -> ActivityView { ActivityView() }
787 func updateNSView(_ view: ActivityView, context: Context) { view.handlers = self }
788 static func dismantleNSView(_ view: ActivityView, coordinator: ()) { view.stop() }
789
790 final class ActivityView: NSView {
791 var handlers: CallWindowActivity?
792 private var tracking: NSTrackingArea?
793 private var monitor: Any?
794 private var observers: [NSObjectProtocol] = []
795
796 override var isFlipped: Bool { true }
797
798 override func updateTrackingAreas() {
799 super.updateTrackingAreas()
800 if let tracking { removeTrackingArea(tracking) }
801 let area = NSTrackingArea(
802 rect: .zero,
803 options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect],
804 owner: self)
805 addTrackingArea(area)
806 tracking = area
807 }
808
809 override func mouseEntered(with event: NSEvent) { report(event) }
810 override func mouseMoved(with event: NSEvent) { report(event) }
811 override func mouseExited(with event: NSEvent) { handlers?.exited() }
812
813 private func report(_ event: NSEvent) {
814 handlers?.moved(convert(event.locationInWindow, from: nil))
815 }
816
817 override func viewDidMoveToWindow() {
818 super.viewDidMoveToWindow()
819 stop()
820 guard let window else { return }
821 window.acceptsMouseMovedEvents = true
822 // Tab is keyboard navigation starting: bring the controls to it.
823 monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown]) {
824 [weak self] event in
825 nonisolated(unsafe) let event = event
826 MainActor.assumeIsolated {
827 guard let self, event.window === self.window else { return }
828 if event.type == .leftMouseDown || event.keyCode == 48 { self.handlers?.activity() }
829 }
830 return event
831 }
832 let center = NotificationCenter.default
833 observers = [
834 center.addObserver(forName: NSMenu.didBeginTrackingNotification, object: nil, queue: .main)
835 { [weak self] _ in MainActor.assumeIsolated { self?.handlers?.menuTracking(true) } },
836 center.addObserver(forName: NSMenu.didEndTrackingNotification, object: nil, queue: .main)
837 { [weak self] _ in MainActor.assumeIsolated { self?.handlers?.menuTracking(false) } },
838 center.addObserver(
839 forName: NSWindow.willBeginSheetNotification, object: window, queue: .main
840 ) { [weak self] _ in MainActor.assumeIsolated { self?.handlers?.sheet(true) } },
841 center.addObserver(
842 forName: NSWindow.didEndSheetNotification, object: window, queue: .main
843 ) { [weak self] _ in MainActor.assumeIsolated { self?.handlers?.sheet(false) } },
844 ]
845 }
846
847 func stop() {
848 if let monitor { NSEvent.removeMonitor(monitor) }
849 monitor = nil
850 observers.forEach(NotificationCenter.default.removeObserver)
851 observers = []
852 }
853
854 deinit {
855 if let monitor { NSEvent.removeMonitor(monitor) }
856 observers.forEach(NotificationCenter.default.removeObserver)
857 }
858
859 // A layer of bookkeeping, not of content: clicks go through it.
860 override func hitTest(_ point: NSPoint) -> NSView? { nil }
861 }
862 }
863#endif
864