SPB Git

Repository Public

Geometry.swift 14.8 KB 263 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocLayout/Geometry.swift3// Description: Queries on a finished layout used by the editor: caret rectangle, selection rectangles, hit testing, line-wise movement.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import CoreGraphics9import DocModel1011public struct CaretGeometry: Sendable {12    public var page: Int13    public var rect: CGRect14}1516public struct HitResult: Sendable {17    public var story: StoryID18    public var position: Position19    /// The click landed at the end of a wrapped line: keep the caret on that line rather than at the start of the next.20    public var upstream: Bool21    /// Generated content (contents, bibliography) or a break marker was hit; the position designates the whole block.22    public var onAtomicBlock: Bool23}2425public extension DocumentLayout {26    private func isHeaderFooter(_ s: StoryID) -> Bool {27        switch s { case .header, .footer: return true; default: return false }28    }2930    /// The fragment and line that display `position`.31    func locate(story: StoryID, position: Position, upstream: Bool = false, preferredPage: Int? = nil) -> (page: Int, fragment: TextFragment, line: Int)? {32        var frags = fragments(story: story, path: position.path)33        guard !frags.isEmpty else { return nil }34        if isHeaderFooter(story), let pp = preferredPage, let same = frags.first(where: { $0.page == pp }) { frags = [same] }35        let layout = frags[0].fragment.layout36        let line = layout.lineIndex(containing: position.offset, preferPrevious: upstream)37        for f in frags where f.fragment.lines.contains(line) && !f.fragment.generated { return (f.page, f.fragment, line) }38        return frags.first.map { ($0.page, $0.fragment, min(max(line, $0.fragment.lines.lowerBound), $0.fragment.lines.upperBound - 1)) }39    }4041    /// Caret rectangle in page coordinates.42    func caret(story: StoryID, position: Position, blocks: [Block], upstream: Bool = false, preferredPage: Int? = nil) -> CaretGeometry? {43        let isParagraph = blocks.paragraph(at: position.path) != nil44        if !isParagraph, story == .body {45            // Atomic block: a break marker or generated content.46            for (pi, page) in pages.enumerated() {47                if let m = page.markers.first(where: { $0.blockIndex == position.path.block }) {48                    return CaretGeometry(page: pi, rect: CGRect(x: m.rect.minX, y: m.rect.minY, width: 1.5, height: max(10, m.rect.height)))49                }50            }51            if let f = fragments(story: story, path: ParaPath(block: position.path.block)).first {52                let l = f.fragment.layout.lines[f.fragment.lines.lowerBound]53                return CaretGeometry(page: f.page, rect: CGRect(x: f.fragment.origin.x, y: f.fragment.origin.y, width: 1.5, height: l.height))54            }55            return nil56        }57        guard let loc = locate(story: story, position: position, upstream: upstream, preferredPage: preferredPage) else { return nil }58        let line = loc.fragment.layout.lines[loc.line]59        let x = loc.fragment.origin.x + line.xPosition(for: position.offset)60        return CaretGeometry(page: loc.page, rect: CGRect(x: x - 0.75, y: loc.fragment.top(ofLine: loc.line), width: 1.5, height: line.height))61    }6263    /// Rectangles that highlight the text between `start` and `end` (both in the same story).64    func selectionRects(story: StoryID, start s: Position, end e: Position, blocks: [Block], preferredPage: Int? = nil) -> [(page: Int, rect: CGRect)] {65        var out: [(Int, CGRect)] = []66        func isPara(_ i: Int) -> Bool { blocks.indices.contains(i) && blocks[i].paragraph != nil }67        func covered(_ p: ParaPath) -> Bool {68            if p.block < s.path.block || p.block > e.path.block { return false }69            if p.block == s.path.block {70                if s.path.cell == nil && !isPara(s.path.block) { if s.offset >= 1 { return false } }71                else if p < s.path { return false }72            }73            if p.block == e.path.block {74                if e.path.cell == nil && !isPara(e.path.block) { if e.offset < 1 { return false } }75                else if p > e.path { return false }76            }77            return true78        }79        let hf = isHeaderFooter(story)80        for (pi, page) in pages.enumerated() {81            if hf, let pp = preferredPage, pp != pi { continue }82            for f in page.texts where f.story == story && !f.generated && covered(f.path) {83                let lo = f.path == s.path ? s.offset : 084                let continues = f.path != e.path85                let hi = continues ? f.layout.length : e.offset86                for (li, r) in f.layout.rects(for: lo..<hi, lines: f.lines) {87                    var rect = r.offsetBy(dx: f.origin.x, dy: f.top(ofLine: li) - r.minY)88                    // Show the paragraph mark as selected when the selection continues past the end of the paragraph.89                    if continues, li == f.layout.lines.count - 1 { rect.size.width += 5 }90                    if rect.width < 0.5, lo < hi || continues { rect.size.width = 5 }91                    if rect.width > 0 { out.append((pi, rect)) }92                }93                if continues, f.layout.length == 0, f.lines.contains(0) {94                    out.append((pi, CGRect(x: f.origin.x + f.layout.lines[0].x, y: f.top(ofLine: 0), width: 5, height: f.layout.lines[0].height)))95                }96            }97            if story == .body {98                for m in page.markers where covered(ParaPath(block: m.blockIndex)) && m.rect.height > 2 { out.append((pi, m.rect)) }99                for f in page.texts where f.story == .body && f.generated && f.path.cell == nil && covered(f.path) { out.append((pi, f.frame)) }100            }101        }102        return out103    }104105    /// Page rectangle of a table cell.106    func cellRect(block: Int, row: Int, cell: Int) -> (page: Int, rect: CGRect)? {107        for (pi, page) in pages.enumerated() {108            for t in page.tables where t.blockIndex == block {109                if let r = t.cellRect(row: row, cell: cell) { return (pi, r) }110            }111        }112        return nil113    }114115    /// Column boundary of a table under a point (for resizing): the grid column whose right edge is within `tolerance`.116    func columnBoundary(page pi: Int, point: CGPoint, tolerance: CGFloat = 3) -> (block: Int, column: Int, tableX: CGFloat, layout: TableLayout)? {117        guard pages.indices.contains(pi) else { return nil }118        for t in pages[pi].tables where t.frame.insetBy(dx: -tolerance, dy: 0).contains(point) {119            for c in 1..<t.layout.columnX.count where abs(t.origin.x + t.layout.columnX[c] - point.x) <= tolerance {120                return (t.blockIndex, c - 1, t.origin.x, t.layout)121            }122        }123        return nil124    }125126    /// The floating object under a point, if any.127    func floatHit(page pi: Int, point: CGPoint) -> FloatFragment? {128        guard pages.indices.contains(pi) else { return nil }129        return pages[pi].floats.last { $0.rect.contains(point) }130    }131132    /// Text position under a page point. `restrictTo` limits the search to one story (normal clicks stay in the story being edited).133    func hitTest(page pi: Int, point: CGPoint, restrictTo: StoryID? = nil) -> HitResult? {134        guard pages.indices.contains(pi) else { return nil }135        let page = pages[pi]136        if restrictTo == nil || restrictTo == .body {137            for m in page.markers where m.rect.insetBy(dx: 0, dy: -2).contains(point) && m.rect.height > 3 {138                return HitResult(story: .body, position: Position(block: m.blockIndex, offset: 0), upstream: false, onAtomicBlock: true)139            }140        }141        // Inside a table the cell under the point decides.142        var cellFilter: (block: Int, row: Int, cell: Int)?143        if restrictTo == nil || restrictTo == .body {144            outer: for t in page.tables where t.frame.contains(point) {145                for r in t.rows {146                    for c in t.layout.cells[r] where t.layout.table.rows[r].cells[c.cellIndex].vMerge != .continue {147                        if let rect = t.cellRect(row: r, cell: c.cellIndex), rect.contains(point) { cellFilter = (t.blockIndex, r, c.cellIndex); break outer }148                    }149                }150            }151        }152        var best: (score: CGFloat, f: TextFragment)?153        for f in page.texts {154            if let s = restrictTo, f.story != s { continue }155            if f.generated && f.path.cell != nil { continue }156            if let cf = cellFilter {157                guard f.story == .body, f.path.block == cf.block, f.path.cell?.row == cf.row, f.path.cell?.cell == cf.cell else { continue }158            }159            let fr = f.frame160            let dy = point.y < fr.minY ? fr.minY - point.y : (point.y > fr.maxY ? point.y - fr.maxY : 0)161            let dx = point.x < fr.minX ? fr.minX - point.x : (point.x > fr.maxX ? point.x - fr.maxX : 0)162            let score = dy * 4 + dx163            if best == nil || score < best!.score { best = (score, f) }164        }165        guard let f = best?.f else { return nil }166        if f.generated { return HitResult(story: f.story, position: Position(block: f.path.block, offset: 0), upstream: false, onAtomicBlock: true) }167        let li = f.line(atY: point.y)168        let line = f.layout.lines[li]169        var offset = line.offset(atX: point.x - f.origin.x)170        var upstream = false171        if offset == line.range.upperBound, li < f.layout.lines.count - 1, !line.range.isEmpty {172            let text = f.layout.attributed.string as NSString173            let last = text.character(at: offset - 1)174            if last == 0x2028 || last == 0x000A { offset -= 1 } else { upstream = true }175        }176        return HitResult(story: f.story, position: Position(path: f.path, offset: offset), upstream: upstream, onAtomicBlock: false)177    }178179    /// Model range of the visual line that holds `position` (Home and End).180    func lineRange(story: StoryID, position: Position, upstream: Bool = false, preferredPage: Int? = nil) -> Range<Int>? {181        guard let loc = locate(story: story, position: position, upstream: upstream, preferredPage: preferredPage) else { return nil }182        var r = loc.fragment.layout.lines[loc.line].range183        // The caret cannot sit after a forced line break on the same line.184        let text = loc.fragment.layout.attributed.string as NSString185        if r.count > 0, r.upperBound <= text.length, text.character(at: r.upperBound - 1) == 0x2028 { r = r.lowerBound..<(r.upperBound - 1) }186        return r187    }188189    private struct LineRef { var page: Int; var fragment: TextFragment; var line: Int }190191    private func lineRefs(story: StoryID, preferredPage: Int?) -> [LineRef] {192        var out: [LineRef] = []193        let hf = isHeaderFooter(story)194        for (pi, page) in pages.enumerated() {195            if hf, let pp = preferredPage, pp != pi { continue }196            for f in page.texts where f.story == story && !f.generated {197                for li in f.lines { out.append(LineRef(page: pi, fragment: f, line: li)) }198            }199            if hf, preferredPage == nil, !out.isEmpty { break }200        }201        return out202    }203204    /// Up / Down arrow: the position on the adjacent visual line closest to `goalX` (a page x coordinate).205    func verticalMove(story: StoryID, from position: Position, goalX: CGFloat, down: Bool, upstream: Bool = false, preferredPage: Int? = nil) -> (position: Position, upstream: Bool)? {206        let refs = lineRefs(story: story, preferredPage: preferredPage)207        guard let here = locate(story: story, position: position, upstream: upstream, preferredPage: preferredPage),208              let cur = refs.firstIndex(where: { $0.fragment.path == position.path && $0.line == here.line && $0.page == here.page }) else { return nil }209        let step = down ? 1 : -1210        func result(_ r: LineRef) -> (Position, Bool) {211            let line = r.fragment.layout.lines[r.line]212            var offset = line.offset(atX: goalX - r.fragment.origin.x)213            var up = false214            if offset == line.range.upperBound, r.line < r.fragment.layout.lines.count - 1, !line.range.isEmpty {215                let text = r.fragment.layout.attributed.string as NSString216                let last = text.character(at: offset - 1)217                if last == 0x2028 || last == 0x000A { offset -= 1 } else { up = true }218            }219            return (Position(path: r.fragment.path, offset: offset), up)220        }221        func pick(_ candidates: [LineRef]) -> LineRef? {222            candidates.min { a, b in223                func d(_ r: LineRef) -> CGFloat { let f = r.fragment.frame; return goalX < f.minX ? f.minX - goalX : (goalX > f.maxX ? goalX - f.maxX : 0) }224                return d(a) < d(b)225            }226        }227        if let cell = position.path.cell {228            let block = position.path.block229            let j = cur + step230            if refs.indices.contains(j), refs[j].fragment.path.block == block, refs[j].fragment.path.cell?.row == cell.row, refs[j].fragment.path.cell?.cell == cell.cell {231                return result(refs[j])232            }233            // Leave the cell: the cell above or below in the same grid column, else the block before or after the table.234            let inTable = refs.filter { $0.fragment.path.block == block }235            var row = cell.row + step236            let rows = Set(inTable.compactMap { $0.fragment.path.cell?.row })237            while rows.contains(row) || (rows.min() ?? 0) < row && row < (rows.max() ?? 0) {238                let candidates = inTable.filter { r in239                    guard let c = r.fragment.path.cell, c.row == row else { return false }240                    let lastPara = inTable.filter { $0.fragment.path.cell?.row == row && $0.fragment.path.cell?.cell == c.cell }.map { $0.fragment.path.cell!.paragraph }.max() ?? 0241                    return down ? (c.paragraph == 0 && r.line == 0) : (c.paragraph == lastPara && r.line == r.fragment.layout.lines.count - 1)242                }243                if let p = pick(candidates) { return result(p) }244                row += step245            }246            let outside = down ? refs.first { $0.fragment.path.block > block } : refs.last { $0.fragment.path.block < block }247            return outside.map(result)248        }249        let j = cur + step250        guard refs.indices.contains(j) else { return nil }251        if let c = refs[j].fragment.path.cell {252            // Entering a table: choose the cell under the caret in its first (or last) row.253            let block = refs[j].fragment.path.block254            let candidates = refs.filter { r in255                guard r.fragment.path.block == block, let rc = r.fragment.path.cell, rc.row == c.row else { return false }256                return down ? (rc.paragraph == 0 && r.line == 0) : (r.line == r.fragment.layout.lines.count - 1)257            }258            if let p = pick(candidates) { return result(p) }259        }260        return result(refs[j])261    }262}263
Files main
Menu

Theme