import CoreText import UIKit import os /// Draws the document through a viewport (height map, layout cache, gutter, active line) in a scroll view /// whose content is TextInputView. layoutSubviews is the frame loop. @MainActor final class CodeEditorView: UIScrollView { /// revision is the snapshot the spans came from, -1 when the line was laid out plain. final class Entry { let id: Int let layout: LineLayout let spans: [Int]? var revision: Int init(id: Int, layout: LineLayout, spans: [Int]?, revision: Int) { self.id = id self.layout = layout self.spans = spans self.revision = revision } } /// Row geometry in content view coordinates for the decoration paths; reads the cache only. @MainActor private final class ContentGeometry: @MainActor RowGeometry { unowned let view: CodeEditorView init(_ view: CodeEditorView) { self.view = view } var rowHeight: Int { view.rowMetrics().rowHeight } var spaceWidth: CGFloat { view.rowMetrics().spaceWidth } var viewHeight: Int { view.viewport.scrollY - view.viewport.insetTop + view.viewport.height } var originX: CGFloat { view.textPadding } func lineAt(_ offset: Int) -> Int { view.docLineAt(offset) } func lineStart(_ line: Int) -> Int { view.docLineStart(line) } func lineLength(_ line: Int) -> Int { view.docLineLength(line) } func lineTop(_ line: Int) -> Int { view.viewport.rowStart(line) * rowHeight } func rowCount(_ line: Int) -> Int { view.cache[line]?.layout.rowCount ?? 0 } func rowSpans(line: Int, from: Int, to: Int, _ out: (_ row: Int, _ left: CGFloat, _ right: CGFloat) -> Void) { view.cache[line]?.layout.selectionRows(from: from, to: to, out) } } /// Visual rows for the caret mover; lays out the lines it is asked about. @MainActor private final class ContentLineGeometry: @MainActor LineGeometry { unowned let view: CodeEditorView init(_ view: CodeEditorView) { self.view = view } private func layout(_ line: Int) -> LineLayout { (view.cache[line] ?? view.layoutLine(line)).layout } func rows(_ line: Int) -> Int { layout(line).rowCount } func rowOf(line: Int, column: Int) -> Int { layout(line).rowOf(column) } func caretX(line: Int, column: Int) -> CGFloat { layout(line).caretX(column) } func columnAt(line: Int, row: Int, x: CGFloat) -> Int { layout(line).columnAt(row: row, x: x) } } static let defaultTextPadding: CGFloat = 8 static let gutterPadding: CGFloat = 8 static let caretWidth: CGFloat = 2 /// Android's SCROLL_DURATION_MS. static let scrollDuration: CFTimeInterval = 0.25 /// An animated scrollToLine in flight. private struct LineScroll { let line: Int let startY: Int let start: CFTimeInterval let link: CADisplayLink } // The JS thread reads the core, the last frame and the focus through these locks. private let coreLock: OSAllocatedUnfairLock private let frameLock = OSAllocatedUnfairLock(initialState: FrameInfo.empty) private let focusLock = OSAllocatedUnfairLock(initialState: false) nonisolated var core: EditorCore { coreLock.withLock { $0 } } nonisolated var latestFrame: FrameInfo { frameLock.withLock { $0 } } nonisolated var hasFocus: Bool { focusLock.withLock { $0 } } var onReady: (() -> Void)? var onScroll: ((FrameInfo) -> Void)? var onSelectionChange: ((Selection) -> Void)? var onChange: ((Change, ChangeOrigin) -> Void)? var onChangeText: ((String) -> Void)? var onContentSizeChange: ((CGSize) -> Void)? var onGapLayout: (([GapRect]) -> Void)? var onEditorFocus: (() -> Void)? var onEditorBlur: (() -> Void)? private(set) var isReadOnly = false let textInput: TextInputView private let clipboard = ClipboardActions() private(set) lazy var undoBridge = CodeEditorUndoManager(editor: self) private let gutter = GutterView() private var search: SearchController? private var goalX: CGFloat? private var movingVertically = false private var theme = ThemeColors.default private var font: CTFont private var lineHeight: CGFloat = 1.4 private var languageId: String? private var metrics: RowMetrics? private var snapshot: Snapshot? // The revision of the last snapshot prepare consumed; a snapshot based on it re-queries only the lines it changed. private var appliedRevision = -1 // The dropped entry's spans moved along a one line change, painted until the snapshot lands. private var pendingSpans: [Int]? private var pendingTail: [Int]? private var pendingLine = -1 private var pendingRevision = -1 private var highlighter: Highlighter? private(set) var engine: SyntaxEngine? private let frameReader = FrameReader() // Set from the frame call to the end of publish. private var drawFrame: EditorFrame? let viewport = Viewport() let cache = LayoutCache(capacity: 64) private var nextEntryId = 0 private var brackets: BracketHighlight private lazy var geometry = ContentGeometry(self) private lazy var lineGeometry = ContentLineGeometry(self) private var layers: [Int: LineLayer] = [:] private var pool: [LineLayer] = [] private var placeholderLayer: LineLayer? private var placeholderLayout: LineLayout? private var lineNumbers = true /// Whole points, so the viewport's Int padding and the layers' CGFloat padding never disagree. private(set) var textPadding = CodeEditorView.defaultTextPadding private var highlightActiveLine = true private var placeholder: String? private var contentInsetTop: CGFloat = 0 private var contentInsetBottom: CGFloat = 0 private var contentInsetLeft: CGFloat = 0 private var contentInsetRight: CGFloat = 0 private(set) var keyboardInset: CGFloat = 0 private var avoidsKeyboard = false private(set) var keyboardTracker: KeyboardInsetTracker? private var ready = false private var scrollDirty = false private var lineScroll: LineScroll? private var selectionDirty = false private var selectionViewsDirty = false private var contentDirty = false private var gapsDirty = false private var revealPending = false private var autoFocusPending = false private var lastContentSize = CGSize(width: -1, height: -1) private var inputTime: TimeInterval = 0 private var inputWork: TimeInterval = 0 private var frameStart: TimeInterval = 0 private var debugOn = false private var debugChecked: TimeInterval = 0 override init(frame: CGRect) { let core = EditorCore() coreLock = OSAllocatedUnfairLock(initialState: core) font = CTFontCreateWithName("Menlo" as CFString, 14, nil) brackets = BracketHighlight(core: core) textInput = TextInputView(core: core) super.init(frame: frame) contentInsetAdjustmentBehavior = .never alwaysBounceVertical = true // The scroll edge effects would blur the first and last rows under the edges of the view. if #available(iOS 26.0, *) { for effect in [topEdgeEffect, bottomEdgeEffect, leftEdgeEffect, rightEdgeEffect] { effect.isHidden = true } } backgroundColor = UIColor(cgColor: theme.background) viewport.textPadding = Int(textPadding) gutter.padding = CodeEditorView.gutterPadding textInput.editor = self textInput.decorations.setTheme(theme) addSubview(textInput) addSubview(gutter) // Touches reach the content view at once, and a caret or handle drag beats the scroll, as in UITextView. delaysContentTouches = false for pan in textInput.dragRecognizers { panGestureRecognizer.require(toFail: pan) } wire(core) } required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } /// The revision of the snapshot the layers paint from, -1 without one. var snapshotRevision: Int { snapshot?.revision ?? -1 } func setInitialText(_ value: String) { let settings = core.settings let next = EditorCore(value) next.settings = settings coreLock.withLock { $0 = next } wire(next) if let engine { engine.attach(next) } else { _ = ensureEngine() } // The new document starts at revision 0 like the old one, so a kept snapshot would pass the revision check. snapshot = nil resetDocument() } func setText(_ text: String, keepHistory: Bool) { textInput.session.reset() core.setText(text, keepHistory: keepHistory) stopLineScroll() viewport.scrollTo(0, 0) pushScroll() setNeedsLayout() } func setLanguage(_ id: String?) { if id == languageId { return } languageId = id highlighter = id.flatMap { LanguageRegistry.resolve($0) }.map { Highlighter(language: $0) } ensureEngine().setLanguage(id) // The old grammar's tree would paint garbage under the new query until the next snapshot lands. snapshot = nil cache.clear() setNeedsLayout() } func setTheme(_ colors: ThemeColors) { theme = colors backgroundColor = UIColor(cgColor: colors.background) gutter.theme = colors textInput.decorations.setTheme(colors) textInput.apply(theme: colors) placeholderLayout = nil cache.clear() selectionViewsDirty = true setNeedsLayout() } /// `family` is a family's regular upright face, else a font name, else Menlo; the size is in points. func setFont(family: String?, size: CGFloat, lineHeight: CGFloat) { self.lineHeight = lineHeight font = CTFontCreateWithName(Self.fontName(for: family) as CFString, size, nil) metrics = nil placeholderLayout = nil relayout() } /// The family lookup also answers expo-font's keys, which `UIFont(name:)` never sees. static func fontName(for family: String?) -> String { guard let family else { return "Menlo" } return FontFace.regular(of: UIFont.fontNames(forFamilyName: family)) ?? UIFont(name: family, size: 12)?.fontName ?? "Menlo" } func setLineNumbers(_ enabled: Bool) { if lineNumbers == enabled { return } lineNumbers = enabled relayout() } func setTextPadding(_ points: CGFloat) { let padding = max(0, points).rounded() if padding == textPadding { return } textPadding = padding viewport.textPadding = Int(padding) for layer in layers.values { layer.padding = padding layer.setNeedsDisplay() } placeholderLayer?.padding = padding placeholderLayer?.setNeedsDisplay() relayout() if hasFocus { revealPending = true } } func setSoftWrap(_ enabled: Bool) { if viewport.wrap == enabled { return } viewport.wrap = enabled relayout() } func setHighlightActiveLine(_ enabled: Bool) { highlightActiveLine = enabled setNeedsLayout() } func setMatchBrackets(_ enabled: Bool) { brackets.enabled = enabled setNeedsLayout() } func setReadOnly(_ enabled: Bool) { isReadOnly = enabled textInput.isReadOnly = enabled } func setSuggestions(_ mode: Suggestions) { textInput.setSuggestions(mode) } func setPlaceholder(_ text: String?) { placeholder = text placeholderLayout = nil setNeedsLayout() } /// Tab size, space insertion, auto indent and bracket closing; a tab size change re-measures the rows. func setEditorSettings(_ settings: EditorSettings) { if core.settings == settings { return } let tabChanged = core.settings.tabSize != settings.tabSize core.settings = settings if tabChanged { metrics = nil relayout() } } /// Insets in points. The bottom inset is how consumers keep the caret above a toolbar. func setContentInsets(top: CGFloat, bottom: CGFloat, left: CGFloat, right: CGFloat) { contentInsetTop = top contentInsetBottom = bottom contentInsetLeft = left contentInsetRight = right applyInsets() } /// Points of the view under the keyboard, applied like a bottom inset. func applyKeyboardInset(_ points: CGFloat) { if points == keyboardInset { return } keyboardInset = points applyInsets() } /// Follows the window's keyboard while attached; off by default. func setAvoidKeyboard(_ on: Bool) { avoidsKeyboard = on if on && window != nil { startKeyboardTracker() } else { stopKeyboardTracker() } } private func startKeyboardTracker() { if keyboardTracker != nil { return } let tracker = KeyboardInsetTracker(view: self) { [weak self] points in self?.applyKeyboardInset(points) } keyboardTracker = tracker tracker.start() } private func stopKeyboardTracker() { keyboardTracker?.stop() keyboardTracker = nil } /// Off leaves vertical drags to the parent; the pan stays on for lines wider than the view. private(set) var scrollsVertically = true func setScrollEnabled(_ enabled: Bool) { stopLineScroll() scrollsVertically = enabled alwaysBounceVertical = enabled // A second scroll-to-top view in the window turns off the page's status bar tap. scrollsToTop = enabled } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer === panGestureRecognizer && !scrollsVertically { let t = panGestureRecognizer.translation(in: self) if !viewport.pansSideways(dx: Double(t.x), dy: Double(t.y)) { return false } } return super.gestureRecognizerShouldBegin(gestureRecognizer) } override var contentOffset: CGPoint { get { super.contentOffset } set { var offset = newValue if !scrollsVertically && (isDragging || isDecelerating) { offset.y = CGFloat(viewport.scrollY) } super.contentOffset = offset } } func focus() { _ = textInput.becomeFirstResponder() } func blur() { _ = textInput.resignFirstResponder() } /// Focuses once, right away in a window or when the view joins one. func setAutoFocus(_ enabled: Bool) { autoFocusPending = enabled if enabled && window != nil { runAutoFocus() } } /// False when nothing is selected. @discardableResult func copySelection() -> Bool { clipboard.copy(core) } func cut(origin: ChangeOrigin = .input) { if !isReadOnly { clipboard.cut(core, origin: origin) } } func paste(origin: ChangeOrigin = .input) { if !isReadOnly && clipboard.paste(core, origin: origin) { revealAfterInput() } } func selectAll() { core.selectAll() } // Commands /// Runs a hardware key or toolbar command; editing commands end a composition first and read only drops them. func perform(_ command: KeyCommand) { if command.edits && isReadOnly { return } if command.edits && textInput.session.marked != nil { textInput.session.unmarkText() } switch command { case .vertical(let direction, let page, let extend): moveVertically(direction: direction, page: page, extend: extend) case .copy: copySelection() case .cut: cut() case .paste: paste() case .undo: undo() case .redo: redo() default: CoreCommands.run(core, command) } revealAfterInput() } /// Types through the keyboard path: auto closing, the indenter on a newline, typing coalescing. func typeText(_ text: String) { if isReadOnly || text.isEmpty { return } if textInput.session.marked != nil { textInput.session.unmarkText() } core.typeText(text) revealAfterInput() } func undo() { textInput.session.reset() if core.undo() { revealAfterInput() } } func redo() { textInput.session.reset() if core.redo() { revealAfterInput() } } private func moveVertically(direction: Int, page: Bool, extend: Bool) { let rows = page ? max(1, viewport.viewportHeight / rowMetrics().rowHeight) : 1 let result = CaretMover.move( doc: core.document, geometry: lineGeometry, offset: core.selection.head, rows: rows * direction, goalX: goalX) movingVertically = true core.setSelection(anchor: extend ? core.selection.anchor : result.offset, head: result.offset) movingVertically = false goalX = result.goalX } // Search /// Throws SearchError for an invalid regex. The matches arrive through whenSearchFresh. func setSearch(_ query: SearchQuery) throws { try searchController().setQuery(query) setNeedsLayout() } func clearSearch() { try? search?.setQuery(nil) setNeedsLayout() } /// Runs the block once the painted matches belong to the current revision, right away without a search. func whenSearchFresh(_ block: @escaping () -> Void) { if let search { search.whenFresh(block) } else { block() } } var matchCount: Int { core.matchCount } var matchLimited: Bool { core.matchLimited } func findNext() -> EditorCore.SearchHit? { let hit = core.findNext() afterSearchMove() return hit } func findPrevious() -> EditorCore.SearchHit? { let hit = core.findPrevious() afterSearchMove() return hit } func replaceCurrent(_ text: String) -> Bool { let replaced = core.replaceCurrent(text) afterSearchMove() return replaced } func replaceAll(_ text: String) -> Int { let count = core.replaceAll(text) afterSearchMove() return count } private func afterSearchMove() { revealPending = true setNeedsLayout() } /// The controller shares the syntax queue, so a search never races a parse of the same text. private func searchController() -> SearchController { if let search { return search } let controller = SearchController( core: core, queue: ensureEngine().queue, postToMain: { block in DispatchQueue.main.async(execute: block) }) controller.onResult = { [weak self] count, millis in MainActor.assumeIsolated { self?.searchResultLanded(count, millis) } } search = controller return controller } private func searchResultLanded(_ count: Int, _ millis: Int64) { if debugSwitch() { DebugSwitch.log.info("{\"call\":\"search\",\"count\":\(count, privacy: .public),\"ms\":\(millis, privacy: .public)}") } setNeedsLayout() } func scrollToLine(_ line: Int, animated: Bool) { stopLineScroll() // Ends a deceleration or an animated offset, as Android aborts its scroller. setContentOffset(contentOffset, animated: false) if animated { let link = CADisplayLink(target: self, selector: #selector(stepLineScroll)) link.add(to: .main, forMode: .common) lineScroll = LineScroll(line: line, startY: Int(contentOffset.y.rounded()), start: CACurrentMediaTime(), link: link) } else if viewport.scrollTo(viewport.scrollX, lineTop(line)) { pushScroll() onScrolled() } } private func lineTop(_ line: Int) -> Int { viewport.rowStart(max(0, min(line, core.document.lineCount - 1))) * viewport.rowHeight } /// Aims at the line again every frame: the wrapped lines the scroll passes take their rows on the way. @objc private func stepLineScroll() { guard let scroll = lineScroll else { return } if isTracking { stopLineScroll() return } let t = min(1, (CACurrentMediaTime() - scroll.start) / Self.scrollDuration) let eased = 1 - pow(1 - t, 3) let target = min(lineTop(scroll.line), viewport.maxScrollY) let y = Double(scroll.startY) + Double(target - scroll.startY) * eased if t >= 1 { stopLineScroll() } if viewport.scrollTo(viewport.scrollX, Int(y.rounded())) { pushScroll() onScrolled() } } private func stopLineScroll() { lineScroll?.link.invalidate() lineScroll = nil } /// Scrolls the least amount that shows the caret with the text padding around it. func revealSelection() { stopLineScroll() let m = rowMetrics() let doc = core.document let head = core.selection.head let line = doc.lineAt(head) let entry = cache[line] ?? layoutLine(line) let col = head - doc.lineStart(line) let row = entry.layout.rowOf(col) let x = Int(entry.layout.caretX(col).rounded()) let top = (viewport.rowStart(line) + row) * m.rowHeight if viewport.reveal(left: x, top: top, right: x + Int(CodeEditorView.caretWidth), bottom: top + m.rowHeight) { pushScroll() onScrolled() } } /// Document offset under a point of the visible area. Points left of the text snap to the row start, points below to the end. func offsetAt(x: CGFloat, y: CGFloat) -> Int { offsetAt(row: viewport.rowAt(Int(y.rounded(.down))), contentX: viewport.contentX(x)) } /// The same for a point in the content view's coordinates, what UITextInput receives. func offsetAt(contentPoint point: CGPoint) -> Int { let row = Int((point.y / CGFloat(rowMetrics().rowHeight)).rounded(.down)) return offsetAt(row: row, contentX: point.x - textPadding) } private func offsetAt(row: Int, contentX: CGFloat) -> Int { let doc = core.document if row < 0 { return 0 } if row >= viewport.totalRows { return doc.length } let line = viewport.lineAtRow(row) let entry = cache[line] ?? layoutLine(line) let rowInLine = max(0, min(row - viewport.rowStart(line), entry.layout.rowCount - 1)) return doc.lineStart(line) + entry.layout.columnAt(row: rowInLine, x: contentX) } /// The caret rect at an offset in content view coordinates. func caretRect(offset: Int) -> CGRect { let m = rowMetrics() let line = docLineAt(offset) let entry = cache[line] ?? layoutLine(line) let col = offset - docLineStart(line) let top = CGFloat((viewport.rowStart(line) + entry.layout.rowOf(col)) * m.rowHeight) return CGRect( x: textPadding + entry.layout.caretX(col), y: top, width: CodeEditorView.caretWidth, height: CGFloat(m.rowHeight)) } /// One rect per visible row of [start, end) in content view coordinates, flagged at the selection ends. func selectionRects(start: Int, end: Int) -> [CPSelectionRect] { let m = rowMetrics() var rects: [CGRect] = [] Decorations.forEachRect(geometry, start: start, end: end, firstLine: viewport.firstVisibleLine()) { rects.append($0) } let startLine = docLineAt(start) let endLine = docLineAt(end) // The last rect carries the end only when the end's row was reached, not cut off by the view bottom. var endTop: CGFloat = -1 if let entry = cache[endLine] { endTop = CGFloat((viewport.rowStart(endLine) + entry.layout.rowOf(end - docLineStart(endLine))) * m.rowHeight) } return rects.enumerated().map { i, rect in CPSelectionRect( rect: rect, containsStart: i == 0 && startLine >= viewport.firstVisibleLine(), containsEnd: i == rects.count - 1 && rect.minY == endTop) } } /// Up or down by visual rows from an offset, for the keyboard's arrow handling. func verticalMove(from offset: Int, rows: Int) -> Int { CaretMover.move(doc: core.document, geometry: lineGeometry, offset: offset, rows: rows, goalX: nil).offset } /// Keyboard input moves the caret, so the next frame reveals it. func revealAfterInput() { revealPending = true setNeedsLayout() } /// Runs a block on the main thread from any thread, for the JS side. nonisolated func runOnMain(_ block: @escaping @Sendable @MainActor () -> Void) { Task { @MainActor in block() } } /// Remembers when input arrived so the next frame can log its latency, while the debug setting is on. func markInputTime(_ time: TimeInterval = CACurrentMediaTime()) { if inputTime == 0 && debugSwitch() { inputTime = time } } /// Adds the time a key handler or keyboard call spends on the main thread to the next paint line. func inputWork(_ block: () throws -> T) rethrows -> T { let started = CACurrentMediaTime() defer { if inputTime != 0 { inputWork += CACurrentMediaTime() - started } } return try block() } /// The content view became or stopped being first responder. func textInputFocusChanged(_ focused: Bool) { focusLock.withLock { $0 = focused } selectionViewsDirty = true if focused { revealPending = true } else { textInput.menu.hide() } setNeedsLayout() if focused { onEditorFocus?() } else { onEditorBlur?() } } override func didMoveToWindow() { super.didMoveToWindow() if window == nil { stopLineScroll() textInput.menu.hide() textInput.endLoupe() search?.close() search = nil engine?.close() engine = nil snapshot = nil stopKeyboardTracker() } else { _ = ensureEngine() if avoidsKeyboard { startKeyboardTracker() } if autoFocusPending { runAutoFocus() } } } override func layoutSubviews() { super.layoutSubviews() frameStart = CACurrentMediaTime() let w = Int(bounds.width.rounded()) let h = Int(bounds.height.rounded()) if w != viewport.width || h != viewport.height { sizeChanged(w, h) } let m = rowMetrics() // The layout's three calls of a draw: this scroll, the frame, then the measure call in prepare. Until endDraw, // the layout reads come from them. With the debug switch on, a ninth single call traps. let x = Int(contentOffset.x.rounded()) if viewport.beginDraw(scrollX: x, scrollY: Int(contentOffset.y.rounded()), checksCalls: debugSwitch()) { scrollDirty = true } let scrolled = scrollDirty if w == 0 || h == 0 { viewport.endDraw() return } if revealPending { revealPending = false revealSelection() } var frame = readFrame() drawFrame = frame core.document.drawing = true var moved = prepare(frame, m) // A measure call that clamps the scroll (a visible line lost rows at the end) shows lines above the frame, and // their own measure call can clamp again. They are laid out in this draw, so none of them shows blank. while viewport.firstVisibleLine() < frame.first { frame = readFrame() drawFrame = frame if prepare(frame, m) { moved = true } } let first = frame.first let lastBound = frame.last if moved { // A move the measure call made reaches the scroll listener at the end of this draw. scrollDirty = true pushScroll() } else { updateContentSize() } let caretLine = frame.caretLine let lastLine = placeLayers(first, lastBound, m) placeGutter(first, lastLine, caretLine) placeDecorations(frame, first, lastLine, caretLine, m) placeMarkedUnderline(first) placeHandles() placePlaceholder(frame, m) publish(first, lastLine, caretLine, m) viewport.endDraw() core.document.drawing = false drawFrame = nil if scrollDirty { scrollDirty = false textInput.menu.hide() onScroll?(latestFrame) } if contentDirty { contentDirty = false onContentSizeChange?(lastContentSize) } if gapsDirty { gapsDirty = false onGapLayout?(latestFrame.gaps) } if selectionDirty { selectionDirty = false onSelectionChange?(core.selection) } if selectionViewsDirty { selectionViewsDirty = false textInput.selectionInteraction.setNeedsSelectionUpdate() } if !ready { ready = true onReady?() } if inputTime != 0 { logPaint() } else if scrolled { logFrame() } } private func wire(_ core: EditorCore) { viewport.attach(core) core.onChange = { [weak self] change, origin in self?.onDocumentChange(change, origin) } core.onSelectionChange = { [weak self] _ in self?.onSelectionMoved() } let enabled = brackets.enabled brackets = BracketHighlight(core: core) brackets.enabled = enabled textInput.session = MarkedTextSession(core: core) search?.close() search = nil } private func runAutoFocus() { autoFocusPending = false focus() } private func onSelectionMoved() { if !movingVertically { goalX = nil } selectionDirty = true selectionViewsDirty = true if !textInput.session.applying { textInput.inputDelegate?.selectionWillChange(textInput) textInput.inputDelegate?.selectionDidChange(textInput) } setNeedsLayout() } private func onDocumentChange(_ change: Change, _ origin: ChangeOrigin) { let doc = core.document let first = doc.lineAt(change.start) let oldCount = lineSpan(change.removed) let newCount = lineSpan(change.inserted) keepSpans(first, oldCount, newCount, change) cache.shift(first: first, oldCount: oldCount, newCount: newCount) search?.onChange(change) // The core already moved the rows and gaps with the edit and clamped the scroll. if updateGutter() { // A relayout that moved the offset is a scroll the listener hears of, like the clamp below. let before = contentOffset relayout() if contentOffset != before { onScrolled() } } if origin != .api { revealPending = true } // A change the keyboard did not make: it ends a composition it touched and the keyboard hears of it. let session = textInput.session if !session.applying { textInput.inputDelegate?.textWillChange(textInput) _ = session.onExternalChange(change) textInput.inputDelegate?.textDidChange(textInput) } textInput.cursorView.resetBlinkAnimation() textInput.menu.hide() selectionViewsDirty = true // An edit that shortens the content under the offset clamped the core scroll. The scroll view and the scroll // listener take it here, since the next draw's clamp would see no move. if contentOffset.y > CGFloat(viewport.maxScrollY) || contentOffset.x > CGFloat(viewport.maxScrollX) { pushScroll() onScrolled() } else { updateContentSize() } setNeedsLayout() onChange?(change, origin) onChangeText?(doc.text()) } private func lineSpan(_ text: String) -> Int { text.utf16.reduce(1) { $0 + ($1 == 10 ? 1 : 0) } } /// Replaces the decorations. `revision` is the one they were computed for, below zero for the current text. func setDecorations(_ items: [Decoration], revision: Int) { // The core moves the gaps and keeps the top visible line where it was. if !core.setDecorations(items, revision: revision) { return } pushScroll() selectionViewsDirty = true updateContentSize() setNeedsLayout() } /// True when a point in content view coordinates is in a gap, where taps leave the caret alone. func inGap(contentY: CGFloat) -> Bool { viewport.isGapRow(Int((contentY / CGFloat(rowMetrics().rowHeight)).rounded(.down))) } /// The gap under `line` in view points from the last frame, or nil. nonisolated func gapRect(line: Int) -> CGRect? { latestFrame.gaps.first { $0.line == line }?.rect } private func resetDocument() { cache.clear() viewport.widestLine = 0 updateGutter() stopLineScroll() viewport.scrollTo(0, 0) pushScroll() selectionViewsDirty = true setNeedsLayout() } /// Width, wrap, font, gutter or inset changes drop every layout and keep the top visible line in place. private func relayout() { let anchor = viewport.anchor() let scrollX = viewport.scrollX viewport.rowHeight = rowMetrics().rowHeight cache.clear() viewport.resetRows() viewport.widestLine = 0 updateGutter() viewport.restore(anchor) // The visible lines are measured again right away so the horizontal position survives the widest line reset. layoutVisibleLines() viewport.scrollTo(scrollX, viewport.scrollY) pushScroll() selectionViewsDirty = true setNeedsLayout() } private func layoutVisibleLines() { var line = viewport.firstVisibleLine() while line < core.document.lineCount && line <= viewport.lastVisibleLine() { if cache[line] == nil { layoutLine(line) } line += 1 } } @discardableResult private func updateGutter() -> Bool { let digit = RowMetrics.advance(of: "0", in: font) let w = lineNumbers ? GutterMetrics.width(lineCount: core.document.lineCount, digitAdvance: digit, padding: CodeEditorView.gutterPadding) : 0 if w == viewport.gutterWidth { return false } viewport.gutterWidth = w return true } // Created on first use and after every re-attach, since detaching closes the parse queue. private func ensureEngine() -> SyntaxEngine { if let engine { return engine } let created = SyntaxEngine( postToMain: { block in DispatchQueue.main.async(execute: block) }, onSnapshot: { [weak self] snapshot in MainActor.assumeIsolated { self?.onSnapshot(snapshot) } }) engine = created created.setLanguage(languageId) created.attach(core) return created } private func onSnapshot(_ next: Snapshot) { // A parse that started before a language switch still reports the old grammar; it must not paint. if next.languageId != languageId { engine?.release(next) return } let previous = snapshot snapshot = next if let previous { engine?.release(previous) } if debugSwitch() { let s = next.stats DebugSwitch.log.info( "{\"call\":\"parse\",\"ms\":\(s.latencyMillis, privacy: .public),\"fresh\":\(s.freshInjections, privacy: .public),\"reused\":\(s.reusedInjections, privacy: .public),\"carried\":\(s.carriedInjections, privacy: .public)}" ) } setNeedsLayout() } private func rowMetrics() -> RowMetrics { if let metrics { return metrics } let m = RowMetrics(font: font, lineHeight: lineHeight, tabSize: core.settings.tabSize) metrics = m viewport.rowHeight = m.rowHeight gutter.metrics = m return m } /// The draw's frame: the layout picks the lines, the frame says which need a layout and brings their spans and text. private func readFrame() -> EditorFrame { let usable = highlighter != nil ? snapshot : nil var pairs: [Int32] = [] pairs.reserveCapacity(2 * cache.size) cache.forEachEntry { line, entry in pairs.append(Int32(clamping: line)) pairs.append(Int32(clamping: entry.revision)) } let incremental = usable.map { $0.basedOn >= 0 && $0.basedOn == appliedRevision } ?? false return frameReader.read( core: core, layout: viewport, snapshot: usable, applied: appliedRevision, useChanged: incremental, pairs: pairs) } // Line reads for the geometry and UIKit: from the frame while a draw runs, else one core call. Neither goes // through the document's checked members. fileprivate func docLineAt(_ offset: Int) -> Int { if let frame = drawFrame, let line = frame.lineAt(offset) { return line } return Int(cp_doc_line_at(core.document.handle, Document.unsigned(offset))) } fileprivate func docLineStart(_ line: Int) -> Int { if let frame = drawFrame, let start = frame.lineStart(line) { return start } return Int(cp_doc_line_start(core.document.handle, Int32(clamping: line))) } fileprivate func docLineLength(_ line: Int) -> Int { if let frame = drawFrame, let length = frame.lineLength(line) { return length } let handle = core.document.handle return Int(cp_doc_line_end(handle, Int32(clamping: line))) - Int(cp_doc_line_start(handle, Int32(clamping: line))) } private func takeEntryId() -> Int { nextEntryId += 1 return nextEntryId } private func makeLayout(_ text: [UInt16], spans: [Int]?, _ m: RowMetrics) -> LineLayout { LineLayout( text: text, spans: spans ?? [], font: font, styles: theme, foreground: theme.foreground, metrics: m, wrapWidth: viewport.wrapWidth) } /// Lays out one line plain, for hit tests and reveals on lines outside the drawn range. @discardableResult private func layoutLine(_ line: Int) -> Entry { let entry = plainEntry(line) let scrollBefore = viewport.scrollY viewport.measured(line, entry.layout.rowCount, widest: offeredWidth(entry.layout)) if viewport.scrollY != scrollBefore { pushScroll() } else { updateContentSize() } return entry } /// A plain layout put in the cache and not yet measured. private func plainEntry(_ line: Int) -> Entry { let spans = keptSpans(line, revision: drawFrame?.revision) let text = drawFrame?.text(line) ?? core.document.lineOutsideFrame(line) let entry = Entry(id: takeEntryId(), layout: makeLayout(text, spans: spans, rowMetrics()), spans: spans, revision: -1) cache.put(line, entry) return entry } /// The width a layout offers as the widest line, or -1 while wrapping. private func offeredWidth(_ layout: LineLayout) -> Int { viewport.wrap ? -1 : Int(layout.width().rounded()) } private func onScrolled() { scrollDirty = true setNeedsLayout() } /// Pushes the viewport's scroll into the scroll view after a programmatic change. private func pushScroll() { updateContentSize() let target = CGPoint(x: CGFloat(viewport.scrollX), y: CGFloat(viewport.scrollY)) if contentOffset != target { contentOffset = target } } /// contentSize is the viewport's content plus its insets; the content view starts at the text area and /// reaches the bottom of the visible area at least, so a touch below the last line still places the caret. private func updateContentSize() { let size = CGSize( width: CGFloat(viewport.textAreaLeft + viewport.contentWidth + viewport.insetRight), height: CGFloat(viewport.insetTop + viewport.contentHeight + viewport.insetBottom)) if contentSize != size { contentSize = size } let frame = CGRect( x: CGFloat(viewport.textAreaLeft), y: CGFloat(viewport.insetTop), width: CGFloat(viewport.contentWidth), height: max(CGFloat(viewport.contentHeight), bounds.height - CGFloat(viewport.insetTop))) if textInput.frame != frame { textInput.frame = frame } } private func applyInsets() { let changed = viewport.setInsets( top: Int(contentInsetTop.rounded()), bottom: Int((contentInsetBottom + keyboardInset).rounded()), left: Int(contentInsetLeft.rounded()), right: Int(contentInsetRight.rounded())) if changed { relayout() } else if viewport.clamp() { pushScroll() onScrolled() } else { updateContentSize() setNeedsLayout() } if hasFocus { revealPending = true } } private func sizeChanged(_ w: Int, _ h: Int) { let widthChanged = viewport.resize(width: w, height: h) cache.capacity = max(64, 3 * (h / rowMetrics().rowHeight + 1)) if widthChanged { relayout() } else if viewport.clamp() { pushScroll() onScrolled() } } /// Builds missing layouts for [first, last] with one highlight query per run of dirty lines: the lines the snapshot's /// regions meet when it follows the one last applied, else every line not at its revision. Ends with the draw's /// measure call and returns true when it moved the scroll. private func prepare(_ frame: EditorFrame, _ m: RowMetrics) -> Bool { // The core paints from the snapshot only when it is at the frame's revision. Otherwise its runs are the lines // with no layout, and those take the spans keepSpans kept. let consistent = highlighter != nil && snapshot?.revision == frame.revision let revision = consistent ? frame.revision : -1 let runs = frame.runs var pairs: [Int32] = [] var widest = -1 func measured(_ line: Int, _ layout: LineLayout) { pairs.append(Int32(clamping: line)) pairs.append(Int32(clamping: layout.rowCount)) widest = max(widest, offeredWidth(layout)) } var r = 0 // A run line's insert evicts the oldest layout, which must not be a frame line the loop has not reached yet. for line in frame.first...frame.last { _ = cache[line] } // The spans and text of the run lines arrive in line order, one entry per line. var next = 0 for line in frame.first...frame.last { while r + 1 < runs.count && runs[r + 1] < line { r += 2 } let inRun = r + 1 < runs.count && line >= runs[r] let entry = cache[line] if !inRun { // A clean line keeps its layout and takes the revision without a query. Every line without one is in a run. if let entry, revision >= 0 { entry.revision = revision } continue } let lineSpans = next < frame.spans.count ? frame.spans[next] : [] next += 1 var fresh: [Int]? = nil if consistent { if !lineSpans.isEmpty { fresh = lineSpans } if let entry, entry.spans == fresh { entry.revision = revision continue } } else { fresh = keptSpans(line, revision: frame.revision) } let layout = makeLayout(frame.text(line) ?? [], spans: fresh, m) cache.put(line, Entry(id: takeEntryId(), layout: layout, spans: fresh, revision: consistent ? revision : -1)) measured(line, layout) } if revision >= 0 { appliedRevision = revision pendingSpans = nil pendingTail = nil } // The handles' lines too, so placeHandles finds their layouts without a measurement inside the draw. let sel = core.selection if hasFocus && !sel.isEmpty { for offset in [sel.min, sel.max] { let line = docLineAt(offset) if cache[line] == nil { measured(line, plainEntry(line).layout) } } } return viewport.measure(pairs: pairs, widest: widest, first: frame.first, last: frame.last) } /// The spans keepSpans kept for a line of the current revision, or nil. private func keptSpans(_ line: Int, revision: Int? = nil) -> [Int]? { guard pendingRevision == (revision ?? core.document.revision) else { return nil } if line == pendingLine { return pendingSpans } if line == pendingLine + 1 { return pendingTail } return nil } /// The edited line's previous spans moved along a change that stays inside it, or split by a typed newline. private func keepSpans(_ first: Int, _ oldCount: Int, _ newCount: Int, _ change: Change) { pendingSpans = nil pendingTail = nil guard oldCount == 1, let spans = cache[first]?.spans else { return } let doc = core.document let column = change.start - doc.lineStart(first) let removed = change.removed.utf16.count if newCount == 1 { pendingSpans = shiftSpans(spans, start: column, removed: removed, inserted: change.inserted.utf16.count) } else if newCount == 2, removed == 0, change.inserted.hasPrefix("\n") { let added = change.inserted.utf16.count - 1 pendingTail = shiftSpans(spans, start: 0, removed: column, inserted: added) pendingSpans = shiftSpans(spans, start: column, removed: doc.lineLength(first + 1) - added, inserted: 0) } else { return } pendingLine = first pendingRevision = doc.revision } /// The visible rect grown by half a screen each way, in content view coordinates: a line layer never /// gets a backing store beyond it, so a huge line costs a redraw on scroll instead of a giant bitmap. private func paintWindow() -> CGRect { let w = CGFloat(viewport.textAreaWidth) let h = CGFloat(viewport.height) let grown = CGRect(x: CGFloat(viewport.scrollX) - w / 2, y: CGFloat(viewport.scrollY - viewport.insetTop) - h / 2, width: 2 * w, height: 2 * h) return grown.intersection(CGRect(x: 0, y: 0, width: CGFloat(viewport.contentWidth), height: CGFloat(viewport.contentHeight))) } /// Gives every line from `first` a layer while it is on screen; returns the last line placed. private func placeLayers(_ first: Int, _ lastBound: Int, _ m: RowMetrics) -> Int { let scale = displayScale() let clip = paintWindow() var visible = Set() var lastLine = first var line = first while line <= lastBound { if viewport.lineTop(line) >= viewport.height { break } guard let entry = cache[line] else { break } let full = CGRect( x: 0, y: CGFloat(viewport.rowStart(line) * m.rowHeight), width: CGFloat(viewport.contentWidth), height: CGFloat(entry.layout.rowCount * m.rowHeight)) let clipped = full.intersection(clip) place(entry, clipped.isNull || clipped.isEmpty ? full : clipped, full, scale) visible.insert(entry.id) lastLine = line line += 1 } for (id, layer) in layers where !visible.contains(id) { layers[id] = nil layer.removeFromSuperlayer() layer.layout = nil pool.append(layer) } return lastLine } private func place(_ entry: Entry, _ rect: CGRect, _ full: CGRect, _ scale: CGFloat) { let layer = layers[entry.id] ?? takeLayer(entry) let offset = CGPoint(x: rect.minX - full.minX, y: rect.minY - full.minY) let redraw = layer.layout !== entry.layout || layer.offset != offset || layer.bounds.size != rect.size || layer.contentsScale != scale if layer.frame != rect { layer.frame = rect } if redraw { layer.layout = entry.layout layer.offset = offset layer.contentsScale = scale layer.setNeedsDisplay() } } private func takeLayer(_ entry: Entry) -> LineLayer { let layer = pool.popLast() ?? LineLayer() layer.padding = textPadding textInput.textHost.addSublayer(layer) layers[entry.id] = layer return layer } private func displayScale() -> CGFloat { max(1, window?.screen.scale ?? traitCollection.displayScale) } private func placeGutter(_ first: Int, _ last: Int, _ caretLine: Int) { gutter.isHidden = !lineNumbers if !lineNumbers { return } let frame = CGRect( x: max(contentOffset.x, 0) + CGFloat(viewport.insetLeft), y: CGFloat(viewport.scrollY), width: CGFloat(viewport.gutterWidth), height: bounds.height) if gutter.frame != frame { gutter.frame = frame } var rows: [GutterView.Row] = [] for line in first...last { rows.append(GutterView.Row(number: line + 1, top: CGFloat(viewport.lineTop(line)), active: line == caretLine)) } gutter.update(rows) } /// Fills under the text: the active line, the search matches with the selected one apart, and the bracket pair. private func placeDecorations(_ frame: EditorFrame, _ first: Int, _ lastLine: Int, _ caretLine: Int, _ m: RowMetrics) { let d = textInput.decorations let sel = Selection(anchor: frame.anchor, head: frame.head) if let search, search.active { let windowStart = docLineStart(first) let windowEnd = docLineStart(lastLine) + docLineLength(lastLine) let matches = search.matchesForPaint() let path = CGMutablePath() let active = CGMutablePath() var i = SearchSession.firstEndingAfter(matches, windowStart) * 2 while i + 1 < matches.count && matches[i] <= windowEnd { let current = !sel.isEmpty && sel.min == matches[i] && sel.max == matches[i + 1] Decorations.addRects(current ? active : path, geometry, start: matches[i], end: matches[i + 1], firstLine: first) i += 2 } d.setMatches(path.isEmpty ? nil : path, active: active.isEmpty ? nil : active) } else { d.setMatches(nil, active: nil) } if highlightActiveLine && sel.isEmpty { d.setActiveLine( CGRect( x: 0, y: CGFloat(viewport.rowStart(caretLine) * m.rowHeight), width: CGFloat(viewport.contentWidth), height: CGFloat(viewport.rows(caretLine) * m.rowHeight))) } else { d.setActiveLine(nil) } let consistent = snapshot.flatMap { $0.revision == frame.revision ? $0 : nil } if let pair = brackets.pair(snapshot: consistent, revision: frame.revision, head: frame.head) { let path = CGMutablePath() for offset in [pair.0, pair.1] { Decorations.addRects(path, geometry, start: offset, end: offset + 1, firstLine: first) } d.setBrackets(path.isEmpty ? nil : path) } else { d.setBrackets(nil) } placeAppDecorations(first, lastLine, m) } /// The app's line backgrounds and underlines over the visible lines, in content coordinates like the fills. private func placeAppDecorations(_ first: Int, _ lastLine: Int, _ m: RowMetrics) { let items = core.decorations.items let layers = textInput.decorationLayers if items.isEmpty { layers.clear() return } let scale = displayScale() // An underline starting below the window would cost a layout call to find that out. let windowEnd = docLineStart(lastLine) + docLineLength(lastLine) var backgrounds = DecorationLayers.Batch() var underlines = DecorationLayers.Batch() for item in items { switch item { case .lineBackground(let line, let color): if line < first || line > lastLine { continue } let rect = CGRect( x: 0, y: CGFloat(viewport.rowStart(line) * m.rowHeight), width: CGFloat(viewport.contentWidth), height: CGFloat(viewport.rows(line) * m.rowHeight)) backgrounds.path(DecorationLayers.Paint(color: color, width: 0)).addRect(rect) case .underline(let u): if u.start > windowEnd { continue } let thickness = CGFloat(u.thickness) RangeRects.forEach(geometry, start: u.start, end: u.end, firstLine: first, padNewline: false) { left, top, right, _ in let lineTop = top + m.ascent + CGFloat(u.offset) if u.style == .solid { // Whole pixels, so the line stays as crisp as a browser draws it. let y = (lineTop * scale).rounded() / scale let height = max(1, (thickness * scale).rounded()) / scale underlines.path(DecorationLayers.Paint(color: u.color, width: 0)) .addRect(CGRect(x: left, y: y, width: right - left, height: height)) } else { let path = underlines.path(DecorationLayers.Paint(color: u.color, width: thickness)) WaveGeometry.add( to: path, left: left, right: right, centre: lineTop + WaveGeometry.centre(thickness), thickness: thickness) } } case .gap: continue } } layers.set(backgrounds: backgrounds, underlines: underlines) } /// A one point line along the bottom of every row of the marked text, the composing cue. private func placeMarkedUnderline(_ first: Int) { let underline = textInput.markedUnderline guard let marked = textInput.session.marked else { underline.isHidden = true return } var strips: [CGRect] = [] Decorations.forEachRect(geometry, start: marked.start, end: marked.end, firstLine: first) { rect in strips.append(CGRect(x: rect.minX, y: rect.maxY - 1, width: rect.width, height: 1)) } guard let bounds = strips.dropFirst().reduce(strips.first, { $0?.union($1) }) else { underline.isHidden = true return } let path = CGMutablePath() for strip in strips { path.addRect(strip.offsetBy(dx: -bounds.minX, dy: -bounds.minY)) } underline.frame = bounds underline.path = path underline.isHidden = false } /// The handles wrap the caret rects of a ranged selection while the editor has focus. private func placeHandles() { let sel = core.selection let shown = hasFocus && !sel.isEmpty for (handle, offset) in zip(textInput.handleViews, [sel.min, sel.max]) { handle.isHidden = !shown if !shown { continue } let frame = handle.preferredFrame(for: caretRect(offset: offset)) if handle.frame != frame { handle.frame = frame } } } /// One layer in gutterForeground on the first row while the document is empty. private func placePlaceholder(_ frame: EditorFrame, _ m: RowMetrics) { guard let placeholder, frame.length == 0 else { placeholderLayer?.isHidden = true return } let layer: LineLayer if let existing = placeholderLayer { layer = existing } else { layer = LineLayer() layer.padding = textPadding textInput.textHost.addSublayer(layer) placeholderLayer = layer } if placeholderLayout == nil { placeholderLayout = LineLayout( text: Array(placeholder.utf16), spans: [], font: font, styles: theme, foreground: theme.gutterForeground, metrics: m, wrapWidth: 0) } let frame = CGRect(x: 0, y: 0, width: CGFloat(viewport.contentWidth), height: CGFloat(m.rowHeight)) let scale = displayScale() if layer.layout !== placeholderLayout || layer.frame != frame || layer.contentsScale != scale { layer.layout = placeholderLayout layer.frame = frame layer.contentsScale = scale layer.setNeedsDisplay() } layer.isHidden = false } /// The caret rect in visible area points, nil while the line has no layout. private func caretRect(_ m: RowMetrics, line: Int) -> CGRect? { guard let entry = cache[line] else { return nil } let col = core.selection.head - docLineStart(line) let x = viewport.viewX(entry.layout.caretX(col)) let top = CGFloat(viewport.lineTop(line) + entry.layout.rowOf(col) * m.rowHeight) return CGRect(x: x, y: top, width: CodeEditorView.caretWidth, height: CGFloat(m.rowHeight)) } /// Every gap in view points, sorted by line, the full view width wide. private func gapRects(_ m: RowMetrics) -> [GapRect] { viewport.gaps().map { gap in let rect = CGRect(x: 0, y: CGFloat(gap.top), width: bounds.width, height: CGFloat(gap.rows * m.rowHeight)) return GapRect(line: gap.line, rect: rect) } } private func publish(_ first: Int, _ last: Int, _ caretLine: Int, _ m: RowMetrics) { let gaps = gapRects(m) if gaps != latestFrame.gaps { gapsDirty = true } let frame = FrameInfo( firstLine: first, lastLine: last, caret: caretRect(m, line: caretLine), scrollX: CGFloat(viewport.scrollX), scrollY: CGFloat(viewport.scrollY), contentWidth: CGFloat(viewport.contentWidth), contentHeight: CGFloat(viewport.contentHeight), gaps: gaps) frameLock.withLock { $0 = frame } let size = CGSize( width: CGFloat(viewport.textAreaLeft + viewport.contentWidth + viewport.insetRight), height: CGFloat(viewport.insetTop + viewport.contentHeight + viewport.insetBottom) - keyboardInset) if size != lastContentSize { lastContentSize = size contentDirty = true } } // Re-read at most once a second, so the setting can be flipped while the editor stays up. private func debugSwitch() -> Bool { let now = CACurrentMediaTime() if now - debugChecked > 1 { debugChecked = now debugOn = DebugSwitch.isOn } return debugOn } private func logPaint() { if inputTime == 0 { return } let now = CACurrentMediaTime() let latency = Int(((now - inputTime) * 1000).rounded()) let work = Int(((inputWork + now - frameStart) * 1000).rounded()) DebugSwitch.log.info("{\"call\":\"paint\",\"latency\":\(latency, privacy: .public),\"work\":\(work, privacy: .public)}") inputWork = 0 inputTime = 0 } /// One line per scrolled frame with its layout time, for the scroll bench. private func logFrame() { if !debugSwitch() { return } let elapsed = CACurrentMediaTime() - frameStart let ms = Int((elapsed * 1000).rounded()) let us = Int((elapsed * 1_000_000).rounded()) DebugSwitch.log.info("{\"call\":\"frame\",\"ms\":\(ms, privacy: .public),\"us\":\(us, privacy: .public)}") } }