Repository Public License
1import CoreGraphics2import Foundation3import NavigatorCore45public enum SplitError: Error, Sendable, Equatable {6 /// The device cannot show more panes (see `SplitCapacity`).7 case paneLimitReached(limit: Int)8 case tabAlreadyInSplit9 case paneOutOfRange10 case dividerOutOfRange11}1213/// The kind of device, as far as Split is concerned.14public enum SplitPlatform: Sendable, Equatable {15 case mac16 /// iPad. `isRegularWidth`: the window has a regular horizontal size class (not Slide Over, not a narrow17 /// Split View / Stage Manager window).18 case pad(isRegularWidth: Bool)19 case phone20}2122/// How many panes a window may show. These are product limits chosen to keep each pane usable and the number23/// of simultaneously visible (therefore never suspended) web views compatible with the device's memory; they24/// are documented in docs/ORBIT.md and are not the result of a measurement campaign.25public enum SplitCapacity {26 /// - iPhone: 1 pane (no Split; the UI offers a quick switch between the two most recent tabs instead).27 /// - iPad, compact width: 2. iPad, regular width: 3, or 2 below 6 GB of physical memory.28 /// - Mac: 8 from 24 GB, 6 from 16 GB, 4 below.29 public static func maximumPanes(platform: SplitPlatform, physicalMemoryBytes: UInt64) -> Int {30 let gigabytes = Double(physicalMemoryBytes) / 1_073_741_82431 switch platform {32 case .phone: return 133 case .pad(let isRegularWidth): return isRegularWidth && gigabytes >= 6 ? 3 : 234 // Thresholds sit slightly under the nominal size: a "16 GB" Mac reports exactly 16 GiB, but virtual35 // machines and future configurations may report a little less.36 case .mac: return gigabytes >= 23.5 ? 8 : gigabytes >= 15.5 ? 6 : 437 }38 }3940 /// The platform this process runs on. On iPadOS the caller should pass the real size class instead.41 public static var currentPlatform: SplitPlatform {42 #if os(macOS)43 return .mac44 #else45 // "iPad" is the model prefix of every iPad, including when an iPhone-only build would run on it.46 var info = utsname()47 uname(&info)48 let machine = withUnsafeBytes(of: &info.machine) { raw in49 String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)50 }51 if machine.hasPrefix("iPad") { return .pad(isRegularWidth: true) }52 if machine.hasPrefix("iPhone") || machine.hasPrefix("iPod") { return .phone }53 // Simulator and "Designed for iPad" on Mac report the host architecture: use the idiom-neutral default.54 return ProcessInfo.processInfo.isiOSAppOnMac ? .mac : .pad(isRegularWidth: true)55 #endif56 }5758 public static func maximumPanesOnThisDevice(platform: SplitPlatform = currentPlatform) -> Int {59 maximumPanes(platform: platform, physicalMemoryBytes: ProcessInfo.processInfo.physicalMemory)60 }61}6263/// A draggable separator between two panes.64public struct SplitDivider: Sendable, Equatable {65 /// Index of the pane before the divider; the pane after it is `leading + 1`.66 public var leading: Int67 public var rect: CGRect68 /// `true` when the divider is a vertical bar (dragged horizontally).69 public var isVertical: Bool70}7172/// Operations on `SplitLayout`. All pure: they return a new layout and never touch storage.73///74/// Meaning of `fractions` per axis:75/// - `.horizontal`: panes side by side, `fractions` are widths.76/// - `.vertical`: panes stacked, `fractions` are heights.77/// - `.grid`: panes fill rows (`gridRows`). Rows have equal heights; inside a row each pane's width is its78/// fraction divided by the sum of the row's fractions.79public enum SplitEngine {80 public static let defaultMinimumPaneLength: Double = 2408182 // MARK: Building8384 /// Starts a split from the selected tab and a second one, or adds `tab` to an existing split after the85 /// focused pane (or at `index`). The new pane takes half of the pane it is inserted next to.86 public static func adding(_ tab: TabID, to layout: SplitLayout?, selected: TabID, at index: Int? = nil,87 limit: Int = SplitLayout.maximumPanes) throws(SplitError) -> SplitLayout {88 let limit = min(limit, SplitLayout.maximumPanes)89 guard let layout, layout.panes.count >= 2 else {90 guard tab != selected else { throw .tabAlreadyInSplit }91 guard limit >= 2 else { throw .paneLimitReached(limit: limit) }92 return SplitLayout(axis: layout?.axis ?? .horizontal, panes: [selected, tab], focusedPane: 1)93 }94 guard !layout.panes.contains(tab) else { throw .tabAlreadyInSplit }95 guard layout.panes.count < limit else { throw .paneLimitReached(limit: limit) }96 let position = min(max(index ?? layout.focusedPane + 1, 0), layout.panes.count)97 let donor = min(max(position - 1, 0), layout.panes.count - 1)98 var panes = layout.panes, fractions = layout.fractions99 let half = fractions[donor] / 2100 fractions[donor] = half101 panes.insert(tab, at: position)102 fractions.insert(half, at: position)103 return SplitLayout(axis: layout.axis, panes: panes, fractions: fractions, focusedPane: position)104 }105106 /// Removes the pane showing `tab`. Returns `nil` when fewer than two panes remain: the split ends and the107 /// window shows a single tab again. The freed space goes to the neighbours proportionally.108 public static func removing(_ tab: TabID, from layout: SplitLayout) -> SplitLayout? {109 guard let index = layout.panes.firstIndex(of: tab) else { return layout.isValid ? layout : nil }110 var panes = layout.panes, fractions = layout.fractions111 panes.remove(at: index)112 fractions.remove(at: index)113 guard panes.count >= 2 else { return nil }114 let focused = layout.focusedPane > index ? layout.focusedPane - 1 : min(layout.focusedPane, panes.count - 1)115 return SplitLayout(axis: layout.axis, panes: panes, fractions: fractions, focusedPane: focused)116 }117118 /// Shows `tab` in the pane at `index`. If `tab` is already in another pane the two panes swap.119 public static func replacing(paneAt index: Int, with tab: TabID, in layout: SplitLayout) throws(SplitError) -> SplitLayout {120 guard layout.panes.indices.contains(index) else { throw .paneOutOfRange }121 var panes = layout.panes122 if let other = panes.firstIndex(of: tab), other != index { panes[other] = panes[index] }123 panes[index] = tab124 return SplitLayout(axis: layout.axis, panes: panes, fractions: layout.fractions, focusedPane: layout.focusedPane)125 }126127 /// Moves a pane to another position, keeping its size.128 public static func moving(paneAt source: Int, to destination: Int, in layout: SplitLayout) throws(SplitError) -> SplitLayout {129 guard layout.panes.indices.contains(source), layout.panes.indices.contains(destination) else { throw .paneOutOfRange }130 var panes = layout.panes, fractions = layout.fractions131 let focusedTab = panes[layout.focusedPane]132 panes.insert(panes.remove(at: source), at: destination)133 fractions.insert(fractions.remove(at: source), at: destination)134 return SplitLayout(axis: layout.axis, panes: panes, fractions: fractions,135 focusedPane: panes.firstIndex(of: focusedTab) ?? 0)136 }137138 public static func changingAxis(of layout: SplitLayout, to axis: SplitLayout.Axis) -> SplitLayout {139 SplitLayout(axis: axis, panes: layout.panes, fractions: layout.fractions, focusedPane: layout.focusedPane)140 }141142 /// Gives every pane the same size.143 public static func equalized(_ layout: SplitLayout) -> SplitLayout {144 SplitLayout(axis: layout.axis, panes: layout.panes, focusedPane: layout.focusedPane)145 }146147 // MARK: Focus148149 public static func focusingNext(_ layout: SplitLayout) -> SplitLayout { focusing(layout, offset: 1) }150 public static func focusingPrevious(_ layout: SplitLayout) -> SplitLayout { focusing(layout, offset: -1) }151152 private static func focusing(_ layout: SplitLayout, offset: Int) -> SplitLayout {153 guard !layout.panes.isEmpty else { return layout }154 var copy = layout155 copy.focusedPane = ((layout.focusedPane + offset) % layout.panes.count + layout.panes.count) % layout.panes.count156 return copy157 }158159 public static func focusing(paneAt index: Int, in layout: SplitLayout) throws(SplitError) -> SplitLayout {160 guard layout.panes.indices.contains(index) else { throw .paneOutOfRange }161 var copy = layout162 copy.focusedPane = index163 return copy164 }165166 public static func focusedTab(of layout: SplitLayout) -> TabID? {167 layout.panes.indices.contains(layout.focusedPane) ? layout.panes[layout.focusedPane] : nil168 }169170 // MARK: Restoring171172 /// Validates a layout read from storage against the tabs that still exist and the device limit: panes whose173 /// tab is gone are dropped, duplicates are removed, extra panes beyond `limit` are dropped from the end,174 /// fractions are renormalised. `nil` when fewer than two panes survive.175 public static func restored(_ layout: SplitLayout?, existingTabs: Set<TabID>,176 limit: Int = SplitLayout.maximumPanes) -> SplitLayout? {177 guard let layout, limit >= 2 else { return nil }178 let focusedTab = focusedTab(of: layout)179 var seen = Set<TabID>()180 var panes: [TabID] = [], fractions: [Double] = []181 for (index, tab) in layout.panes.enumerated() where existingTabs.contains(tab) && seen.insert(tab).inserted {182 guard panes.count < min(limit, SplitLayout.maximumPanes) else { break }183 panes.append(tab)184 let fraction = index < layout.fractions.count ? layout.fractions[index] : 0185 fractions.append(fraction.isFinite && fraction > 0 ? fraction : 0)186 }187 guard panes.count >= 2 else { return nil }188 // Nothing to repair: return the stored value untouched (renormalising would move fractions by an ulp).189 if panes == layout.panes, layout.isValid, layout.fractions.count == panes.count, !fractions.contains(0),190 abs(fractions.reduce(0, +) - 1) < 1e-9, layout.panes.indices.contains(layout.focusedPane) {191 return layout192 }193 // A stored layout with unusable fractions falls back to equal sizes (the initialiser does it).194 return SplitLayout(axis: layout.axis, panes: panes, fractions: fractions.contains(0) ? nil : fractions,195 focusedPane: focusedTab.flatMap(panes.firstIndex(of:)) ?? 0)196 }197198 // MARK: Geometry199200 /// Rows of the grid arrangement, as counts of panes per row: 2 → [2], 3 → [2, 1], 4 → [2, 2], 5 → [3, 2],201 /// 6 → [3, 3], 7 → [4, 3], 8 → [4, 4]. In a container clearly taller than wide (portrait) the same counts202 /// are used as columns instead, see `paneRects`.203 public static func gridRows(paneCount: Int) -> [Int] {204 guard paneCount > 2 else { return paneCount > 0 ? [paneCount] : [] }205 let top = (paneCount + 1) / 2206 return [top, paneCount - top]207 }208209 static func isPortrait(_ size: CGSize) -> Bool { size.height > size.width * 1.2 }210211 /// Pane index ranges of each line (row, or column in portrait) of the grid.212 static func gridLines(paneCount: Int) -> [Range<Int>] {213 var start = 0214 return gridRows(paneCount: paneCount).map { count in215 defer { start += count }216 return start..<(start + count)217 }218 }219220 /// Lengths of segments sharing `total` according to `weights`, with `spacing` between them.221 private static func segments(total: Double, weights: [Double], spacing: Double) -> [(origin: Double, length: Double)] {222 let usable = max(total - spacing * Double(max(weights.count - 1, 0)), 0)223 let sum = weights.reduce(0, +)224 var origin = 0.0225 return weights.map { weight in226 let length = sum > 0 ? usable * weight / sum : usable / Double(max(weights.count, 1))227 defer { origin += length + spacing }228 return (origin, length)229 }230 }231232 /// Frame of every pane, in pane order, for a container of `size`. `spacing` is the divider thickness.233 public static func paneRects(for layout: SplitLayout, in size: CGSize, spacing: Double = 1) -> [CGRect] {234 guard !layout.panes.isEmpty else { return [] }235 switch layout.axis {236 case .horizontal:237 return segments(total: size.width, weights: layout.fractions, spacing: spacing).map {238 CGRect(x: $0.origin, y: 0, width: $0.length, height: size.height)239 }240 case .vertical:241 return segments(total: size.height, weights: layout.fractions, spacing: spacing).map {242 CGRect(x: 0, y: $0.origin, width: size.width, height: $0.length)243 }244 case .grid:245 let lines = gridLines(paneCount: layout.panes.count)246 let portrait = isPortrait(size)247 let across = segments(total: portrait ? size.width : size.height,248 weights: Array(repeating: 1, count: lines.count), spacing: spacing)249 var rects = [CGRect](repeating: .zero, count: layout.panes.count)250 for (line, range) in lines.enumerated() {251 let along = segments(total: portrait ? size.height : size.width,252 weights: Array(layout.fractions[range]), spacing: spacing)253 for (offset, index) in range.enumerated() {254 rects[index] = portrait255 ? CGRect(x: across[line].origin, y: along[offset].origin, width: across[line].length, height: along[offset].length)256 : CGRect(x: along[offset].origin, y: across[line].origin, width: along[offset].length, height: across[line].length)257 }258 }259 return rects260 }261 }262263 /// Indices `i` such that a divider sits between panes `i` and `i + 1`.264 public static func dividerIndices(for layout: SplitLayout) -> [Int] {265 switch layout.axis {266 case .horizontal, .vertical: return Array(0..<max(layout.panes.count - 1, 0))267 case .grid: return gridLines(paneCount: layout.panes.count).flatMap { Array($0.dropLast()) }268 }269 }270271 /// Draggable dividers with their hit rectangles (`hitThickness` wide, centred on the gap).272 public static func dividers(for layout: SplitLayout, in size: CGSize, spacing: Double = 1,273 hitThickness: Double = 8) -> [SplitDivider] {274 let rects = paneRects(for: layout, in: size, spacing: spacing)275 let vertical: Bool276 switch layout.axis {277 case .horizontal: vertical = true278 case .vertical: vertical = false279 case .grid: vertical = !isPortrait(size)280 }281 return dividerIndices(for: layout).map { index in282 let pane = rects[index]283 let rect = vertical284 ? CGRect(x: pane.maxX + spacing / 2 - hitThickness / 2, y: pane.minY, width: hitThickness, height: pane.height)285 : CGRect(x: pane.minX, y: pane.maxY + spacing / 2 - hitThickness / 2, width: pane.width, height: hitThickness)286 return SplitDivider(leading: index, rect: rect, isVertical: vertical)287 }288 }289290 /// Moves the divider after pane `leading` by `delta` points (positive = towards the trailing pane), in a291 /// container of `size`. Only the two panes next to the divider change; neither goes below292 /// `minimumLength` points (when the two together are smaller than twice the minimum, they split evenly).293 public static func resizing(_ layout: SplitLayout, dividerAfter leading: Int, by delta: Double, in size: CGSize,294 minimumLength: Double = defaultMinimumPaneLength,295 spacing: Double = 1) throws(SplitError) -> SplitLayout {296 guard dividerIndices(for: layout).contains(leading) else { throw .dividerOutOfRange }297 let rects = paneRects(for: layout, in: size, spacing: spacing)298 let alongWidth: Bool299 switch layout.axis {300 case .horizontal: alongWidth = true301 case .vertical: alongWidth = false302 case .grid: alongWidth = !isPortrait(size)303 }304 let first = alongWidth ? rects[leading].width : rects[leading].height305 let second = alongWidth ? rects[leading + 1].width : rects[leading + 1].height306 let pair = first + second307 guard pair > 0, delta.isFinite else { return layout }308 let minimum = min(minimumLength, pair / 2)309 let newFirst = min(max(first + delta, minimum), pair - minimum)310 var fractions = layout.fractions311 let pairFraction = fractions[leading] + fractions[leading + 1]312 fractions[leading] = pairFraction * newFirst / pair313 fractions[leading + 1] = pairFraction - fractions[leading]314 guard fractions[leading] > 0, fractions[leading + 1] > 0 else { return layout }315 return SplitLayout(axis: layout.axis, panes: layout.panes, fractions: fractions, focusedPane: layout.focusedPane)316 }317318 /// Pane under a point, for drops and clicks.319 public static func pane(at point: CGPoint, layout: SplitLayout, in size: CGSize, spacing: Double = 1) -> Int? {320 paneRects(for: layout, in: size, spacing: spacing).firstIndex { $0.contains(point) }321 }322}323