oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1import CoreGraphics
2import Foundation
3import SwiftUI
4
5// The rules of the full-window call, for Mac and iPhone alike, kept apart
6// from the views that apply them so tests can hold them without a window,
7// a pointer or a finger: when the controls show, where the self view
8// sits, which notices outlive the controls, and how a grid fills a window.
9
10/// Which call layout the person has chosen. "Full window" is the call
11/// filling the window with its controls over it, appearing on demand;
12/// "Classic" is the call as it was before 0.3.4, kept so the two can be
13/// compared and the old one gone back to.
14public enum CallLayoutStyle: String, CaseIterable, Identifiable, Sendable {
15 case fullWindow
16 case classic
17
18 public static let key = "callLayout"
19 public static let defaultStyle = CallLayoutStyle.fullWindow
20 public var id: String { rawValue }
21 public var title: String {
22 switch self {
23 case .fullWindow: "Full window (new)"
24 case .classic: "Classic"
25 }
26 }
27}
28
29// MARK: - Controls visibility
30
31/// Whether the call's controls are showing, as a small state machine.
32///
33/// Inputs are what a person does — moves the pointer, leaves the window,
34/// taps, presses a key, uses a control — and what is going on around the
35/// controls that should keep them up: a menu or panel open, keyboard
36/// focus in them, VoiceOver, an alert. The one output is `visible`, and
37/// `hideAt`, the moment it will turn false if nothing else happens, for
38/// whoever owns the clock to wake at.
39///
40/// Time is plain seconds on any monotonic clock, passed in, so a test is
41/// a sequence of calls with made-up times.
42public struct ControlsVisibility: Equatable, Sendable {
43 /// How the person is pointing: a Mac's pointer, or a finger.
44 public enum Input: Sendable { case pointer, touch }
45
46 /// Things that keep the controls up for as long as they last.
47 public struct Holds: OptionSet, Hashable, Sendable {
48 public let rawValue: Int
49 public init(rawValue: Int) { self.rawValue = rawValue }
50 /// The pointer is over the control bar itself.
51 public static let pointerOverControls = Holds(rawValue: 1 << 0)
52 /// A menu, popover, sheet or panel from the controls is open.
53 public static let menuOpen = Holds(rawValue: 1 << 1)
54 /// Keyboard focus is on one of the controls.
55 public static let keyboardFocus = Holds(rawValue: 1 << 2)
56 /// VoiceOver is running: controls that come and go are controls a
57 /// screen reader cannot find, so they stay.
58 public static let voiceOver = Holds(rawValue: 1 << 3)
59 /// An alert or window sheet is showing.
60 public static let alert = Holds(rawValue: 1 << 4)
61 }
62
63 /// A Mac keeps its controls fully up for 3 s after the pointer last
64 /// moved. At 1.5 s (0.3.4) they went while the person was still reading
65 /// them; three is what QuickTime and FaceTime give, and moving the
66 /// pointer a millimetre still brings them straight back.
67 public static let pointerDelay: TimeInterval = 3
68 /// A touch screen waits 3 s after the last tap. There is no hover to say
69 /// the person is still looking: a tap is the only sign, and after it the
70 /// thumb still has to find its target and the eyes have to read the bar.
71 public static let touchDelay: TimeInterval = 3
72 /// When the pointer leaves the window the controls linger 1.5 s rather
73 /// than going at once: a pointer that overshoots the edge, or crosses
74 /// out and back on its way to the Dock, should not blink them. Leaving
75 /// only ever shortens the wait — controls due to go sooner still do.
76 public static let pointerExitDelay: TimeInterval = 1.5
77 /// How long the controls take to fade out: long enough to be seen going,
78 /// eased out so the change starts at once and settles.
79 public static let fadeOutDuration: TimeInterval = 0.35
80 /// How long they take to come back: quicker, since the person asked.
81 public static let fadeInDuration: TimeInterval = 0.2
82 /// With Reduce Motion: a short opacity change rather than none, so the
83 /// change is still noticed without anything easing across the screen.
84 public static let reducedMotionFadeDuration: TimeInterval = 0.1
85
86 public let input: Input
87 public private(set) var visible: Bool
88 public private(set) var holds: Holds = []
89 /// When the controls hide unless something happens first. Nil when
90 /// they are hidden, or held up.
91 public private(set) var hideAt: TimeInterval?
92 /// Whether the pointer is inside the window. Always false for touch.
93 public private(set) var pointerInside = false
94
95 public var delay: TimeInterval { input == .pointer ? Self.pointerDelay : Self.touchDelay }
96 public var held: Bool { !holds.isEmpty }
97
98 /// Controls start visible, so a call opens with them in view, and fade
99 /// on the usual schedule.
100 public init(input: Input, now: TimeInterval) {
101 self.input = input
102 visible = true
103 hideAt = now + (input == .pointer ? Self.pointerDelay : Self.touchDelay)
104 }
105
106 /// The pointer moved over the window: show, and start the wait again.
107 public mutating func pointerMoved(now: TimeInterval) {
108 pointerInside = true
109 reveal(now: now)
110 }
111
112 /// The pointer left the window: hide `pointerExitDelay` later (or when
113 /// they were due already, if sooner), unless something holds the
114 /// controls up. Leaving the window is also leaving the bar.
115 public mutating func pointerExited(now: TimeInterval) {
116 pointerInside = false
117 holds.remove(.pointerOverControls)
118 guard visible, !held else { return }
119 let linger = now + Self.pointerExitDelay
120 hideAt = min(hideAt ?? linger, linger)
121 }
122
123 /// A tap on the picture (touch). It toggles: a tap shows hidden
124 /// controls and hides showing ones — unless they are held, when it only
125 /// starts the wait again.
126 public mutating func tapped(now: TimeInterval) {
127 if visible, !held {
128 hide()
129 } else {
130 reveal(now: now)
131 }
132 }
133
134 /// Anything else that says the person is here: a key such as Tab, a
135 /// control being used. Shows the controls and starts the wait again.
136 public mutating func activity(now: TimeInterval) {
137 reveal(now: now)
138 }
139
140 /// Something that holds the controls up started (`on`) or stopped.
141 /// Holding shows them; letting go of the last hold starts the usual wait
142 /// rather than hiding them under the person's nose.
143 public mutating func set(_ hold: Holds, _ on: Bool, now: TimeInterval) {
144 if on {
145 holds.formUnion(hold)
146 visible = true
147 hideAt = nil
148 } else {
149 guard !holds.isDisjoint(with: hold) else { return }
150 holds.subtract(hold)
151 if !held, visible { hideAt = now + delay }
152 }
153 }
154
155 /// The clock: hides the controls once `hideAt` has passed.
156 public mutating func tick(now: TimeInterval) {
157 guard !held, let hideAt, now >= hideAt else { return }
158 hide()
159 }
160
161 /// Whether the pointer should be hidden too: on a Mac, when the
162 /// controls have gone and the pointer is over the call. Moving it
163 /// brings both back.
164 public var hidesPointer: Bool { input == .pointer && !visible && pointerInside }
165
166 /// How long the controls take to fade in or out. Opacity only, never a
167 /// slide; with Reduce Motion a short cross-fade rather than none, so
168 /// the change is still noticed without anything moving.
169 public static func fadeDuration(showing: Bool, reduceMotion: Bool) -> TimeInterval {
170 if reduceMotion { return reducedMotionFadeDuration }
171 return showing ? fadeInDuration : fadeOutDuration
172 }
173
174 /// The fade itself: ease-out, so it starts at once and settles; with
175 /// Reduce Motion a short linear opacity change.
176 public static func fade(showing: Bool, reduceMotion: Bool) -> Animation {
177 let duration = fadeDuration(showing: showing, reduceMotion: reduceMotion)
178 return reduceMotion ? .linear(duration: duration) : .easeOut(duration: duration)
179 }
180
181 /// Whether a Mac call window's traffic lights show: with the controls,
182 /// so the picture is clean when they go, as in QuickTime — except in
183 /// full screen, where the system shows them with the menu bar.
184 public func showsWindowButtons(fullScreen: Bool) -> Bool { fullScreen || visible }
185
186 private mutating func reveal(now: TimeInterval) {
187 visible = true
188 hideAt = held ? nil : now + delay
189 }
190
191 private mutating func hide() {
192 visible = false
193 hideAt = nil
194 }
195}
196
197/// Owns a `ControlsVisibility` and the clock it needs: wakes at `hideAt`
198/// and ticks. Views talk to this; tests talk to the struct.
199@MainActor public final class ControlsVisibilityModel: ObservableObject {
200 @Published public private(set) var state: ControlsVisibility
201 /// Pins the controls shown or hidden regardless of input, for fixtures.
202 public let pinned: Bool?
203 /// Called whenever `state` changes, after it has.
204 public var changed: ((ControlsVisibility) -> Void)?
205 private var timer: Task<Void, Never>?
206
207 public init(input: ControlsVisibility.Input, pinned: Bool? = nil) {
208 state = ControlsVisibility(input: input, now: Self.now)
209 self.pinned = pinned
210 schedule()
211 }
212
213 public var visible: Bool { pinned ?? state.visible }
214 /// See `ControlsVisibility.showsWindowButtons(fullScreen:)`; a fixture's
215 /// pin decides for the traffic lights as for the controls.
216 public func showsWindowButtons(fullScreen: Bool) -> Bool {
217 fullScreen || visible
218 }
219
220 public func pointerMoved() { update { $0.pointerMoved(now: Self.now) } }
221 public func pointerExited() { update { $0.pointerExited(now: Self.now) } }
222 public func tapped() { update { $0.tapped(now: Self.now) } }
223 public func activity() { update { $0.activity(now: Self.now) } }
224 public func set(_ hold: ControlsVisibility.Holds, _ on: Bool) {
225 guard on ? !state.holds.isSuperset(of: hold) : !state.holds.isDisjoint(with: hold) else {
226 return
227 }
228 update { $0.set(hold, on, now: Self.now) }
229 }
230
231 private static var now: TimeInterval { ProcessInfo.processInfo.systemUptime }
232
233 private func update(_ change: (inout ControlsVisibility) -> Void) {
234 var next = state
235 change(&next)
236 if next != state {
237 state = next
238 changed?(next)
239 }
240 schedule()
241 }
242
243 private func schedule() {
244 timer?.cancel()
245 guard let hideAt = state.hideAt else {
246 timer = nil
247 return
248 }
249 let wait = max(0, hideAt - Self.now)
250 timer = Task { [weak self] in
251 try? await Task.sleep(for: .seconds(wait))
252 guard !Task.isCancelled, let self else { return }
253 self.update { $0.tick(now: Self.now) }
254 }
255 }
256}
257
258// MARK: - Self view picture-in-picture
259
260/// A corner of the call, where the self view settles.
261public enum PiPCorner: String, CaseIterable, Sendable {
262 case topLeading, topTrailing, bottomLeading, bottomTrailing
263
264 public static let key = "selfViewCorner"
265 public var top: Bool { self == .topLeading || self == .topTrailing }
266 public var leading: Bool { self == .topLeading || self == .bottomLeading }
267}
268
269/// Where the floating self view goes, and where it goes when dropped.
270public enum PiPLayout {
271 /// The gap between the self view and whatever it is kept clear of.
272 public static let margin: CGFloat = 12
273
274 /// The self view's size in a stage of `container`: about a fifth of the
275 /// width on a Mac (16:9), a little over a quarter on a phone, upright
276 /// in portrait since that is how a phone's camera sees you. `shape` is
277 /// your own picture's, once it is known (2026-10-21): a camera that
278 /// sends upright floats upright, wherever it is, rather than cropped to
279 /// a landscape sliver, and a phone's turned camera turns its view.
280 public static func size(in container: CGSize, touch: Bool, shape: VideoShape? = nil) -> CGSize {
281 if touch {
282 let portrait = shape.map { $0 == .portrait } ?? (container.height >= container.width)
283 let width = min(max(container.width * (portrait ? 0.28 : 0.2), 88), 150)
284 return CGSize(width: width, height: (width * (portrait ? 4 / 3 : 3 / 4)).rounded())
285 }
286 if shape == .portrait {
287 // The same height a landscape one would have at this window's
288 // width, upright: 9:16, at least 90 wide.
289 let height = (min(max(container.width * 0.2, 150), 260) * 9 / 16 * 1.6).rounded()
290 return CGSize(width: max(90, (height * 9 / 16).rounded()), height: height)
291 }
292 let width = min(max(container.width * 0.2, 150), 260)
293 return CGSize(width: width, height: (width * 9 / 16).rounded())
294 }
295
296 /// The self view's frame in `corner`, `margin` in from the stage's
297 /// edges and from anything `insets` keeps it clear of — the control
298 /// bar while it shows, a sidebar, the safe area.
299 public static func frame(
300 corner: PiPCorner, size: CGSize, in container: CGSize, insets: EdgeInsets = EdgeInsets()
301 ) -> CGRect {
302 let x =
303 corner.leading
304 ? insets.leading + margin
305 : container.width - insets.trailing - margin - size.width
306 let y =
307 corner.top
308 ? insets.top + margin
309 : container.height - insets.bottom - margin - size.height
310 // A stage too small for the insets still keeps the view on it.
311 return CGRect(
312 x: min(max(x, 0), max(container.width - size.width, 0)),
313 y: min(max(y, 0), max(container.height - size.height, 0)),
314 width: size.width, height: size.height)
315 }
316
317 /// The corner a dropped self view settles in: the quarter of the stage
318 /// its centre was headed for when let go. `predicted` is where the
319 /// drag's momentum would carry the centre, so a flick towards a corner
320 /// reaches it without being dragged the whole way.
321 public static func corner(droppedAt center: CGPoint, predicted: CGPoint? = nil, in container: CGSize)
322 -> PiPCorner
323 {
324 let point = predicted ?? center
325 let leading = point.x < container.width / 2
326 let top = point.y < container.height / 2
327 switch (top, leading) {
328 case (true, true): return .topLeading
329 case (true, false): return .topTrailing
330 case (false, true): return .bottomLeading
331 case (false, false): return .bottomTrailing
332 }
333 }
334}
335
336// MARK: - Notices
337
338/// Something the call needs to say, over the picture.
339public struct CallNotice: Identifiable, Equatable, Sendable {
340 public enum Kind: Equatable, Sendable {
341 /// The call is being reached: before the first roster, and between a
342 /// fresh stream and admission. The title pill said "Connecting" until
343 /// 2026-10-02; with the pill gone this notice is where it is said.
344 case connecting
345 /// The connection dropped and is coming back.
346 case reconnecting
347 /// You are waiting for a member to let you in.
348 case waitingToJoin
349 /// The meeting is full; "Try joining again".
350 case full
351 /// The call is over for you — ended, open elsewhere, removed — and
352 /// "Join again" may be offered.
353 case ended
354 /// Something went wrong that the person should know about.
355 case problem
356 /// This app is sharing its screen: said in words for as long as it is,
357 /// with a Stop sharing button of its own (`action`).
358 case sharing
359 /// Someone's view of this app's screen stalled and the watchdog is
360 /// putting it right (spec §15.21). Quiet, and under the sharing notice.
361 case screenRecovering
362 /// Relay unavailable: direct connections only.
363 case floor
364 }
365 public let kind: Kind
366 public let text: String
367 public var id: String { "\(kind):\(text)" }
368
369 /// Important notices stay on screen with the controls hidden, until what
370 /// they are about is over or the person dismisses them. The rest fade
371 /// with the controls.
372 public var important: Bool { kind != .floor }
373 /// Whether the notice has a close button. Notices that describe a state
374 /// that ends on its own (reconnecting, sharing) go when it does; a
375 /// problem or an ended call is the person's to put away.
376 public var dismissible: Bool { kind == .problem }
377
378 /// What the notice's own button does, if it has one.
379 public enum Action: Equatable, Sendable {
380 /// Paul, 2026-09-28: "I would expect this notification to have a
381 /// 'Stop sharing' button inline." The same stop as the bar's toggle.
382 case stopSharing
383 /// The call has ended under you: "Report a problem" (spec §15.26),
384 /// which works for ten minutes after it.
385 case reportProblem
386 }
387 public var action: Action? {
388 switch kind {
389 case .sharing: .stopSharing
390 case .ended: .reportProblem
391 default: nil
392 }
393 }
394}
395
396public enum CallNotices {
397 /// The call's own line when there is nothing to say about it: in the
398 /// meeting, not yet joining, or left. Every other status is a notice.
399 public static let quietStatuses: Set<String> = [
400 "In the meeting", "Ready to join", "You left the meeting",
401 ]
402
403 /// What to say over the call, most urgent first. `status` is the call's
404 /// own line ("In the meeting").
405 ///
406 /// Since 2026-10-02 there is no title pill showing `status` beside the
407 /// title, so every status that is not one of `quietStatuses` is a
408 /// notice here: Connecting…, Waiting to be let in, the room full,
409 /// Reconnecting…, the call over, and anything that went wrong ("Could
410 /// not…", "A participant’s media could not connect.", "Keep the
411 /// message within 2 KB.") — not only the ones that began "Could not".
412 public static func notices(
413 phase: String?, status: String, sharingScreen: Bool, screenNote: String, floor: Bool,
414 screenRecovery: String = ""
415 ) -> [CallNotice] {
416 var out: [CallNotice] = []
417 switch phase {
418 case "reconnecting": out.append(CallNotice(kind: .reconnecting, text: status))
419 case "waiting": out.append(CallNotice(kind: .waitingToJoin, text: status))
420 case "full": out.append(CallNotice(kind: .full, text: status))
421 case "ended": out.append(CallNotice(kind: .ended, text: status))
422 default:
423 if status == "Connecting…" {
424 out.append(CallNotice(kind: .connecting, text: status))
425 } else if !status.isEmpty, !quietStatuses.contains(status) {
426 out.append(CallNotice(kind: .problem, text: status))
427 }
428 }
429 if sharingScreen {
430 out.append(CallNotice(kind: .sharing, text: "You are sharing your screen"))
431 // Quiet: said while the watchdog puts it right, and gone after.
432 if !screenRecovery.isEmpty { out.append(CallNotice(kind: .screenRecovering, text: screenRecovery)) }
433 } else if !screenNote.isEmpty {
434 out.append(CallNotice(kind: .problem, text: screenNote))
435 }
436 if floor {
437 out.append(
438 CallNotice(
439 kind: .floor,
440 text: "Direct connections only. People on some networks may be unable to connect."))
441 }
442 return out
443 }
444}
445
446/// The call's title over the picture (2026-10-02, Paul approved). There
447/// is no pill: a title someone chose is shown the way a window shows its
448/// title — plain, centred, fading with the controls — and a title Calls
449/// wrote ("Call, 2 Oct 15:40") is not shown at all. The window's own
450/// title, which the Window menu, Mission Control and VoiceOver read, is
451/// the meeting's title either way.
452public enum CallTitle {
453 /// What to show over the call, or nil for nothing.
454 public static func shown(title: String, named: Bool) -> String? {
455 let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
456 return named && !trimmed.isEmpty ? trimmed : nil
457 }
458
459 /// The window's title: the meeting's, named or not, and the app's name
460 /// before a meeting has said what it is called.
461 public static func window(title: String) -> String {
462 let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
463 return trimmed.isEmpty ? "Calls" : trimmed
464 }
465}
466
467/// A notice's own button (`CallNotice.action`): a compact light capsule
468/// that reads on the dark glass, reachable from the keyboard, where
469/// Return as well as Space presses it.
470public struct NoticeActionButton: View {
471 let action: CallNotice.Action
472 let perform: () -> Void
473 @FocusState private var focused: Bool
474
475 public init(_ action: CallNotice.Action, perform: @escaping () -> Void) {
476 self.action = action
477 self.perform = perform
478 }
479
480 public var body: some View {
481 switch action {
482 case .stopSharing: capsule("Stop sharing", label: "Stop sharing your screen", id: "stopSharingInline")
483 case .reportProblem: capsule(ProblemWords.title, label: ProblemWords.title, id: "reportProblem")
484 }
485 }
486
487 private func capsule(_ title: String, label: String, id: String) -> some View {
488 Button(action: perform) {
489 Text(title).font(.callout.weight(.semibold))
490 .padding(.horizontal, 12).padding(.vertical, 4)
491 .foregroundStyle(Color.black)
492 .background(Capsule().fill(Color.white.opacity(focused ? 1 : 0.92)))
493 .overlay(Capsule().strokeBorder(Color.white, lineWidth: focused ? 2 : 0).padding(-3))
494 .contentShape(Capsule())
495 }
496 .buttonStyle(.plain)
497 .focusable()
498 .focused($focused)
499 .onKeyPress(.return) {
500 perform()
501 return .handled
502 }
503 .accessibilityLabel(label)
504 .accessibilityIdentifier(id)
505 }
506}
507
508extension Call {
509 /// Runs a notice's own action (see `CallNotice.action`).
510 public func perform(_ action: CallNotice.Action) {
511 switch action {
512 case .stopSharing: stopSharingScreen()
513 case .reportProblem: reportProblem()
514 }
515 }
516}
517
518// MARK: - Grid
519
520/// How a grid of tiles fills a stage without scrolling.
521public enum GridFit {
522 /// The column count that makes `count` tiles of `aspect` (width over
523 /// height) as large as they can be in `size`, `spacing` apart.
524 public static func columns(count: Int, in size: CGSize, aspect: CGFloat, spacing: CGFloat = 4)
525 -> Int
526 {
527 guard count > 1, size.width > 0, size.height > 0 else { return 1 }
528 var best = 1
529 var bestWidth: CGFloat = 0
530 for columns in 1...count {
531 let rows = (count + columns - 1) / columns
532 let width = tileWidth(columns: columns, rows: rows, in: size, aspect: aspect, spacing: spacing)
533 if width > bestWidth + 0.5 {
534 best = columns
535 bestWidth = width
536 }
537 }
538 return best
539 }
540
541 /// The tile size for `count` tiles in `columns` columns.
542 public static func tile(count: Int, columns: Int, in size: CGSize, aspect: CGFloat, spacing: CGFloat = 4)
543 -> CGSize
544 {
545 let rows = (max(count, 1) + max(columns, 1) - 1) / max(columns, 1)
546 let width = tileWidth(
547 columns: max(columns, 1), rows: rows, in: size, aspect: aspect, spacing: spacing)
548 return CGSize(width: width, height: width / aspect)
549 }
550
551 private static func tileWidth(
552 columns: Int, rows: Int, in size: CGSize, aspect: CGFloat, spacing: CGFloat
553 ) -> CGFloat {
554 let across = (size.width - CGFloat(columns - 1) * spacing) / CGFloat(columns)
555 let down = (size.height - CGFloat(rows - 1) * spacing) / CGFloat(rows)
556 return max(0, min(across, down * aspect))
557 }
558}
559
560// MARK: - Camera flip
561
562public enum CameraFlip {
563 /// The camera "Flip camera" moves to: from the built-in (front) camera
564 /// to the first other one, and from any other back to the built-in —
565 /// front to back and back to front on an iPhone. Nil with nothing to
566 /// flip to.
567 public static func next(from current: String?, in cameras: [CameraDevice]) -> CameraDevice? {
568 guard cameras.count > 1 else { return nil }
569 guard let current, let now = cameras.first(where: { $0.id == current }) else {
570 return cameras.first
571 }
572 if let other = cameras.first(where: { $0.builtIn != now.builtIn }) { return other }
573 let index = cameras.firstIndex(of: now) ?? 0
574 return cameras[(index + 1) % cameras.count]
575 }
576}
577