SPB Git

Repository Public

DocumentSession.swift 17.5 KB 389 lines swift

1// ORIX Docs2// File: App/Sources/Document/DocumentSession.swift3// Description: The live state of one open document: the editor (model + selection), its layout, undo, and the workspace state the views observe.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AppKit8import Observation9import DocModel10import DocContainer11import DocLayout12import DocReferences1314enum WorkspaceMode: String, CaseIterable, Identifiable {15    case writing, pageLayout, review, academic, publishing, focus16    var id: String { rawValue }17    var title: LocalizedStringResource {18        switch self {19        case .writing: return "Writing"20        case .pageLayout: return "Page Layout"21        case .review: return "Review"22        case .academic: return "Academic"23        case .publishing: return "Publishing"24        case .focus: return "Focus"25        }26    }27    var symbol: String {28        switch self {29        case .writing: return "pencil.line"30        case .pageLayout: return "doc.richtext"31        case .review: return "text.bubble"32        case .academic: return "graduationcap"33        case .publishing: return "book.pages"34        case .focus: return "scope"35        }36    }37}3839enum SidebarTab: String, CaseIterable, Identifiable {40    case outline, pages, search, review41    var id: String { rawValue }42    var symbol: String {43        switch self { case .outline: return "list.bullet.indent"; case .pages: return "square.grid.2x2"; case .search: return "magnifyingglass"; case .review: return "text.bubble" }44    }45    var title: LocalizedStringResource {46        switch self { case .outline: return "Outline"; case .pages: return "Pages"; case .search: return "Find"; case .review: return "Review" }47    }48}4950enum InspectorTab: String, CaseIterable, Identifiable {51    case format, styles, document, table, object, academic, publish, audit, intelligence52    var id: String { rawValue }53    var symbol: String {54        switch self {55        case .format: return "textformat"; case .styles: return "paragraphsign"; case .document: return "doc"; case .table: return "tablecells"56        case .object: return "photo"; case .academic: return "quote.opening"; case .publish: return "square.and.arrow.up.on.square"57        case .audit: return "checklist"; case .intelligence: return "sparkles"58        }59    }60    var title: LocalizedStringResource {61        switch self {62        case .format: return "Typography"; case .styles: return "Styles"; case .document: return "Document"; case .table: return "Table"63        case .object: return "Object"; case .academic: return "References"; case .publish: return "Publish"; case .audit: return "Auditor"64        case .intelligence: return "Intelligence"65        }66    }67}6869/// Thread-safe holder of the latest model, read by NSDocument when it saves on a background thread.70nonisolated final class ModelStore: @unchecked Sendable {71    private let lock = NSLock()72    private var model = DocumentModel()73    private var pendingWarnings: [FormatWarning] = []74    private var imported: DocFormat?7576    var document: DocumentModel {77        get { lock.lock(); defer { lock.unlock() }; return model }78        set { lock.lock(); model = newValue; lock.unlock() }79    }80    func setImported(_ doc: DocumentModel, warnings: [FormatWarning], format: DocFormat?) {81        lock.lock(); model = doc; pendingWarnings = warnings; imported = format; lock.unlock()82    }83    func takeWarnings() -> [FormatWarning] { lock.lock(); defer { lock.unlock() }; let w = pendingWarnings; pendingWarnings = []; return w }84    var importedFormat: DocFormat? { lock.lock(); defer { lock.unlock() }; return imported }85    func clearImported() { lock.lock(); imported = nil; lock.unlock() }86}8788@Observable89final class DocumentSession {90    // MARK: Model and layout91    private(set) var editor: DocumentEditor92    private(set) var layout: DocumentLayout93    /// Bumped on every document change (views that derive data from the model depend on it).94    private(set) var revision = 095    /// Bumped when only the selection moved.96    private(set) var selectionRevision = 097    private(set) var statistics = DocumentStatistics()98    private(set) var lastLayoutMilliseconds: Double = 099    @ObservationIgnored let cache = LayoutCache()100    @ObservationIgnored let images = ImageStore()101    @ObservationIgnored let store: ModelStore102    @ObservationIgnored weak var undoManager: UndoManager?103    @ObservationIgnored weak var canvas: EditorCanvasView?104    @ObservationIgnored weak var document: ORIXDocument?105106    // MARK: Workspace state107    var mode: WorkspaceMode = .writing { didSet { applyMode(from: oldValue) } }108    var sidebarTab: SidebarTab = .outline109    var inspectorTab: InspectorTab = .format110    var showSidebar = true111    var showInspector = true112    var showRuler = true113    var zoom: CGFloat = 1.0 { didSet { if zoom != oldValue { canvas?.layoutChanged(scrollToCaret: false) } } }114    /// Show tracked changes with their markup (true) or the text as if all were accepted (false).115    var showMarkup = true { didSet { if showMarkup != oldValue { relayout(); canvas?.layoutChanged(scrollToCaret: false) } } }116    var importWarnings: [FormatWarning] = []117    var showImportWarnings = false118    var activeSheet: SheetKind?119    var findQuery = ""120    var findOptions = FindOptions()121    private(set) var findMatches: [TextMatch] = []122    var statusMessage: String?123    /// Comment whose text field should take focus (a comment was just added).124    var pendingCommentFocus: String?125    /// Bumped to move keyboard focus to the find field.126    var focusFindField = 0127    /// Bumped to ask the auditor panel to run.128    var auditRequest = 0129    /// The next equation sheet starts in numbered display mode.130    var pendingDisplayEquation = false131    var lastExportWarnings: [FormatWarning] = []132133    /// The caret is at the end of a wrapped line rather than at the start of the next one.134    @ObservationIgnored var caretUpstream = false135    /// Page of the header, footer or note being edited (those stories repeat on every page).136    @ObservationIgnored var activePage: Int?137    @ObservationIgnored private var lastCoalesceKey: String?138    @ObservationIgnored private var lastCoalesceTime = Date.distantPast139    @ObservationIgnored private var statsWork: DispatchWorkItem?140    @ObservationIgnored private var savedPanels: (sidebar: Bool, inspector: Bool)?141142    init(store: ModelStore, author: String) {143        self.store = store144        let doc = store.document145        self.editor = DocumentEditor(doc: doc, author: author)146        self.layout = Paginator.layout(doc, citations: CitationEngine(document: doc), cache: cache)147        self.statistics = DocumentStatistics(doc)148    }149150    var doc: DocumentModel { editor.doc }151    var selection: Selection { editor.selection }152    var numbering: Numbering { layout.numbering }153    var blocks: [Block] { editor.blocks }154155    // MARK: Editing156157    /// Runs an editing operation as one undoable step. `coalesce` merges consecutive operations of the same kind (typing) into one undo step.158    func perform(_ actionName: String, coalesce: String? = nil, _ change: (inout DocumentEditor) -> Void) {159        let before = (doc: editor.doc, selection: editor.selection)160        change(&editor)161        let now = Date()162        let merges = coalesce != nil && coalesce == lastCoalesceKey && now.timeIntervalSince(lastCoalesceTime) < 2.5 && (undoManager?.canUndo ?? false)163        if !merges { registerUndo(doc: before.doc, selection: before.selection, name: actionName) }164        lastCoalesceKey = coalesce165        lastCoalesceTime = now166        documentChanged()167    }168169    private func registerUndo(doc: DocumentModel, selection: Selection, name: String) {170        guard let um = undoManager else { return }171        // One explicit group per editing step. With event grouping on this nests inside the event's group; with it off172        // (the interaction self-test sends many events in one run-loop pass) each step is still its own undo unit.173        let explicit = !um.groupsByEvent && !um.isUndoing && !um.isRedoing174        if explicit { um.beginUndoGrouping() }175        defer { if explicit { um.endUndoGrouping() } }176        um.registerUndo(withTarget: self) { session in177            MainActor.assumeIsolated {178                let current = (session.editor.doc, session.editor.selection)179                session.editor.doc = doc180                session.editor.selection = selection181                session.editor.sanitizeSelection()182                session.editor.typingOverride = nil183                session.registerUndo(doc: current.0, selection: current.1, name: name)184                session.lastCoalesceKey = nil185                session.documentChanged()186            }187        }188        if !um.isUndoing && !um.isRedoing { um.setActionName(name) }189    }190191    /// Replaces the whole document (revert, version restore).192    func reload(_ doc: DocumentModel) {193        editor = DocumentEditor(doc: doc, author: editor.author)194        cache.removeAll()195        lastCoalesceKey = nil196        documentChanged(storeModel: false)197    }198199    func documentChanged(storeModel: Bool = true) {200        if storeModel { store.document = editor.doc }201        relayout()202        revision &+= 1203        selectionRevision &+= 1204        if !findQuery.isEmpty { findMatches = editor.doc.findAll(findQuery, options: findOptions) }205        canvas?.layoutChanged(scrollToCaret: true)206        scheduleStatistics()207    }208209    func relayout() {210        let start = CFAbsoluteTimeGetCurrent()211        layout = Paginator.layout(editor.doc, citations: CitationEngine(document: editor.doc),212                                  options: LayoutOptions(markup: showMarkup ? .all : .none), cache: cache, previous: layout)213        lastLayoutMilliseconds = (CFAbsoluteTimeGetCurrent() - start) * 1000214    }215216    private func scheduleStatistics() {217        statsWork?.cancel()218        let work = DispatchWorkItem { [weak self] in219            guard let self else { return }220            self.statistics = DocumentStatistics(self.editor.doc)221        }222        statsWork = work223        DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: work)224    }225226    /// Direct access for transient states (input-method composition); callers handle layout and undo.227    func mutateEditor(_ change: (inout DocumentEditor) -> Void) { change(&editor) }228229    // MARK: Selection230231    /// Moves the selection (no document change).232    func select(_ selection: Selection, upstream: Bool = false, scroll: Bool = true) {233        var s = selection234        let old = editor.selection235        editor.selection = s236        editor.sanitizeSelection()237        s = editor.selection238        caretUpstream = upstream239        if s != old {240            editor.typingOverride = nil241            lastCoalesceKey = nil242            selectionRevision &+= 1243        }244        canvas?.selectionChanged(scroll: scroll)245    }246247    func moveCaret(to position: Position, extending: Bool, upstream: Bool = false) {248        let anchor = extending ? editor.selection.anchor : position249        select(Selection(story: editor.selection.story, anchor: anchor, head: position), upstream: upstream)250    }251252    /// Leaves a header, footer or note and returns to the body.253    func returnToBody() {254        guard editor.selection.story != .body else { return }255        var target = Position(block: 0, offset: 0)256        if case .note(let id) = editor.selection.story {257            // Back to the note's reference.258            editor.doc.forEachBodyParagraph { p, path in259                var off = 0260                for r in p.runs { if case .note(let ref)? = r.inline, ref.id == id { target = Position(path: path, offset: off + 1) }; off += r.length }261            }262        } else if let page = activePage, layout.pages.indices.contains(page), let f = layout.pages[page].texts.first(where: { $0.story == .body && !$0.generated }) {263            target = Position(path: f.path, offset: f.layout.lines[f.lines.lowerBound].range.lowerBound)264        }265        activePage = nil266        select(Selection(story: .body, caret: target))267    }268269    /// Selects a paragraph by path and scrolls to it (outline, search results, audit findings).270    func reveal(story: StoryID = .body, path: ParaPath, range: Range<Int>? = nil) {271        if story != .body, let frag = layout.fragments(story: story, path: path).first { activePage = frag.page }272        let r = range ?? 0..<0273        select(Selection(story: story, anchor: Position(path: path, offset: r.lowerBound), head: Position(path: path, offset: r.upperBound)))274        canvas?.window?.makeFirstResponder(canvas)275    }276277    func revealBlock(id: String) {278        guard let i = editor.doc.body.firstIndex(where: { $0.id == id }) else { return }279        if editor.selection.story != .body { activePage = nil }280        select(Selection(story: .body, caret: DocumentEditor.firstPosition(inBlock: i, editor.doc.body)))281        canvas?.scrollToCaret(center: true)282        canvas?.window?.makeFirstResponder(canvas)283    }284285    func revealPage(_ index: Int) { canvas?.scrollToPage(index) }286287    /// Page (0-based) that shows the caret.288    var currentPage: Int {289        layout.caret(story: selection.story, position: selection.head, blocks: blocks, upstream: caretUpstream, preferredPage: activePage)?.page ?? 0290    }291292    var currentSectionIndex: Int {293        switch selection.story {294        case .body: return doc.sectionIndex(ofBlock: selection.head.path.block)295        case .header(let s, _), .footer(let s, _): return s296        case .note: return 0297        }298    }299300    // MARK: Typing301302    /// Text typed on the keyboard: applies smart quotes and dashes when the document asks for them.303    func type(_ text: String) {304        var out = text305        var replaceBefore = 0306        if text.count == 1, let p = editor.blocks.paragraph(at: selection.start.path) {307            let before = p.plainText.utf16Substring(max(0, selection.start.offset - 1)..<selection.start.offset)308            let french = (editor.currentCharacterFormat().language ?? doc.meta.language).hasPrefix("fr")309            let opening = before.isEmpty || before.unicodeScalars.allSatisfy { CharacterSet.whitespacesAndNewlines.contains($0) || "([{«“‘—–-".unicodeScalars.contains($0) }310            if doc.settings.smartQuotes {311                if text == "\"" { out = french ? (opening ? "«\u{00A0}" : "\u{00A0}»") : (opening ? "“" : "”") }312                else if text == "'" { out = opening && !french ? "‘" : "’" }313            }314            if doc.settings.smartDashes, text == "-", before == "-", selection.isCaret,315               editor.currentCharacterFormat().fontFamily != doc.styles.style(StyleID.code)?.char.fontFamily {316                out = "—"; replaceBefore = 1317            }318        }319        perform(String(localized: "Typing"), coalesce: "typing") { e in320            if replaceBefore > 0, e.selection.isCaret {321                e.selection.anchor.offset = max(0, e.selection.head.offset - replaceBefore)322                e.deleteSelection(caretAtEnd: true)323            }324            e.insertText(out)325        }326    }327328    // MARK: Find329330    func runFind() {331        findMatches = findQuery.isEmpty ? [] : editor.doc.findAll(findQuery, options: findOptions)332        canvas?.needsDisplay = true333    }334335    var visibleFindMatches: [TextMatch] { findMatches }336337    func selectMatch(_ m: TextMatch) { reveal(story: m.story, path: m.path, range: m.range) }338339    func findNext(forward: Bool) {340        guard !findMatches.isEmpty else { return }341        let here = forward ? selection.end : selection.start342        let same = findMatches.filter { $0.story == selection.story }343        let pool = same.isEmpty ? findMatches : same344        let next: TextMatch345        if forward {346            next = pool.first { Position(path: $0.path, offset: $0.range.lowerBound) >= here } ?? pool[0]347        } else {348            next = pool.last { Position(path: $0.path, offset: $0.range.upperBound) <= here } ?? pool[pool.count - 1]349        }350        selectMatch(next)351    }352353    // MARK: Modes354355    private func applyMode(from old: WorkspaceMode) {356        guard mode != old else { return }357        if old == .focus, let s = savedPanels { showSidebar = s.sidebar; showInspector = s.inspector; savedPanels = nil }358        switch mode {359        case .writing: break360        case .pageLayout: inspectorTab = .document; showInspector = true; showRuler = true; sidebarTab = .pages361        case .review: sidebarTab = .review; showSidebar = true; showMarkup = true362        case .academic: inspectorTab = .academic; showInspector = true; sidebarTab = .outline363        case .publishing: inspectorTab = .publish; showInspector = true; sidebarTab = .pages364        case .focus:365            savedPanels = (showSidebar, showInspector)366            showSidebar = false; showInspector = false367        }368        canvas?.needsDisplay = true369        canvas?.layoutChanged(scrollToCaret: false)370    }371372    /// Reviewer name used for tracked changes and comments.373    var author: String {374        get { editor.author }375        set { editor.author = newValue }376    }377}378379enum SheetKind: Identifiable, Equatable {380    case equation(existing: Position?), link, citation, crossReference, insertTable, export, compare, importWarnings, properties, caption, formula, automation381    var id: String {382        switch self {383        case .equation: return "equation"; case .link: return "link"; case .citation: return "citation"; case .crossReference: return "xref"384        case .insertTable: return "table"; case .export: return "export"; case .compare: return "compare"; case .importWarnings: return "warnings"385        case .properties: return "properties"; case .caption: return "caption"; case .formula: return "formula"; case .automation: return "automation"386        }387    }388}389
Files main
Menu

Theme