SPB Git

Repository Public

EditorCanvasView.swift 17.1 KB 360 lines swift

1// ORIX Docs2// File: App/Sources/Canvas/EditorCanvasView.swift3// Description: The document canvas: draws the paginated layout and overlays (selection, caret, find matches, spelling), and geometry4//              conversions between view, page and model coordinates. Input handling lives in the extensions next to this file.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import DocModel10import DocLayout1112final class EditorCanvasView: NSView {13    let session: DocumentSession14    let pageGap: CGFloat = 2215    let edgePadding: CGFloat = 261617    private(set) var pageFrames: [CGRect] = []18    private var caretOn = true19    private var caretTimer: Timer?20    /// Horizontal position kept while moving up and down through lines of different lengths (page coordinates).21    var goalX: CGFloat?22    /// Text being composed by an input method: paragraph path and range.23    var marked: (story: StoryID, path: ParaPath, range: Range<Int>)?24    var compositionBase: (doc: DocumentModel, selection: Selection)?25    var dragState: DragState = .none26    let spelling = SpellingCache()2728    enum DragState {29        case none30        case selecting31        case resizingColumn(block: Int, column: Int, startX: CGFloat, startWidth: CGFloat, scale: CGFloat)32        case resizingObject(story: StoryID, position: Position, startPoint: CGPoint, startSize: CGSize)33    }3435    init(session: DocumentSession) {36        self.session = session37        super.init(frame: .zero)38        wantsLayer = true39        layerContentsRedrawPolicy = .onSetNeedsDisplay40        registerForDraggedTypes([.fileURL, .string, .png, .tiff])41        setAccessibilityIdentifier("document-canvas")42    }4344    @available(*, unavailable)45    required init?(coder: NSCoder) { fatalError("not used") }4647    override var isFlipped: Bool { true }48    override var acceptsFirstResponder: Bool { true }49    override var isOpaque: Bool { true }50    override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }5152    var zoom: CGFloat { session.zoom }53    var layout: DocumentLayout { session.layout }5455    // MARK: Geometry5657    func recomputeFrames() {58        let clipWidth = enclosingScrollView?.contentView.bounds.width ?? bounds.width59        let z = zoom60        var frames: [CGRect] = []61        var y = edgePadding62        let widest = (layout.pages.map(\.size.width).max() ?? 612) * z63        let totalWidth = max(clipWidth, widest + 2 * edgePadding)64        for page in layout.pages {65            let w = page.size.width * z, h = page.size.height * z66            frames.append(CGRect(x: ((totalWidth - w) / 2).rounded(), y: y.rounded(), width: w, height: h))67            y += h + pageGap68        }69        pageFrames = frames70        let size = NSSize(width: totalWidth, height: max(y - pageGap + edgePadding, enclosingScrollView?.contentView.bounds.height ?? 0))71        if frame.size != size { setFrameSize(size) }72    }7374    func layoutChanged(scrollToCaret scroll: Bool) {75        recomputeFrames()76        needsDisplay = true77        if scroll { scrollToCaret(center: false) }78        resetCaretBlink()79        NSAccessibility.post(element: self, notification: .valueChanged)80    }8182    func selectionChanged(scroll: Bool) {83        needsDisplay = true84        if scroll { scrollToCaret(center: false) }85        resetCaretBlink()86        NSAccessibility.post(element: self, notification: .selectedTextChanged)87    }8889    /// Page under a view point (the nearest one when the point is between pages) and the point in page coordinates.90    func pagePoint(_ p: CGPoint) -> (page: Int, point: CGPoint)? {91        guard !pageFrames.isEmpty else { return nil }92        var best = 093        var bestDistance = CGFloat.greatestFiniteMagnitude94        for (i, f) in pageFrames.enumerated() {95            let d = p.y < f.minY ? f.minY - p.y : (p.y > f.maxY ? p.y - f.maxY : 0)96            if d < bestDistance { bestDistance = d; best = i }97            if d == 0 { break }98        }99        let f = pageFrames[best]100        return (best, CGPoint(x: (p.x - f.minX) / zoom, y: (p.y - f.minY) / zoom))101    }102103    func viewRect(page: Int, rect: CGRect) -> CGRect {104        guard pageFrames.indices.contains(page) else { return .zero }105        let f = pageFrames[page]106        return CGRect(x: f.minX + rect.minX * zoom, y: f.minY + rect.minY * zoom, width: rect.width * zoom, height: rect.height * zoom)107    }108109    var caretGeometry: CaretGeometry? {110        layout.caret(story: session.selection.story, position: session.selection.head, blocks: session.blocks, upstream: session.caretUpstream, preferredPage: session.activePage)111    }112113    func scrollToCaret(center: Bool) {114        guard let c = caretGeometry else { return }115        let r = viewRect(page: c.page, rect: c.rect).insetBy(dx: -30, dy: center ? -(visibleRect.height / 2 - 20) : -36)116        scrollToVisible(r.intersection(bounds))117    }118119    func scrollToPage(_ index: Int) {120        guard pageFrames.indices.contains(index) else { return }121        var r = pageFrames[index]122        r.size.height = min(r.height, visibleRect.height)123        scrollToVisible(r.insetBy(dx: 0, dy: -12))124    }125126    /// Zoom that makes the page width fill the visible width.127    func zoomToFitWidth() -> CGFloat {128        let clip = enclosingScrollView?.contentView.bounds.width ?? bounds.width129        let w = layout.pages.map(\.size.width).max() ?? 612130        return max(0.25, min(4, (clip - 2 * edgePadding) / w))131    }132133    // MARK: Caret blinking134135    func resetCaretBlink() {136        caretOn = true137        caretTimer?.invalidate()138        guard window?.firstResponder === self else { return }139        caretTimer = Timer.scheduledTimer(withTimeInterval: 0.56, repeats: true) { [weak self] _ in140            MainActor.assumeIsolated {141                guard let self else { return }142                self.caretOn.toggle()143                if let c = self.caretGeometry { self.setNeedsDisplay(self.viewRect(page: c.page, rect: c.rect).insetBy(dx: -3, dy: -3)) }144            }145        }146    }147148    override func becomeFirstResponder() -> Bool { resetCaretBlink(); needsDisplay = true; return true }149    override func resignFirstResponder() -> Bool { caretTimer?.invalidate(); caretOn = false; needsDisplay = true; return true }150    override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); recomputeFrames(); updateTrackingAreas() }151152    override func updateTrackingAreas() {153        super.updateTrackingAreas()154        trackingAreas.forEach(removeTrackingArea)155        addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseMoved, .activeInKeyWindow, .inVisibleRect, .cursorUpdate], owner: self))156    }157158    // MARK: Drawing159160    override func draw(_ dirtyRect: NSRect) {161        guard let ctx = NSGraphicsContext.current?.cgContext else { return }162        if pageFrames.count != layout.pages.count { recomputeFrames() }163        ORIX.Palette.canvasNS.setFill()164        ctx.fill(dirtyRect)165        let renderer = PageRenderer(doc: session.doc, layout: layout, images: session.images)166        renderer.labels = MarkerLabels.localized167        if session.mode == .focus, session.selection.story == .body, let p = session.blocks.paragraph(at: session.selection.head.path) { renderer.focusParagraphID = p.id }168        let sel = session.selection169        let target = DocumentEditor.resolve(sel, session.blocks)170        let isKey = window?.isKeyWindow == true && window?.firstResponder === self171        let z = zoom172173        for (i, frame) in pageFrames.enumerated() where frame.insetBy(dx: -16, dy: -16).intersects(dirtyRect) {174            // Paper with a soft shadow.175            ctx.saveGState()176            ctx.setShadow(offset: CGSize(width: 0, height: -1.5), blur: 14, color: NSColor.black.withAlphaComponent(effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? 0.55 : 0.16).cgColor)177            ctx.setFillColor(CGColor(gray: 1, alpha: 1))178            ctx.fill(frame)179            ctx.restoreGState()180181            ctx.saveGState()182            ctx.clip(to: frame)183            ctx.translateBy(x: frame.minX, y: frame.minY)184            ctx.scaleBy(x: z, y: z)185            renderer.draw(page: i, in: ctx)186            drawOverlays(page: i, target: target, isKey: isKey, ctx)187            ctx.restoreGState()188        }189    }190191    private func drawOverlays(page i: Int, target: SelectionTarget, isKey: Bool, _ ctx: CGContext) {192        let page = layout.pages[i]193        let sel = session.selection194        // Header / footer / note being edited: a tag and a guide line.195        if sel.story != .body, session.activePage == nil || session.activePage == i {196            let frags = page.texts.filter { $0.story == sel.story }197            if let first = frags.first, let last = frags.last {198                let area = first.frame.union(last.frame).insetBy(dx: -6, dy: -4)199                ctx.setStrokeColor(ORIX.Palette.accentNS.withAlphaComponent(0.7).cgColor)200                ctx.setLineWidth(0.6); ctx.setLineDash(phase: 0, lengths: [3, 2])201                ctx.stroke(area)202                ctx.setLineDash(phase: 0, lengths: [])203                let label: String204                switch sel.story {205                case .header: label = String(localized: "Header")206                case .footer: label = String(localized: "Footer")207                case .note: label = String(localized: "Note")208                case .body: label = ""209                }210                drawTag(label, at: CGPoint(x: area.minX, y: area.maxY + 2), ctx)211            }212        }213        // Find matches.214        if !session.findQuery.isEmpty {215            ctx.setFillColor(NSColor.systemYellow.withAlphaComponent(0.45).cgColor)216            for f in page.texts where !f.generated {217                for m in session.visibleFindMatches where m.story == f.story && m.path == f.path {218                    for (li, r) in f.layout.rects(for: m.range, lines: f.lines) { ctx.fill(r.offsetBy(dx: f.origin.x, dy: f.top(ofLine: li) - r.minY)) }219                }220            }221        }222        // Spelling.223        if AppSettings.shared.checkSpelling {224            let caretPath = sel.isCaret ? sel.head.path : nil225            for f in page.texts where !f.generated && f.layout.length > 0 {226                guard f.story == .body || f.story == sel.story else { continue }227                let text = f.layout.plainString228                let ranges = spelling.misspellings(id: f.layout.paragraphID, text: text)229                for r in ranges {230                    // The word being typed is not flagged until the caret leaves it.231                    if f.story == sel.story, f.path == caretPath, sel.head.offset >= r.lowerBound, sel.head.offset <= r.upperBound { continue }232                    for (li, rect) in f.layout.rects(for: r, lines: f.lines) {233                        let line = f.layout.lines[li]234                        let y = f.top(ofLine: li) + (line.baseline - line.top) + 2.2235                        drawSquiggle(from: f.origin.x + rect.minX, to: f.origin.x + rect.maxX, y: y, ctx)236                    }237                }238            }239        }240        // Selection.241        ctx.setFillColor(ORIX.Palette.selectionNS.withAlphaComponent(isKey ? 0.28 : 0.14).cgColor)242        switch target {243        case .caret: break244        case .range(let s, let e):245            for (pi, rect) in layout.selectionRects(story: sel.story, start: s, end: e, blocks: session.blocks, preferredPage: session.activePage) where pi == i { ctx.fill(rect) }246        case .cells(let block, let rows, let cols):247            if let t = session.blocks[block].table {248                for r in rows { for ci in DocumentEditor.cells(in: t.rows[r], columns: cols) {249                    if let c = layout.cellRect(block: block, row: r, cell: ci), c.page == i { ctx.fill(c.rect) }250                } }251            }252        }253        // Selected object outline and resize handle.254        if let obj = selectedObject(), obj.page == i {255            ctx.setStrokeColor(ORIX.Palette.accentNS.cgColor); ctx.setLineWidth(1)256            ctx.stroke(obj.rect)257            let h = handleRect(for: obj.rect)258            ctx.setFillColor(CGColor(gray: 1, alpha: 1)); ctx.fillEllipse(in: h)259            ctx.strokeEllipse(in: h)260        }261        // Input-method composition underline.262        if let m = marked, m.story == sel.story {263            for f in page.texts where f.story == m.story && f.path == m.path {264                ctx.setFillColor(ORIX.Palette.accentNS.cgColor)265                for (li, r) in f.layout.rects(for: m.range, lines: f.lines) {266                    let line = f.layout.lines[li]267                    ctx.fill(CGRect(x: f.origin.x + r.minX, y: f.top(ofLine: li) + (line.baseline - line.top) + 2, width: r.width, height: 1))268                }269            }270        }271        // Caret.272        if isKey, caretOn, sel.isCaret, let c = caretGeometry, c.page == i {273            ctx.setFillColor(ORIX.Palette.accentNS.cgColor)274            ctx.fill(c.rect)275        }276    }277278    private func drawTag(_ text: String, at p: CGPoint, _ ctx: CGContext) {279        let attrs: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 8, weight: .semibold), .foregroundColor: NSColor.white]280        let s = NSAttributedString(string: text.uppercased(), attributes: attrs)281        let size = s.size()282        let rect = CGRect(x: p.x, y: p.y, width: size.width + 10, height: size.height + 3)283        ctx.setFillColor(ORIX.Palette.accentNS.cgColor)284        ctx.addPath(CGPath(roundedRect: rect, cornerWidth: 3, cornerHeight: 3, transform: nil)); ctx.fillPath()285        let ns = NSGraphicsContext(cgContext: ctx, flipped: true)286        NSGraphicsContext.saveGraphicsState()287        NSGraphicsContext.current = ns288        s.draw(at: CGPoint(x: rect.minX + 5, y: rect.minY + 1.5))289        NSGraphicsContext.restoreGraphicsState()290    }291292    private func drawSquiggle(from x0: CGFloat, to x1: CGFloat, y: CGFloat, _ ctx: CGContext) {293        guard x1 > x0 else { return }294        ctx.saveGState()295        ctx.setStrokeColor(NSColor.systemRed.withAlphaComponent(0.85).cgColor)296        ctx.setLineWidth(0.9); ctx.setLineCap(.round); ctx.setLineDash(phase: 0, lengths: [0.1, 2.2])297        ctx.move(to: CGPoint(x: x0, y: y)); ctx.addLine(to: CGPoint(x: x1, y: y)); ctx.strokePath()298        ctx.restoreGState()299    }300301    // MARK: Selected object302303    /// The image or shape selected as a whole (selection covering exactly one inline object), with its page rectangle.304    func selectedObject() -> (page: Int, rect: CGRect, position: Position, inline: Inline)? {305        let sel = session.selection306        let s = sel.start, e = sel.end307        guard !sel.isCaret, s.path == e.path, e.offset == s.offset + 1, let inline = session.editor.inline(at: s, in: sel.story) else { return nil }308        switch inline { case .image, .shape, .equation: break; default: return nil }309        if inline.placement.isFloating {310            for (pi, page) in layout.pages.enumerated() {311                if let f = page.floats.first(where: { $0.story == sel.story && $0.path == s.path && $0.box.offset == s.offset }) { return (pi, f.rect, s, inline) }312            }313            return nil314        }315        guard let loc = layout.locate(story: sel.story, position: s, preferredPage: session.activePage), let box = loc.fragment.layout.box(at: s.offset) else { return nil }316        let line = loc.fragment.layout.lines[loc.line]317        let x = loc.fragment.origin.x + line.xPosition(for: s.offset)318        let baseline = loc.fragment.baseline(ofLine: loc.line)319        return (loc.page, CGRect(x: x, y: baseline - box.ascent, width: box.width, height: box.ascent + box.descent), s, inline)320    }321322    func handleRect(for rect: CGRect) -> CGRect { CGRect(x: rect.maxX - 4, y: rect.maxY - 4, width: 8, height: 8) }323}324325extension MarkerLabels {326    static var localized: MarkerLabels {327        var l = MarkerLabels()328        l.pageBreak = String(localized: "Page Break")329        l.columnBreak = String(localized: "Column Break")330        l.sectionNextPage = String(localized: "Section Break (Next Page)")331        l.sectionContinuous = String(localized: "Section Break (Continuous)")332        l.sectionOdd = String(localized: "Section Break (Odd Page)")333        l.sectionEven = String(localized: "Section Break (Even Page)")334        return l335    }336}337338/// Caches spelling results per paragraph; a paragraph is checked again only when its text changes.339final class SpellingCache {340    private var entries: [String: (text: String, ranges: [Range<Int>])] = [:]341    private let tag = NSSpellChecker.uniqueSpellDocumentTag()342    var documentTag: Int { tag }343344    func misspellings(id: String, text: String) -> [Range<Int>] {345        if let e = entries[id], e.text == text { return e.ranges }346        let ns = text as NSString347        var out: [Range<Int>] = []348        if ns.length > 0, ns.length < 20_000 {349            let results = NSSpellChecker.shared.check(text, range: NSRange(location: 0, length: ns.length), types: NSTextCheckingResult.CheckingType.spelling.rawValue,350                                                      options: nil, inSpellDocumentWithTag: tag, orthography: nil, wordCount: nil)351            for r in results where r.resultType == .spelling { out.append(r.range.location..<(r.range.location + r.range.length)) }352        }353        if entries.count > 4000 { entries.removeAll(keepingCapacity: true) }354        entries[id] = (text, out)355        return out356    }357358    func invalidate() { entries.removeAll() }359}360
Files main
Menu

Theme