Repository Public License
1// CanvasEngine — geometry shared by the editor, the hit-tester, the router and the culling index.2import Foundation3import NavigatorCore45/// An axis-aligned rectangle in canvas coordinates (y grows downwards, like the views that draw it).6public struct CanvasRect: Hashable, Sendable, Codable {7 public var origin: CanvasPoint8 public var size: CanvasSize910 public init(origin: CanvasPoint, size: CanvasSize) { self.origin = origin; self.size = size }11 public init(x: Double, y: Double, width: Double, height: Double) {12 origin = CanvasPoint(x: x, y: y); size = CanvasSize(width: width, height: height)13 }14 /// The rectangle spanned by two opposite corners, in any order (marquee selection).15 public init(corner a: CanvasPoint, corner b: CanvasPoint) {16 self.init(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(a.x - b.x), height: abs(a.y - b.y))17 }1819 public var minX: Double { origin.x }20 public var minY: Double { origin.y }21 public var maxX: Double { origin.x + size.width }22 public var maxY: Double { origin.y + size.height }23 public var midX: Double { origin.x + size.width / 2 }24 public var midY: Double { origin.y + size.height / 2 }25 public var width: Double { size.width }26 public var height: Double { size.height }27 public var center: CanvasPoint { CanvasPoint(x: midX, y: midY) }28 public var isEmpty: Bool { size.width <= 0 || size.height <= 0 }2930 /// Edges are inclusive: a point on the border is inside.31 public func contains(_ point: CanvasPoint) -> Bool {32 point.x >= minX && point.x <= maxX && point.y >= minY && point.y <= maxY33 }3435 public func contains(_ other: CanvasRect) -> Bool {36 other.minX >= minX && other.maxX <= maxX && other.minY >= minY && other.maxY <= maxY37 }3839 /// Touching edges count as intersecting, so a card flush with the viewport edge is still drawn.40 public func intersects(_ other: CanvasRect) -> Bool {41 other.minX <= maxX && other.maxX >= minX && other.minY <= maxY && other.maxY >= minY42 }4344 public func union(_ other: CanvasRect) -> CanvasRect {45 let x = min(minX, other.minX), y = min(minY, other.minY)46 return CanvasRect(x: x, y: y, width: max(maxX, other.maxX) - x, height: max(maxY, other.maxY) - y)47 }4849 /// Positive values shrink the rectangle, negative values grow it. Never returns a negative size.50 public func insetBy(dx: Double, dy: Double) -> CanvasRect {51 let width = max(0, size.width - 2 * dx), height = max(0, size.height - 2 * dy)52 return CanvasRect(x: midX - width / 2, y: midY - height / 2, width: width, height: height)53 }5455 public func offsetBy(dx: Double, dy: Double) -> CanvasRect {56 CanvasRect(x: origin.x + dx, y: origin.y + dy, width: size.width, height: size.height)57 }5859 /// The smallest rectangle containing every given rectangle; `nil` for an empty list.60 public static func bounding(_ rects: some Sequence<CanvasRect>) -> CanvasRect? {61 var iterator = rects.makeIterator()62 guard var result = iterator.next() else { return nil }63 while let next = iterator.next() { result = result.union(next) }64 return result65 }66}6768extension CanvasPoint {69 public func translated(dx: Double, dy: Double) -> CanvasPoint { CanvasPoint(x: x + dx, y: y + dy) }70 public func distance(to other: CanvasPoint) -> Double { hypot(x - other.x, y - other.y) }71 var isFinite: Bool { x.isFinite && y.isFinite }72}7374extension CanvasCard {75 public var frame: CanvasRect { CanvasRect(origin: origin, size: size) }7677 /// A one-line label for outlines, accessibility and export.78 public var displayTitle: String {79 switch content {80 case .page(let url, let title): return title.isEmpty ? (url.host ?? url.absoluteString) : title81 case .note(let text):82 let line = text.split(whereSeparator: \.isNewline).first.map(String.init) ?? ""83 return line.isEmpty ? "Note" : line84 case .image(let path): return "Image \(path.prefix(8))"85 case .pdf(let path, let page): return "PDF \(path.prefix(8)), page \(page)"86 }87 }88}8990/// The eight resize handles of a selected card.91public enum CanvasHandle: String, Sendable, Hashable, CaseIterable, Codable {92 case topLeft, top, topRight, right, bottomRight, bottom, bottomLeft, left9394 var movesLeft: Bool { self == .topLeft || self == .left || self == .bottomLeft }95 var movesRight: Bool { self == .topRight || self == .right || self == .bottomRight }96 var movesTop: Bool { self == .topLeft || self == .top || self == .topRight }97 var movesBottom: Bool { self == .bottomLeft || self == .bottom || self == .bottomRight }9899 /// Where the handle sits on a frame.100 public func position(on frame: CanvasRect) -> CanvasPoint {101 let x = movesLeft ? frame.minX : (movesRight ? frame.maxX : frame.midX)102 let y = movesTop ? frame.minY : (movesBottom ? frame.maxY : frame.midY)103 return CanvasPoint(x: x, y: y)104 }105}106107public enum CanvasEdge: String, Sendable, Hashable, Codable, CaseIterable {108 case top, right, bottom, left109110 /// Unit vector pointing out of the card through this edge.111 var normal: CanvasPoint {112 switch self {113 case .top: return CanvasPoint(x: 0, y: -1)114 case .right: return CanvasPoint(x: 1, y: 0)115 case .bottom: return CanvasPoint(x: 0, y: 1)116 case .left: return CanvasPoint(x: -1, y: 0)117 }118 }119120 func anchor(on frame: CanvasRect) -> CanvasPoint {121 switch self {122 case .top: return CanvasPoint(x: frame.midX, y: frame.minY)123 case .right: return CanvasPoint(x: frame.maxX, y: frame.midY)124 case .bottom: return CanvasPoint(x: frame.midX, y: frame.maxY)125 case .left: return CanvasPoint(x: frame.minX, y: frame.midY)126 }127 }128}129130/// The drawn shape of one connection: a cubic Bézier from an edge midpoint of the source card to an edge131/// midpoint of the target card. The renderer strokes `start → control1 → control2 → end`.132public struct CanvasRoute: Hashable, Sendable {133 public var connection: CanvasConnection134 public var start: CanvasPoint135 public var control1: CanvasPoint136 public var control2: CanvasPoint137 public var end: CanvasPoint138 public var startEdge: CanvasEdge139 public var endEdge: CanvasEdge140141 /// Point of the curve at parameter `t` in 0…1.142 public func point(at t: Double) -> CanvasPoint {143 let u = 1 - t144 let a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t145 return CanvasPoint(x: a * start.x + b * control1.x + c * control2.x + d * end.x,146 y: a * start.y + b * control1.y + c * control2.y + d * end.y)147 }148149 /// Where a label is centred: the middle of the curve.150 public var labelPoint: CanvasPoint { point(at: 0.5) }151152 /// The curve flattened into `segments + 1` points (hit-testing, simple renderers).153 public func polyline(segments: Int = 24) -> [CanvasPoint] {154 let count = max(1, segments)155 return (0...count).map { point(at: Double($0) / Double(count)) }156 }157158 /// A rectangle containing the whole curve (the convex hull of the four control points contains it).159 public var bounds: CanvasRect {160 let xs = [start.x, control1.x, control2.x, end.x], ys = [start.y, control1.y, control2.y, end.y]161 let minX = xs.min() ?? 0, minY = ys.min() ?? 0162 return CanvasRect(x: minX, y: minY, width: (xs.max() ?? 0) - minX, height: (ys.max() ?? 0) - minY)163 }164165 /// Shortest distance from `point` to the flattened curve.166 public func distance(to point: CanvasPoint, segments: Int = 24) -> Double {167 let points = polyline(segments: segments)168 var best = Double.infinity169 for index in 1..<points.count {170 best = min(best, CanvasRouter.distance(from: point, toSegment: points[index - 1], points[index]))171 }172 return best173 }174175 func offsetBy(dx: Double, dy: Double, scale: Double) -> CanvasRoute {176 func map(_ p: CanvasPoint) -> CanvasPoint { CanvasPoint(x: (p.x + dx) * scale, y: (p.y + dy) * scale) }177 return CanvasRoute(connection: connection, start: map(start), control1: map(control1), control2: map(control2),178 end: map(end), startEdge: startEdge, endEdge: endEdge)179 }180}181182public enum CanvasRouter {183 /// Routes a connection between two card frames. The dominant axis between the centres picks the edges, so184 /// the curve leaves and enters the cards head-on; the control points extend along the edge normals by half185 /// the gap (clamped), which gives the familiar S-curve and never a kink at the anchors.186 public static func route(_ connection: CanvasConnection, from source: CanvasRect, to target: CanvasRect) -> CanvasRoute {187 let dx = target.midX - source.midX, dy = target.midY - source.midY188 let startEdge: CanvasEdge, endEdge: CanvasEdge189 if abs(dx) >= abs(dy) {190 startEdge = dx >= 0 ? .right : .left191 endEdge = dx >= 0 ? .left : .right192 } else {193 startEdge = dy >= 0 ? .bottom : .top194 endEdge = dy >= 0 ? .top : .bottom195 }196 let start = startEdge.anchor(on: source), end = endEdge.anchor(on: target)197 let along = abs(dx) >= abs(dy) ? abs(end.x - start.x) : abs(end.y - start.y)198 let reach = min(max(along / 2, 40), 300)199 let control1 = start.translated(dx: startEdge.normal.x * reach, dy: startEdge.normal.y * reach)200 let control2 = end.translated(dx: endEdge.normal.x * reach, dy: endEdge.normal.y * reach)201 return CanvasRoute(connection: connection, start: start, control1: control1, control2: control2, end: end,202 startEdge: startEdge, endEdge: endEdge)203 }204205 public static func distance(from point: CanvasPoint, toSegment a: CanvasPoint, _ b: CanvasPoint) -> Double {206 let abx = b.x - a.x, aby = b.y - a.y207 let lengthSquared = abx * abx + aby * aby208 guard lengthSquared > 0 else { return point.distance(to: a) }209 let t = min(1, max(0, ((point.x - a.x) * abx + (point.y - a.y) * aby) / lengthSquared))210 return point.distance(to: CanvasPoint(x: a.x + t * abx, y: a.y + t * aby))211 }212}213214/// A uniform-grid index over card frames for viewport culling.215///216/// Built once per document revision (O(n)); a query touches only the cells under the rectangle. Cards covering217/// more than `oversizeCellLimit` cells are kept in a short list scanned linearly, so one huge card cannot blow218/// up the grid. The measured numbers are in docs/CANVAS.md.219public struct CanvasSpatialIndex: Sendable {220 public let cellSize: Double221 public let count: Int222 private let frames: [CanvasRect]223 private let ids: [CanvasCardID]224 private var cells: [Cell: [Int32]] = [:]225 private var oversized: [Int32] = []226 static let oversizeCellLimit = 64227228 private struct Cell: Hashable, Sendable { var x: Int32, y: Int32 }229230 public init(cards: [CanvasCard], cellSize: Double = 512) {231 self.cellSize = max(16, cellSize)232 count = cards.count233 frames = cards.map(\.frame)234 ids = cards.map(\.id)235 cells.reserveCapacity(cards.count)236 for (index, frame) in frames.enumerated() {237 guard let range = cellRange(frame) else { oversized.append(Int32(index)); continue }238 let span = (range.maxX - range.minX + 1) * (range.maxY - range.minY + 1)239 if span > Self.oversizeCellLimit { oversized.append(Int32(index)); continue }240 for x in range.minX...range.maxX {241 for y in range.minY...range.maxY {242 cells[Cell(x: Int32(x), y: Int32(y)), default: []].append(Int32(index))243 }244 }245 }246 }247248 private func cellRange(_ rect: CanvasRect) -> (minX: Int, maxX: Int, minY: Int, maxY: Int)? {249 let values = [rect.minX, rect.maxX, rect.minY, rect.maxY].map { ($0 / cellSize).rounded(.down) }250 // Coordinates beyond Int32 cells (or NaN) cannot be gridded; such cards go to the linear list.251 guard values.allSatisfy({ $0.isFinite && abs($0) < 1_000_000_000 }) else { return nil }252 return (Int(values[0]), Int(values[1]), Int(values[2]), Int(values[3]))253 }254255 /// Indices (into the array the index was built from) of the cards whose frame intersects `rect`, ascending.256 public func indices(intersecting rect: CanvasRect) -> [Int] {257 var seen = Set<Int32>()258 var result: [Int] = []259 func consider(_ index: Int32) {260 if frames[Int(index)].intersects(rect), seen.insert(index).inserted { result.append(Int(index)) }261 }262 for index in oversized { consider(index) }263 if let range = cellRange(rect) {264 let span = Double(range.maxX - range.minX + 1) * Double(range.maxY - range.minY + 1)265 if span > Double(max(cells.count, 1)) {266 // The query covers more cells than exist: walking the occupied cells is cheaper.267 for (cell, members) in cells268 where Int(cell.x) >= range.minX && Int(cell.x) <= range.maxX && Int(cell.y) >= range.minY && Int(cell.y) <= range.maxY {269 for index in members { consider(index) }270 }271 } else {272 for x in range.minX...range.maxX {273 for y in range.minY...range.maxY {274 for index in cells[Cell(x: Int32(x), y: Int32(y))] ?? [] { consider(index) }275 }276 }277 }278 } else {279 for index in frames.indices { consider(Int32(index)) }280 }281 return result.sorted()282 }283284 public func ids(intersecting rect: CanvasRect) -> [CanvasCardID] {285 indices(intersecting: rect).map { ids[$0] }286 }287}288