SPB Git

Repository Public License

OrbitalLayout.swift 19.6 KB 387 lines swift

1import CoreGraphics2import Foundation3import NavigatorCore45/// Shape of the orbital view, in logical points at zoom 1. Rings are concentric circles seen under a tilt, so6/// they project to ellipses: a point at angle `a` on a ring of radius `r` lands at7/// `(cx + r·cos a, cy + r·sin a·cos tilt)`. Angles are in radians, 0 = right, growing clockwise on screen8/// (y points down), so `-π/2` is the top of a ring.9public struct OrbitalMetrics: Sendable, Equatable {10    /// Radius of ring 0.11    public var firstRingRadius: Double12    /// Distance between two consecutive rings.13    public var ringSpacing: Double14    /// Diameter of a satellite at depth 0 (left and right ends of a ring).15    public var satelliteDiameter: Double16    /// Free space kept between two satellites.17    public var minimumGap: Double18    /// Tilt of the orbital plane, 0 (seen from above, circles) to less than π/2 (edge-on).19    public var tilt: Double20    /// Relative size change between the back (top) and the front (bottom) of a ring: a satellite is drawn at21    /// `1 + depthScale · depth`, depth in -1...1.22    public var depthScale: Double23    /// Highest ring index the layout will use.24    public var maximumRing: Int2526    public init(firstRingRadius: Double = 150, ringSpacing: Double = 110, satelliteDiameter: Double = 56,27                minimumGap: Double = 18, tilt: Double = 0.45, depthScale: Double = 0.12, maximumRing: Int = 7) {28        self.firstRingRadius = max(firstRingRadius, 1)29        self.ringSpacing = max(ringSpacing, 1)30        self.satelliteDiameter = max(satelliteDiameter, 1)31        self.minimumGap = max(minimumGap, 0)32        self.tilt = min(max(tilt, 0), 1.4)33        self.depthScale = min(max(depthScale, 0), 0.5)34        self.maximumRing = max(maximumRing, 0)35    }3637    public static let standard = OrbitalMetrics()3839    /// Vertical squash of the rings.40    public var verticalScale: Double { cos(tilt) }4142    public func radius(ofRing ring: Int) -> Double { firstRingRadius + Double(max(ring, 0)) * ringSpacing }4344    /// Largest drawn diameter of a satellite (front of the ring).45    var largestDiameter: Double { satelliteDiameter * (1 + depthScale) }4647    /// Smallest angle between two satellites of a ring that keeps them apart *on screen* wherever they sit.48    ///49    /// Two points of a ring separated by a chord `c` are at least `c·cos tilt` apart once projected (the50    /// projection only shrinks the vertical component), so requiring `2r·sin(Δ/2)·cos tilt ≥ diameter + gap`51    /// is sufficient at every angle.52    public func minimumSeparation(onRing ring: Int) -> Double {53        let needed = (largestDiameter + minimumGap) / (2 * radius(ofRing: ring) * verticalScale)54        return needed >= 1 ? 2 * .pi : 2 * asin(needed)55    }5657    /// How many satellites fit on a ring without overlap (at least 1).58    public func capacity(ofRing ring: Int) -> Int {59        // The epsilon keeps a separation that divides the circle exactly from losing a slot to rounding.60        max(1, Int((2 * .pi / minimumSeparation(onRing: ring)) + 1e-9))61    }62}6364/// Where and how the orbital view is drawn.65public struct OrbitalViewport: Sendable, Equatable {66    public var size: CGSize67    /// 1 = logical points. Clamped to `OrbitalViewport.zoomRange`.68    public var zoom: Double69    /// Pan offset of the core from the centre of the viewport, in screen points.70    public var offset: CGSize7172    public static let zoomRange: ClosedRange<Double> = 0.25...47374    public init(size: CGSize, zoom: Double = 1, offset: CGSize = .zero) {75        self.size = size76        self.zoom = min(max(zoom.isFinite ? zoom : 1, Self.zoomRange.lowerBound), Self.zoomRange.upperBound)77        self.offset = offset78    }7980    public var center: CGPoint { CGPoint(x: size.width / 2 + offset.width, y: size.height / 2 + offset.height) }81}8283/// A space placed in the orbital view.84public struct Satellite: Sendable, Equatable, Identifiable {85    public var id: SpaceID86    public var ring: Int87    /// Normalised to `-π ..< π`.88    public var angle: Double89    public var center: CGPoint90    /// Drawn diameter, depth and zoom applied.91    public var diameter: Double92    /// -1 (back, top of the ring) to 1 (front, bottom). Draw in increasing depth.93    public var depth: Double9495    public var frame: CGRect {96        CGRect(x: center.x - diameter / 2, y: center.y - diameter / 2, width: diameter, height: diameter)97    }98}99100/// The ellipse a ring projects to.101public struct OrbitRingPath: Sendable, Equatable {102    public var ring: Int103    public var center: CGPoint104    public var horizontalRadius: Double105    public var verticalRadius: Double106    public var rect: CGRect {107        CGRect(x: center.x - horizontalRadius, y: center.y - verticalRadius,108               width: horizontalRadius * 2, height: verticalRadius * 2)109    }110}111112/// A position on the orbit: what `OrbitSpace.ring` and `OrbitSpace.angle` store.113public struct OrbitSlot: Sendable, Hashable {114    public var ring: Int115    public var angle: Double116    public init(ring: Int, angle: Double) { self.ring = max(ring, 0); self.angle = OrbitalLayout.normalized(angle) }117}118119public struct OrbitDragResult: Sendable, Equatable {120    public var slot: OrbitSlot121    /// The angle was pulled onto the ring's regular grid.122    public var snappedToGrid: Bool123    /// The requested position was taken and the satellite was moved to the nearest free one.124    public var displaced: Bool125}126127/// Pure geometry of the orbital view. Every function is deterministic: same input, same output.128public enum OrbitalLayout {129    // MARK: Angles130131    /// Maps any angle to `-π ..< π`.132    public static func normalized(_ angle: Double) -> Double {133        guard angle.isFinite else { return 0 }134        var value = (angle + .pi).truncatingRemainder(dividingBy: 2 * .pi)135        if value < 0 { value += 2 * .pi }136        return value - .pi137    }138139    /// Smallest absolute difference between two angles, in `0...π`.140    public static func angularDistance(_ a: Double, _ b: Double) -> Double { abs(normalized(a - b)) }141142    /// Angle measured clockwise from the top of the ring, in `0 ..< 2π`: the reading order of a ring.143    public static func clockwiseFromTop(_ angle: Double) -> Double {144        var value = normalized(angle) + .pi / 2145        if value < 0 { value += 2 * .pi }146        return value147    }148149    // MARK: Projection150151    public static func position(ring: Int, angle: Double, metrics: OrbitalMetrics = .standard,152                                viewport: OrbitalViewport) -> CGPoint {153        let radius = metrics.radius(ofRing: ring) * viewport.zoom154        let center = viewport.center155        return CGPoint(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle) * metrics.verticalScale)156    }157158    public static func satellite(for space: OrbitSpace, metrics: OrbitalMetrics = .standard,159                                 viewport: OrbitalViewport) -> Satellite {160        let ring = min(max(space.ring, 0), metrics.maximumRing)161        let angle = normalized(space.angle)162        let depth = sin(angle)163        return Satellite(id: space.id, ring: ring, angle: angle,164                         center: position(ring: ring, angle: angle, metrics: metrics, viewport: viewport),165                         diameter: metrics.satelliteDiameter * (1 + metrics.depthScale * depth) * viewport.zoom,166                         depth: depth)167    }168169    /// Satellites of the non-archived spaces, back to front (painter's order). Ties are broken by ring then id170    /// so the order never flickers between two frames.171    public static func satellites(for spaces: [OrbitSpace], metrics: OrbitalMetrics = .standard,172                                  viewport: OrbitalViewport) -> [Satellite] {173        spaces.filter { !$0.isArchived }174            .map { satellite(for: $0, metrics: metrics, viewport: viewport) }175            .sorted { ($0.depth, $0.ring, $0.id) < ($1.depth, $1.ring, $1.id) }176    }177178    /// The ellipses to draw for rings `0...highest` (highest used ring, or `upTo` when given).179    public static func ringPaths(for spaces: [OrbitSpace], upTo: Int? = nil, metrics: OrbitalMetrics = .standard,180                                 viewport: OrbitalViewport) -> [OrbitRingPath] {181        let used = spaces.filter { !$0.isArchived }.map(\.ring).max() ?? 0182        let highest = min(max(upTo ?? used, 0), metrics.maximumRing)183        return (0...highest).map { ring in184            let radius = metrics.radius(ofRing: ring) * viewport.zoom185            return OrbitRingPath(ring: ring, center: viewport.center, horizontalRadius: radius,186                                 verticalRadius: radius * metrics.verticalScale)187        }188    }189190    /// Zoom at which rings `0...ring` and their satellites fit entirely in a viewport of `size`.191    public static func zoomToFit(ring: Int, in size: CGSize, metrics: OrbitalMetrics = .standard,192                                 padding: Double = 24) -> Double {193        let radius = metrics.radius(ofRing: ring)194        let halfWidth = radius + metrics.largestDiameter / 2195        let halfHeight = radius * metrics.verticalScale + metrics.largestDiameter / 2196        let horizontal = (size.width / 2 - padding) / halfWidth197        let vertical = (size.height / 2 - padding) / halfHeight198        let zoom = min(horizontal, vertical)199        return min(max(zoom.isFinite && zoom > 0 ? zoom : OrbitalViewport.zoomRange.lowerBound,200                       OrbitalViewport.zoomRange.lowerBound), OrbitalViewport.zoomRange.upperBound)201    }202203    // MARK: Hit-testing204205    /// The space under `point`, the front-most one when several overlap. `slop` enlarges every target (touch).206    public static func hitTest(_ point: CGPoint, spaces: [OrbitSpace], metrics: OrbitalMetrics = .standard,207                               viewport: OrbitalViewport, slop: Double = 0) -> SpaceID? {208        for satellite in satellites(for: spaces, metrics: metrics, viewport: viewport).reversed() {209            let reach = satellite.diameter / 2 + slop210            let dx = point.x - satellite.center.x, dy = point.y - satellite.center.y211            if dx * dx + dy * dy <= reach * reach { return satellite.id }212        }213        return nil214    }215216    /// Ring and angle under a screen point (inverse of the projection). The ring is the nearest one.217    public static func slot(at point: CGPoint, metrics: OrbitalMetrics = .standard,218                            viewport: OrbitalViewport) -> OrbitSlot {219        let center = viewport.center220        let dx = (point.x - center.x) / viewport.zoom221        let dy = (point.y - center.y) / (viewport.zoom * metrics.verticalScale)222        let distance = (dx * dx + dy * dy).squareRoot()223        let ring = Int(((distance - metrics.firstRingRadius) / metrics.ringSpacing).rounded())224        let angle = distance < 1e-9 ? -Double.pi / 2 : atan2(dy, dx)225        return OrbitSlot(ring: min(max(ring, 0), metrics.maximumRing), angle: angle)226    }227228    // MARK: Placement229230    private static func occupants(of ring: Int, in spaces: [OrbitSpace], excluding: SpaceID?) -> [Double] {231        spaces.filter { !$0.isArchived && $0.ring == ring && $0.id != excluding }.map { normalized($0.angle) }.sorted()232    }233234    static func isFree(_ angle: Double, among occupants: [Double], separation: Double) -> Bool {235        // The tolerance lets a satellite sit exactly one separation away from its neighbour.236        occupants.allSatisfy { angularDistance($0, angle) >= separation - 1e-9 }237    }238239    /// Free angle of `ring` closest to `preferred`, or `nil` when the ring has no room left.240    static func nearestFreeAngle(to preferred: Double, occupants: [Double], separation: Double) -> Double? {241        if isFree(preferred, among: occupants, separation: separation) { return normalized(preferred) }242        var best: (angle: Double, distance: Double)?243        for occupant in occupants {244            for candidate in [occupant + separation, occupant - separation]245            where isFree(candidate, among: occupants, separation: separation) {246                let distance = angularDistance(candidate, preferred)247                // Strict comparison + sorted occupants: the first candidate wins ties, deterministically.248                if best == nil || distance < best!.distance - 1e-12 { best = (normalized(candidate), distance) }249            }250        }251        return best?.angle252    }253254    /// Position for a new space: the innermost ring with room, in the middle of its widest gap (the top of the255    /// ring when it is empty). Never overlaps an existing satellite.256    ///257    /// A ring "has room" when its widest gap can take a satellite in its middle. Because existing satellites258    /// are never moved, a ring can therefore be left before its nominal `capacity` is reached (three satellites259    /// placed by halving gaps do not leave a fourth gap wide enough on a ring of capacity 4); `evenSlots` is260    /// the arrangement that reaches the capacity. Returns `nil` when no ring up to `metrics.maximumRing` has room.261    public static func placement(forNewSpaceAmong spaces: [OrbitSpace], metrics: OrbitalMetrics = .standard) -> OrbitSlot? {262        for ring in 0...metrics.maximumRing {263            let taken = occupants(of: ring, in: spaces, excluding: nil)264            if taken.isEmpty { return OrbitSlot(ring: ring, angle: -.pi / 2) }265            guard taken.count < metrics.capacity(ofRing: ring) else { continue }266            let separation = metrics.minimumSeparation(onRing: ring)267            var widest: (start: Double, width: Double)?268            for (index, start) in taken.enumerated() {269                let next = index + 1 < taken.count ? taken[index + 1] : taken[0] + 2 * .pi270                let width = next - start271                if widest == nil || width > widest!.width + 1e-12 { widest = (start, width) }272            }273            if let widest, widest.width >= 2 * separation - 1e-9 {274                return OrbitSlot(ring: ring, angle: widest.start + widest.width / 2)275            }276        }277        return nil278    }279280    /// Regular arrangement of `count` satellites: rings are filled from the inside, each ring's satellites are281    /// evenly spread starting at the top. Used by "tidy up" and for the first layout of imported spaces.282    public static func evenSlots(count: Int, metrics: OrbitalMetrics = .standard) -> [OrbitSlot] {283        var slots: [OrbitSlot] = []284        var remaining = max(count, 0)285        var ring = 0286        while remaining > 0, ring <= metrics.maximumRing {287            let onRing = min(remaining, metrics.capacity(ofRing: ring))288            for index in 0..<onRing {289                slots.append(OrbitSlot(ring: ring, angle: -.pi / 2 + 2 * .pi * Double(index) / Double(onRing)))290            }291            remaining -= onRing292            ring += 1293        }294        return slots295    }296297    /// Total number of spaces the orbital view can show without overlap.298    public static func totalCapacity(metrics: OrbitalMetrics = .standard) -> Int {299        (0...metrics.maximumRing).reduce(0) { $0 + metrics.capacity(ofRing: $1) }300    }301302    // MARK: Dragging303304    /// Where a dragged satellite lands when released at `point`.305    ///306    /// The ring is the nearest one. The angle snaps to the ring's regular grid (`capacity` evenly spaced307    /// positions, one of them at the top) when the pointer is within a quarter of a grid step of a grid308    /// position; otherwise it stays where the user put it. If that position would overlap another satellite,309    /// the nearest free angle of the ring is used, then the nearest ring with room.310    public static func drop(_ id: SpaceID, at point: CGPoint, spaces: [OrbitSpace],311                            metrics: OrbitalMetrics = .standard, viewport: OrbitalViewport) -> OrbitDragResult {312        let raw = slot(at: point, metrics: metrics, viewport: viewport)313        let step = 2 * Double.pi / Double(metrics.capacity(ofRing: raw.ring))314        let offsetFromTop = raw.angle + .pi / 2315        let gridAngle = (offsetFromTop / step).rounded() * step - .pi / 2316        let snaps = angularDistance(gridAngle, raw.angle) <= step / 4317        let wanted = snaps ? normalized(gridAngle) : raw.angle318319        // Nearest ring first, then alternately outwards and inwards.320        var rings = [raw.ring]321        for distance in 1...max(metrics.maximumRing, 1) {322            if raw.ring + distance <= metrics.maximumRing { rings.append(raw.ring + distance) }323            if raw.ring - distance >= 0 { rings.append(raw.ring - distance) }324        }325        for ring in rings {326            let taken = occupants(of: ring, in: spaces, excluding: id)327            let separation = metrics.minimumSeparation(onRing: ring)328            if let angle = nearestFreeAngle(to: wanted, occupants: taken, separation: separation) {329                let displaced = ring != raw.ring || angularDistance(angle, wanted) > 1e-9330                return OrbitDragResult(slot: OrbitSlot(ring: ring, angle: angle),331                                       snappedToGrid: snaps && !displaced, displaced: displaced)332            }333        }334        // Every ring is full: leave the satellite where it was.335        let current = spaces.first { $0.id == id }336        return OrbitDragResult(slot: OrbitSlot(ring: current?.ring ?? raw.ring, angle: current?.angle ?? wanted),337                               snappedToGrid: false, displaced: true)338    }339340    /// Pairs of non-archived spaces whose satellites overlap on screen (data written by an older build, a sync341    /// merge or an import can contain some). Empty for anything produced by `placement` and `drop`.342    public static func overlaps(in spaces: [OrbitSpace], metrics: OrbitalMetrics = .standard) -> [(SpaceID, SpaceID)] {343        let viewport = OrbitalViewport(size: .zero)344        let placed = spaces.filter { !$0.isArchived }.map { satellite(for: $0, metrics: metrics, viewport: viewport) }345            .sorted { $0.id < $1.id }346        var result: [(SpaceID, SpaceID)] = []347        for (index, first) in placed.enumerated() {348            for second in placed[(index + 1)...] {349                let dx = first.center.x - second.center.x, dy = first.center.y - second.center.y350                let reach = (first.diameter + second.diameter) / 2351                if dx * dx + dy * dy < reach * reach - 1e-9 { result.append((first.id, second.id)) }352            }353        }354        return result355    }356357    // MARK: Accessible equivalents358359    /// Order of the accessible list: the user's own order (`order`, then creation date, then id). Archived360    /// spaces are left out. This is the order VoiceOver, the keyboard and the sidebar use.361    public static func listOrder(_ spaces: [OrbitSpace]) -> [OrbitSpace] {362        spaces.filter { !$0.isArchived }.sorted {363            ($0.order, $0.createdAt, $0.id) < ($1.order, $1.createdAt, $1.id)364        }365    }366367    /// Order that follows what is on screen: ring by ring from the core, clockwise from the top of each ring.368    /// Used for arrow-key navigation inside the orbital view.369    public static func spatialOrder(_ spaces: [OrbitSpace]) -> [OrbitSpace] {370        spaces.filter { !$0.isArchived }.sorted {371            ($0.ring, clockwiseFromTop($0.angle), $0.id) < ($1.ring, clockwiseFromTop($1.angle), $1.id)372        }373    }374375    /// Frames of the grid equivalent (same order as `listOrder`), filling rows left to right.376    public static func gridFrames(count: Int, width: Double, minimumCellWidth: Double = 160, cellHeight: Double = 120,377                                  spacing: Double = 16) -> [CGRect] {378        guard count > 0, width > 0 else { return [] }379        let columns = max(1, Int((width + spacing) / (minimumCellWidth + spacing)))380        let cellWidth = (width - spacing * Double(columns - 1)) / Double(columns)381        return (0..<count).map { index in382            CGRect(x: Double(index % columns) * (cellWidth + spacing), y: Double(index / columns) * (cellHeight + spacing),383                   width: cellWidth, height: cellHeight)384        }385    }386}387
Files main
Menu

Theme