import CoreGraphics import Foundation import SwiftUI // The rules of the full-window call, for Mac and iPhone alike, kept apart // from the views that apply them so tests can hold them without a window, // a pointer or a finger: when the controls show, where the self view // sits, which notices outlive the controls, and how a grid fills a window. /// Which call layout the person has chosen. "Full window" is the call /// filling the window with its controls over it, appearing on demand; /// "Classic" is the call as it was before 0.3.4, kept so the two can be /// compared and the old one gone back to. public enum CallLayoutStyle: String, CaseIterable, Identifiable, Sendable { case fullWindow case classic public static let key = "callLayout" public static let defaultStyle = CallLayoutStyle.fullWindow public var id: String { rawValue } public var title: String { switch self { case .fullWindow: "Full window (new)" case .classic: "Classic" } } } // MARK: - Controls visibility /// Whether the call's controls are showing, as a small state machine. /// /// Inputs are what a person does — moves the pointer, leaves the window, /// taps, presses a key, uses a control — and what is going on around the /// controls that should keep them up: a menu or panel open, keyboard /// focus in them, VoiceOver, an alert. The one output is `visible`, and /// `hideAt`, the moment it will turn false if nothing else happens, for /// whoever owns the clock to wake at. /// /// Time is plain seconds on any monotonic clock, passed in, so a test is /// a sequence of calls with made-up times. public struct ControlsVisibility: Equatable, Sendable { /// How the person is pointing: a Mac's pointer, or a finger. public enum Input: Sendable { case pointer, touch } /// Things that keep the controls up for as long as they last. public struct Holds: OptionSet, Hashable, Sendable { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// The pointer is over the control bar itself. public static let pointerOverControls = Holds(rawValue: 1 << 0) /// A menu, popover, sheet or panel from the controls is open. public static let menuOpen = Holds(rawValue: 1 << 1) /// Keyboard focus is on one of the controls. public static let keyboardFocus = Holds(rawValue: 1 << 2) /// VoiceOver is running: controls that come and go are controls a /// screen reader cannot find, so they stay. public static let voiceOver = Holds(rawValue: 1 << 3) /// An alert or window sheet is showing. public static let alert = Holds(rawValue: 1 << 4) } /// A Mac keeps its controls fully up for 3 s after the pointer last /// moved. At 1.5 s (0.3.4) they went while the person was still reading /// them; three is what QuickTime and FaceTime give, and moving the /// pointer a millimetre still brings them straight back. public static let pointerDelay: TimeInterval = 3 /// A touch screen waits 3 s after the last tap. There is no hover to say /// the person is still looking: a tap is the only sign, and after it the /// thumb still has to find its target and the eyes have to read the bar. public static let touchDelay: TimeInterval = 3 /// When the pointer leaves the window the controls linger 1.5 s rather /// than going at once: a pointer that overshoots the edge, or crosses /// out and back on its way to the Dock, should not blink them. Leaving /// only ever shortens the wait — controls due to go sooner still do. public static let pointerExitDelay: TimeInterval = 1.5 /// How long the controls take to fade out: long enough to be seen going, /// eased out so the change starts at once and settles. public static let fadeOutDuration: TimeInterval = 0.35 /// How long they take to come back: quicker, since the person asked. public static let fadeInDuration: TimeInterval = 0.2 /// With Reduce Motion: a short opacity change rather than none, so the /// change is still noticed without anything easing across the screen. public static let reducedMotionFadeDuration: TimeInterval = 0.1 public let input: Input public private(set) var visible: Bool public private(set) var holds: Holds = [] /// When the controls hide unless something happens first. Nil when /// they are hidden, or held up. public private(set) var hideAt: TimeInterval? /// Whether the pointer is inside the window. Always false for touch. public private(set) var pointerInside = false public var delay: TimeInterval { input == .pointer ? Self.pointerDelay : Self.touchDelay } public var held: Bool { !holds.isEmpty } /// Controls start visible, so a call opens with them in view, and fade /// on the usual schedule. public init(input: Input, now: TimeInterval) { self.input = input visible = true hideAt = now + (input == .pointer ? Self.pointerDelay : Self.touchDelay) } /// The pointer moved over the window: show, and start the wait again. public mutating func pointerMoved(now: TimeInterval) { pointerInside = true reveal(now: now) } /// The pointer left the window: hide `pointerExitDelay` later (or when /// they were due already, if sooner), unless something holds the /// controls up. Leaving the window is also leaving the bar. public mutating func pointerExited(now: TimeInterval) { pointerInside = false holds.remove(.pointerOverControls) guard visible, !held else { return } let linger = now + Self.pointerExitDelay hideAt = min(hideAt ?? linger, linger) } /// A tap on the picture (touch). It toggles: a tap shows hidden /// controls and hides showing ones — unless they are held, when it only /// starts the wait again. public mutating func tapped(now: TimeInterval) { if visible, !held { hide() } else { reveal(now: now) } } /// Anything else that says the person is here: a key such as Tab, a /// control being used. Shows the controls and starts the wait again. public mutating func activity(now: TimeInterval) { reveal(now: now) } /// Something that holds the controls up started (`on`) or stopped. /// Holding shows them; letting go of the last hold starts the usual wait /// rather than hiding them under the person's nose. public mutating func set(_ hold: Holds, _ on: Bool, now: TimeInterval) { if on { holds.formUnion(hold) visible = true hideAt = nil } else { guard !holds.isDisjoint(with: hold) else { return } holds.subtract(hold) if !held, visible { hideAt = now + delay } } } /// The clock: hides the controls once `hideAt` has passed. public mutating func tick(now: TimeInterval) { guard !held, let hideAt, now >= hideAt else { return } hide() } /// Whether the pointer should be hidden too: on a Mac, when the /// controls have gone and the pointer is over the call. Moving it /// brings both back. public var hidesPointer: Bool { input == .pointer && !visible && pointerInside } /// How long the controls take to fade in or out. Opacity only, never a /// slide; with Reduce Motion a short cross-fade rather than none, so /// the change is still noticed without anything moving. public static func fadeDuration(showing: Bool, reduceMotion: Bool) -> TimeInterval { if reduceMotion { return reducedMotionFadeDuration } return showing ? fadeInDuration : fadeOutDuration } /// The fade itself: ease-out, so it starts at once and settles; with /// Reduce Motion a short linear opacity change. public static func fade(showing: Bool, reduceMotion: Bool) -> Animation { let duration = fadeDuration(showing: showing, reduceMotion: reduceMotion) return reduceMotion ? .linear(duration: duration) : .easeOut(duration: duration) } /// Whether a Mac call window's traffic lights show: with the controls, /// so the picture is clean when they go, as in QuickTime — except in /// full screen, where the system shows them with the menu bar. public func showsWindowButtons(fullScreen: Bool) -> Bool { fullScreen || visible } private mutating func reveal(now: TimeInterval) { visible = true hideAt = held ? nil : now + delay } private mutating func hide() { visible = false hideAt = nil } } /// Owns a `ControlsVisibility` and the clock it needs: wakes at `hideAt` /// and ticks. Views talk to this; tests talk to the struct. @MainActor public final class ControlsVisibilityModel: ObservableObject { @Published public private(set) var state: ControlsVisibility /// Pins the controls shown or hidden regardless of input, for fixtures. public let pinned: Bool? /// Called whenever `state` changes, after it has. public var changed: ((ControlsVisibility) -> Void)? private var timer: Task? public init(input: ControlsVisibility.Input, pinned: Bool? = nil) { state = ControlsVisibility(input: input, now: Self.now) self.pinned = pinned schedule() } public var visible: Bool { pinned ?? state.visible } /// See `ControlsVisibility.showsWindowButtons(fullScreen:)`; a fixture's /// pin decides for the traffic lights as for the controls. public func showsWindowButtons(fullScreen: Bool) -> Bool { fullScreen || visible } public func pointerMoved() { update { $0.pointerMoved(now: Self.now) } } public func pointerExited() { update { $0.pointerExited(now: Self.now) } } public func tapped() { update { $0.tapped(now: Self.now) } } public func activity() { update { $0.activity(now: Self.now) } } public func set(_ hold: ControlsVisibility.Holds, _ on: Bool) { guard on ? !state.holds.isSuperset(of: hold) : !state.holds.isDisjoint(with: hold) else { return } update { $0.set(hold, on, now: Self.now) } } private static var now: TimeInterval { ProcessInfo.processInfo.systemUptime } private func update(_ change: (inout ControlsVisibility) -> Void) { var next = state change(&next) if next != state { state = next changed?(next) } schedule() } private func schedule() { timer?.cancel() guard let hideAt = state.hideAt else { timer = nil return } let wait = max(0, hideAt - Self.now) timer = Task { [weak self] in try? await Task.sleep(for: .seconds(wait)) guard !Task.isCancelled, let self else { return } self.update { $0.tick(now: Self.now) } } } } // MARK: - Self view picture-in-picture /// A corner of the call, where the self view settles. public enum PiPCorner: String, CaseIterable, Sendable { case topLeading, topTrailing, bottomLeading, bottomTrailing public static let key = "selfViewCorner" public var top: Bool { self == .topLeading || self == .topTrailing } public var leading: Bool { self == .topLeading || self == .bottomLeading } } /// Where the floating self view goes, and where it goes when dropped. public enum PiPLayout { /// The gap between the self view and whatever it is kept clear of. public static let margin: CGFloat = 12 /// The self view's size in a stage of `container`: about a fifth of the /// width on a Mac (16:9), a little over a quarter on a phone, upright /// in portrait since that is how a phone's camera sees you. public static func size(in container: CGSize, touch: Bool) -> CGSize { if touch { let portrait = container.height >= container.width let width = min(max(container.width * (portrait ? 0.28 : 0.2), 88), 150) return CGSize(width: width, height: (width * (portrait ? 4 / 3 : 3 / 4)).rounded()) } let width = min(max(container.width * 0.2, 150), 260) return CGSize(width: width, height: (width * 9 / 16).rounded()) } /// The self view's frame in `corner`, `margin` in from the stage's /// edges and from anything `insets` keeps it clear of — the control /// bar while it shows, a sidebar, the safe area. public static func frame( corner: PiPCorner, size: CGSize, in container: CGSize, insets: EdgeInsets = EdgeInsets() ) -> CGRect { let x = corner.leading ? insets.leading + margin : container.width - insets.trailing - margin - size.width let y = corner.top ? insets.top + margin : container.height - insets.bottom - margin - size.height // A stage too small for the insets still keeps the view on it. return CGRect( x: min(max(x, 0), max(container.width - size.width, 0)), y: min(max(y, 0), max(container.height - size.height, 0)), width: size.width, height: size.height) } /// The corner a dropped self view settles in: the quarter of the stage /// its centre was headed for when let go. `predicted` is where the /// drag's momentum would carry the centre, so a flick towards a corner /// reaches it without being dragged the whole way. public static func corner(droppedAt center: CGPoint, predicted: CGPoint? = nil, in container: CGSize) -> PiPCorner { let point = predicted ?? center let leading = point.x < container.width / 2 let top = point.y < container.height / 2 switch (top, leading) { case (true, true): return .topLeading case (true, false): return .topTrailing case (false, true): return .bottomLeading case (false, false): return .bottomTrailing } } } // MARK: - Notices /// Something the call needs to say, over the picture. public struct CallNotice: Identifiable, Equatable, Sendable { public enum Kind: Equatable, Sendable { /// The call is being reached: before the first roster, and between a /// fresh stream and admission. The title pill said "Connecting" until /// 2026-10-02; with the pill gone this notice is where it is said. case connecting /// The connection dropped and is coming back. case reconnecting /// You are waiting for a member to let you in. case waitingToJoin /// The meeting is full; "Try joining again". case full /// The call is over for you — ended, open elsewhere, removed — and /// "Join again" may be offered. case ended /// Something went wrong that the person should know about. case problem /// This app is sharing its screen: said in words for as long as it is, /// with a Stop sharing button of its own (`action`). case sharing /// Someone's view of this app's screen stalled and the watchdog is /// putting it right (spec §15.21). Quiet, and under the sharing notice. case screenRecovering /// Relay unavailable: direct connections only. case floor } public let kind: Kind public let text: String public var id: String { "\(kind):\(text)" } /// Important notices stay on screen with the controls hidden, until what /// they are about is over or the person dismisses them. The rest fade /// with the controls. public var important: Bool { kind != .floor } /// Whether the notice has a close button. Notices that describe a state /// that ends on its own (reconnecting, sharing) go when it does; a /// problem or an ended call is the person's to put away. public var dismissible: Bool { kind == .problem } /// What the notice's own button does, if it has one. public enum Action: Equatable, Sendable { /// Paul, 2026-09-28: "I would expect this notification to have a /// 'Stop sharing' button inline." The same stop as the bar's toggle. case stopSharing /// The call has ended under you: "Report a problem" (spec §15.26), /// which works for ten minutes after it. case reportProblem } public var action: Action? { switch kind { case .sharing: .stopSharing case .ended: .reportProblem default: nil } } } public enum CallNotices { /// The call's own line when there is nothing to say about it: in the /// meeting, not yet joining, or left. Every other status is a notice. public static let quietStatuses: Set = [ "In the meeting", "Ready to join", "You left the meeting", ] /// What to say over the call, most urgent first. `status` is the call's /// own line ("In the meeting"). /// /// Since 2026-10-02 there is no title pill showing `status` beside the /// title, so every status that is not one of `quietStatuses` is a /// notice here: Connecting…, Waiting to be let in, the room full, /// Reconnecting…, the call over, and anything that went wrong ("Could /// not…", "A participant’s media could not connect.", "Keep the /// message within 2 KB.") — not only the ones that began "Could not". public static func notices( phase: String?, status: String, sharingScreen: Bool, screenNote: String, floor: Bool, screenRecovery: String = "" ) -> [CallNotice] { var out: [CallNotice] = [] switch phase { case "reconnecting": out.append(CallNotice(kind: .reconnecting, text: status)) case "waiting": out.append(CallNotice(kind: .waitingToJoin, text: status)) case "full": out.append(CallNotice(kind: .full, text: status)) case "ended": out.append(CallNotice(kind: .ended, text: status)) default: if status == "Connecting…" { out.append(CallNotice(kind: .connecting, text: status)) } else if !status.isEmpty, !quietStatuses.contains(status) { out.append(CallNotice(kind: .problem, text: status)) } } if sharingScreen { out.append(CallNotice(kind: .sharing, text: "You are sharing your screen")) // Quiet: said while the watchdog puts it right, and gone after. if !screenRecovery.isEmpty { out.append(CallNotice(kind: .screenRecovering, text: screenRecovery)) } } else if !screenNote.isEmpty { out.append(CallNotice(kind: .problem, text: screenNote)) } if floor { out.append( CallNotice( kind: .floor, text: "Direct connections only. People on some networks may be unable to connect.")) } return out } } /// The call's title over the picture (2026-10-02, Paul approved). There /// is no pill: a title someone chose is shown the way a window shows its /// title — plain, centred, fading with the controls — and a title Calls /// wrote ("Call, 2 Oct 15:40") is not shown at all. The window's own /// title, which the Window menu, Mission Control and VoiceOver read, is /// the meeting's title either way. public enum CallTitle { /// What to show over the call, or nil for nothing. public static func shown(title: String, named: Bool) -> String? { let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) return named && !trimmed.isEmpty ? trimmed : nil } /// The window's title: the meeting's, named or not, and the app's name /// before a meeting has said what it is called. public static func window(title: String) -> String { let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.isEmpty ? "Calls" : trimmed } } /// A notice's own button (`CallNotice.action`): a compact light capsule /// that reads on the dark glass, reachable from the keyboard, where /// Return as well as Space presses it. public struct NoticeActionButton: View { let action: CallNotice.Action let perform: () -> Void @FocusState private var focused: Bool public init(_ action: CallNotice.Action, perform: @escaping () -> Void) { self.action = action self.perform = perform } public var body: some View { switch action { case .stopSharing: capsule("Stop sharing", label: "Stop sharing your screen", id: "stopSharingInline") case .reportProblem: capsule(ProblemWords.title, label: ProblemWords.title, id: "reportProblem") } } private func capsule(_ title: String, label: String, id: String) -> some View { Button(action: perform) { Text(title).font(.callout.weight(.semibold)) .padding(.horizontal, 12).padding(.vertical, 4) .foregroundStyle(Color.black) .background(Capsule().fill(Color.white.opacity(focused ? 1 : 0.92))) .overlay(Capsule().strokeBorder(Color.white, lineWidth: focused ? 2 : 0).padding(-3)) .contentShape(Capsule()) } .buttonStyle(.plain) .focusable() .focused($focused) .onKeyPress(.return) { perform() return .handled } .accessibilityLabel(label) .accessibilityIdentifier(id) } } extension Call { /// Runs a notice's own action (see `CallNotice.action`). public func perform(_ action: CallNotice.Action) { switch action { case .stopSharing: stopSharingScreen() case .reportProblem: reportProblem() } } } // MARK: - Grid /// How a grid of tiles fills a stage without scrolling. public enum GridFit { /// The column count that makes `count` tiles of `aspect` (width over /// height) as large as they can be in `size`, `spacing` apart. public static func columns(count: Int, in size: CGSize, aspect: CGFloat, spacing: CGFloat = 4) -> Int { guard count > 1, size.width > 0, size.height > 0 else { return 1 } var best = 1 var bestWidth: CGFloat = 0 for columns in 1...count { let rows = (count + columns - 1) / columns let width = tileWidth(columns: columns, rows: rows, in: size, aspect: aspect, spacing: spacing) if width > bestWidth + 0.5 { best = columns bestWidth = width } } return best } /// The tile size for `count` tiles in `columns` columns. public static func tile(count: Int, columns: Int, in size: CGSize, aspect: CGFloat, spacing: CGFloat = 4) -> CGSize { let rows = (max(count, 1) + max(columns, 1) - 1) / max(columns, 1) let width = tileWidth( columns: max(columns, 1), rows: rows, in: size, aspect: aspect, spacing: spacing) return CGSize(width: width, height: width / aspect) } private static func tileWidth( columns: Int, rows: Int, in size: CGSize, aspect: CGFloat, spacing: CGFloat ) -> CGFloat { let across = (size.width - CGFloat(columns - 1) * spacing) / CGFloat(columns) let down = (size.height - CGFloat(rows - 1) * spacing) / CGFloat(rows) return max(0, min(across, down * aspect)) } } // MARK: - Camera flip public enum CameraFlip { /// The camera "Flip camera" moves to: from the built-in (front) camera /// to the first other one, and from any other back to the built-in — /// front to back and back to front on an iPhone. Nil with nothing to /// flip to. public static func next(from current: String?, in cameras: [CameraDevice]) -> CameraDevice? { guard cameras.count > 1 else { return nil } guard let current, let now = cameras.first(where: { $0.id == current }) else { return cameras.first } if let other = cameras.first(where: { $0.builtIn != now.builtIn }) { return other } let index = cameras.firstIndex(of: now) ?? 0 return cameras[(index + 1) % cameras.count] } }