SPB Git

Repository Public

ScriptEditor.swift 51.8 KB 1,024 lines swift

1// ORIX DJ2// File: App/Sources/Features/AutomationStudio/ScriptEditor.swift3// Description: The ORIX Script code editor: an AppKit text view (TextKit 1) with syntax colouring, a gutter with line4//              numbers, breakpoints, diagnostics and fold controls, squiggly underlines, bracket matching, auto-indent,5//              real code folding, autocomplete and the native find bar.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import AppKit10import ORIXDJCore11import SwiftUI1213/// Commands the editor forwards to the studio (keyboard shortcuts typed while the editor has the focus).14enum EditorCommand: Sendable { case save, saveAs, run, stop, validate, simulate, format }1516/// The autocomplete popup: what to show and where (in the editor view's coordinates, origin top-left).17struct CompletionPopup: Equatable {18    var items: [Completion]19    var selected = 020    /// Bottom-left of the word being completed.21    var anchor: CGPoint22    var lineHeight: CGFloat23    var prefixRange: NSRange24}2526enum EditorColors {27    static func token(_ c: TokenClass) -> NSColor {28        switch c {29        case .keyword: NSColor(ORIX.Palette.accent)30        case .root: NSColor(ORIX.Palette.accentSecondary)31        case .number: NSColor(ORIX.Palette.warning)32        case .string: NSColor(ORIX.Palette.success)33        case .comment: NSColor(ORIX.Palette.textTertiary)34        case .symbol: NSColor(ORIX.Palette.textSecondary)35        case .identifier: NSColor(ORIX.Palette.textPrimary)36        }37    }3839    static func severity(_ s: DiagnosticSeverity) -> NSColor {40        switch s {41        case .error: NSColor(ORIX.Palette.danger)42        case .warning: NSColor(ORIX.Palette.warning)43        case .note: NSColor(ORIX.Palette.accentSecondary)44        }45    }4647    static var font: NSFont { NSFont.monospacedSystemFont(ofSize: 12.5, weight: .regular) }48}4950/// Draws diagnostics underlines as squiggles.51final class CodeLayoutManager: NSLayoutManager {52    override func drawUnderline(forGlyphRange glyphRange: NSRange, underlineType underlineVal: NSUnderlineStyle, baselineOffset: CGFloat,53                                lineFragmentRect lineRect: NSRect, lineFragmentGlyphRange lineGlyphRange: NSRange, containerOrigin: NSPoint) {54        guard let container = textContainers.first else { return }55        let charIndex = characterIndexForGlyph(at: glyphRange.location)56        let color = (temporaryAttribute(.underlineColor, atCharacterIndex: charIndex, effectiveRange: nil) as? NSColor) ?? .systemRed57        var rect = boundingRect(forGlyphRange: glyphRange, in: container)58        rect.origin.x += containerOrigin.x; rect.origin.y += containerOrigin.y59        rect.size.width = max(rect.width, 6)60        let y = rect.maxY - 1.561        let path = NSBezierPath()62        path.lineWidth = 1.263        var x = rect.minX64        var up = true65        path.move(to: NSPoint(x: x, y: y))66        while x < rect.maxX {67            let next = min(x + 2.5, rect.maxX)68            path.line(to: NSPoint(x: next, y: y + (up ? -2 : 0)))69            x = next; up.toggle()70        }71        color.setStroke()72        path.stroke()73    }74}7576/// Hides folded character ranges by generating null glyphs for them.77final class FoldingDelegate: NSObject, NSLayoutManagerDelegate {78    var folds: [NSRange] = []7980    func isFolded(_ index: Int) -> Bool { folds.contains { NSLocationInRange(index, $0) } }8182    func layoutManager(_ layoutManager: NSLayoutManager, shouldGenerateGlyphs glyphs: UnsafePointer<CGGlyph>, properties props: UnsafePointer<NSLayoutManager.GlyphProperty>,83                       characterIndexes charIndexes: UnsafePointer<Int>, font aFont: NSFont, forGlyphRange glyphRange: NSRange) -> Int {84        guard !folds.isEmpty else { return 0 }85        var changed = false86        var modified = [NSLayoutManager.GlyphProperty](repeating: [], count: glyphRange.length)87        for i in 0 ..< glyphRange.length {88            // Hidden text gets null glyphs; hidden line breaks stay control characters and are given no advancement below.89            if isFolded(charIndexes[i]) { modified[i] = props[i].contains(.controlCharacter) ? .controlCharacter : .null; changed = true } else { modified[i] = props[i] }90        }91        guard changed else { return 0 }92        modified.withUnsafeBufferPointer { buffer in93            layoutManager.setGlyphs(glyphs, properties: buffer.baseAddress!, characterIndexes: charIndexes, font: aFont, forGlyphRange: glyphRange)94        }95        return glyphRange.length96    }9798    func layoutManager(_ layoutManager: NSLayoutManager, shouldUse action: NSLayoutManager.ControlCharacterAction, forControlCharacterAt charIndex: Int) -> NSLayoutManager.ControlCharacterAction {99        isFolded(charIndex) ? .zeroAdvancement : action100    }101}102103/// One editor per open document: owns the text view, its undo history, folds and breakpoints.104@MainActor @Observable105final class CodeEditorController: NSObject, NSTextViewDelegate {106    let docID: UUID107    @ObservationIgnored let scrollView = NSScrollView()108    @ObservationIgnored let textView: CodeTextView109    @ObservationIgnored private let layout = CodeLayoutManager()110    @ObservationIgnored private let folding = FoldingDelegate()111    @ObservationIgnored private var gutter: CodeGutterView!112113    var completion: CompletionPopup?114115    @ObservationIgnored var onTextChange: ((String) -> Void)?116    /// Path under the caret, line and column (1-based).117    @ObservationIgnored var onCaret: ((String?, Int, Int) -> Void)?118    @ObservationIgnored var onHover: ((String?) -> Void)?119    @ObservationIgnored var onBreakpointsChange: ((Set<Int>) -> Void)?120    @ObservationIgnored var onCommand: ((EditorCommand) -> Void)?121122    @ObservationIgnored private(set) var breakpoints: Set<Int> = []123    @ObservationIgnored private(set) var diagnostics: [Diagnostic] = []124    @ObservationIgnored private(set) var pausedLine: Int?125    @ObservationIgnored private(set) var lineStarts: [Int] = [0]126    /// Matching bracket pairs (UTF-16 offsets of the opener and the closer), from the lexer's symbol tokens.127    @ObservationIgnored private(set) var bracketPairs: [(open: Int, close: Int)] = []128    @ObservationIgnored private var matchedBrackets: [Int] = []129    @ObservationIgnored private var highlightGeneration = 0130    @ObservationIgnored private var applyingExternalText = false131132    init(docID: UUID, source: String) {133        self.docID = docID134        let storage = NSTextStorage(string: source, attributes: [.font: EditorColors.font, .foregroundColor: NSColor(ORIX.Palette.textPrimary)])135        let container = NSTextContainer(size: NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude))136        container.widthTracksTextView = true137        container.lineFragmentPadding = 6138        layout.addTextContainer(container)139        storage.addLayoutManager(layout)140        textView = CodeTextView(frame: .zero, textContainer: container)141        super.init()142        layout.delegate = folding143        layout.allowsNonContiguousLayout = false144145        textView.controller = self146        textView.delegate = self147        textView.isRichText = false148        textView.allowsUndo = true149        textView.usesFindBar = true150        textView.isIncrementalSearchingEnabled = true151        textView.isAutomaticQuoteSubstitutionEnabled = false152        textView.isAutomaticDashSubstitutionEnabled = false153        textView.isAutomaticTextReplacementEnabled = false154        textView.isAutomaticSpellingCorrectionEnabled = false155        textView.isContinuousSpellCheckingEnabled = false156        textView.isGrammarCheckingEnabled = false157        textView.isAutomaticLinkDetectionEnabled = false158        textView.smartInsertDeleteEnabled = false159        textView.font = EditorColors.font160        textView.typingAttributes = [.font: EditorColors.font, .foregroundColor: NSColor(ORIX.Palette.textPrimary)]161        textView.textColor = NSColor(ORIX.Palette.textPrimary)162        textView.backgroundColor = NSColor(ORIX.Palette.surface)163        textView.insertionPointColor = NSColor(ORIX.Palette.accent)164        textView.selectedTextAttributes = [.backgroundColor: NSColor(ORIX.Palette.accent).withAlphaComponent(0.28)]165        textView.textContainerInset = NSSize(width: 2, height: 6)166        textView.isVerticallyResizable = true167        textView.isHorizontallyResizable = false168        textView.autoresizingMask = [.width]169        textView.minSize = NSSize(width: 0, height: 0)170        textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)171        textView.clipsToBounds = true172        textView.setAccessibilityLabel(String(localized: "Script editor"))173        textView.setAccessibilityIdentifier("automation-editor")174175        scrollView.documentView = textView176        scrollView.hasVerticalScroller = true177        scrollView.hasHorizontalScroller = false178        scrollView.autohidesScrollers = true179        scrollView.drawsBackground = true180        scrollView.backgroundColor = NSColor(ORIX.Palette.surface)181        scrollView.borderType = .noBorder182183        gutter = CodeGutterView(scrollView: scrollView, controller: self)184        scrollView.verticalRulerView = gutter185        scrollView.hasVerticalRuler = true186        scrollView.rulersVisible = true187188        textDidChangeInternal(notify: false)189    }190191    var text: String { textView.string }192193    // MARK: Synchronisation with the studio194195    /// Brings the editor in line with the document and the studio state. Cheap when nothing changed.196    func sync(source: String, diagnostics: [Diagnostic], breakpoints: Set<Int>, pausedLine: Int?) {197        if source != textView.string { replaceAll(with: source, undoable: true) }198        if diagnostics != self.diagnostics { self.diagnostics = diagnostics; applyDiagnostics() }199        if breakpoints != self.breakpoints { self.breakpoints = breakpoints; gutter.needsDisplay = true }200        if pausedLine != self.pausedLine {201            self.pausedLine = pausedLine202            textView.needsDisplay = true; gutter.needsDisplay = true203            if let pausedLine { reveal(line: pausedLine, select: false) }204        }205    }206207    func focus() { textView.window?.makeFirstResponder(textView) }208209    /// Replaces the whole text (Format, restoring a version) as one undoable edit, keeping the caret on its line.210    func replaceAll(with new: String, undoable: Bool) {211        let caretLine = line(at: textView.selectedRange().location)212        let full = NSRange(location: 0, length: textView.textStorage?.length ?? 0)213        applyingExternalText = true214        if undoable, textView.shouldChangeText(in: full, replacementString: new) {215            textView.textStorage?.replaceCharacters(in: full, with: new)216            textView.didChangeText()217        } else {218            textView.textStorage?.replaceCharacters(in: full, with: new)219            textDidChangeInternal(notify: false)220        }221        applyingExternalText = false222        let start = lineStarts[min(max(caretLine - 1, 0), lineStarts.count - 1)]223        textView.setSelectedRange(NSRange(location: min(start, (new as NSString).length), length: 0))224    }225226    // MARK: Lines227228    private func recomputeLineStarts() {229        let s = textView.string as NSString230        var starts = [0]231        var i = 0232        let n = s.length233        while i < n {234            if s.character(at: i) == 10 { starts.append(i + 1) }235            i += 1236        }237        lineStarts = starts238    }239240    /// 1-based line containing the UTF-16 offset.241    func line(at offset: Int) -> Int {242        var lo = 0, hi = lineStarts.count - 1243        while lo < hi {244            let mid = (lo + hi + 1) / 2245            if lineStarts[mid] <= offset { lo = mid } else { hi = mid - 1 }246        }247        return lo + 1248    }249250    func range(ofLine line: Int) -> NSRange? {251        guard line >= 1, line <= lineStarts.count else { return nil }252        let start = lineStarts[line - 1]253        let end = line < lineStarts.count ? lineStarts[line] - 1 : (textView.string as NSString).length254        return NSRange(location: start, length: max(0, end - start))255    }256257    /// UTF-16 range of a diagnostic (its column and length count characters).258    private func range(of d: Diagnostic) -> NSRange? {259        let s = textView.string as NSString260        guard let lineRange = range(ofLine: min(d.location.line, lineStarts.count)) else { return nil }261        let lineText = s.substring(with: lineRange)262        let prefix = String(lineText.prefix(max(0, d.location.column - 1)))263        let token = String(lineText.dropFirst(prefix.count).prefix(d.length))264        var r = NSRange(location: lineRange.location + prefix.utf16.count, length: token.utf16.count)265        if r.length == 0 {266            // End of line or end of script: underline the last character before it.267            if r.location > lineRange.location { r = NSRange(location: r.location - 1, length: 1) }268            else if r.location < s.length, s.character(at: r.location) != 10 { r.length = 1 }269            else { return nil }270        }271        return r272    }273274    func reveal(line: Int, column: Int = 1, select: Bool = true) {275        guard let r = range(ofLine: line) else { return }276        unfold(containing: r.location)277        let lineText = (textView.string as NSString).substring(with: r)278        let offset = String(lineText.prefix(max(0, column - 1))).utf16.count279        let target = select ? NSRange(location: r.location + min(offset, r.length), length: 0) : r280        if select { textView.setSelectedRange(target); focus() }281        textView.scrollRangeToVisible(target)282    }283284    func selectLine(_ line: Int) {285        guard let r = range(ofLine: line) else { return }286        unfold(containing: r.location)287        textView.setSelectedRange(r)288        textView.scrollRangeToVisible(r)289        focus()290    }291292    // MARK: Text changes293294    func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {295        guard !applyingExternalText, let replacement = replacementString else { return true }296        let s = textView.string as NSString297        guard NSMaxRange(affectedCharRange) <= s.length else { return true }298        let removed = s.substring(with: affectedCharRange)299        let lineDelta = replacement.filter { $0 == "\n" }.count - removed.filter { $0 == "\n" }.count300        let delta = (replacement as NSString).length - affectedCharRange.length301        // Folds touched by the edit open; folds after it move with the text.302        var folds = folding.folds303        let before = folds304        folds.removeAll { NSMaxRange($0) >= affectedCharRange.location && $0.location <= NSMaxRange(affectedCharRange) }305        folds = folds.map { $0.location > affectedCharRange.location ? NSRange(location: $0.location + delta, length: $0.length) : $0 }306        if folds != before { folding.folds = folds }307        if lineDelta != 0, !breakpoints.isEmpty {308            let editLine = line(at: affectedCharRange.location)309            let lastRemoved = line(at: NSMaxRange(affectedCharRange))310            var moved: Set<Int> = []311            for b in breakpoints {312                if b <= editLine { moved.insert(b) }313                else if lineDelta < 0, b <= lastRemoved { continue }314                else { moved.insert(b + lineDelta) }315            }316            if moved != breakpoints { breakpoints = moved; onBreakpointsChange?(moved) }317        }318        return true319    }320321    func textDidChange(_ notification: Notification) { textDidChangeInternal(notify: true) }322323    private func textDidChangeInternal(notify: Bool) {324        recomputeLineStarts()325        rehighlight()326        if notify { onTextChange?(textView.string) }327        gutter?.needsDisplay = true328        if completion != nil { updateCompletion(force: false) }329    }330331    private func rehighlight() {332        highlightGeneration += 1333        let generation = highlightGeneration334        let source = textView.string335        if source.utf16.count < 30000 {336            apply(spans: Lexer.highlight(source), source: source)337        } else {338            // Large scripts are tokenised off the main thread; stale results are dropped.339            Task.detached(priority: .userInitiated) { [weak self] in340                let spans = Lexer.highlight(source)341                await MainActor.run {342                    guard let self, self.highlightGeneration == generation else { return }343                    self.apply(spans: spans, source: source)344                }345            }346        }347    }348349    private func apply(spans: [HighlightSpan], source: String) {350        let s = source as NSString351        let full = NSRange(location: 0, length: s.length)352        guard full.length == textView.textStorage?.length else { return }353        layout.removeTemporaryAttribute(.foregroundColor, forCharacterRange: full)354        var stack: [(Character, Int)] = []355        var pairs: [(open: Int, close: Int)] = []356        for span in spans where span.range.upperBound <= s.length {357            let r = NSRange(location: span.range.lowerBound, length: span.range.count)358            if span.tokenClass != .identifier { layout.addTemporaryAttribute(.foregroundColor, value: EditorColors.token(span.tokenClass), forCharacterRange: r) }359            guard span.tokenClass == .symbol, r.length == 1, let scalar = UnicodeScalar(s.character(at: r.location)) else { continue }360            let c = Character(scalar)361            if "{([".contains(c) { stack.append((c, r.location)) }362            else if let opener: Character = c == "}" ? "{" : (c == ")" ? "(" : (c == "]" ? "[" : nil)) {363                if let i = stack.lastIndex(where: { $0.0 == opener }) { pairs.append((stack[i].1, r.location)); stack.removeSubrange(i...) }364            }365        }366        bracketPairs = pairs367        // Folds must still sit exactly between a brace pair; anything else opens.368        let valid = folding.folds.filter { f in pairs.contains { $0.open + 1 == f.location && $0.close == NSMaxRange(f) } }369        if valid != folding.folds { setFolds(valid) }370        applyDiagnostics()371        refreshMarks()372    }373374    private func applyDiagnostics() {375        let full = NSRange(location: 0, length: textView.textStorage?.length ?? 0)376        layout.removeTemporaryAttribute(.underlineStyle, forCharacterRange: full)377        layout.removeTemporaryAttribute(.underlineColor, forCharacterRange: full)378        layout.removeTemporaryAttribute(.toolTip, forCharacterRange: full)379        // Errors last so they win where ranges overlap.380        for d in diagnostics.sorted(by: { $0.severity != .error && $1.severity == .error }) {381            guard let r = range(of: d), NSMaxRange(r) <= full.length else { continue }382            layout.addTemporaryAttributes([.underlineStyle: NSUnderlineStyle.thick.rawValue, .underlineColor: EditorColors.severity(d.severity),383                                           .toolTip: "\(d.severity.rawValue.capitalized): \(d.message) [\(d.code)]"], forCharacterRange: r)384        }385        gutter?.needsDisplay = true386    }387388    func severity(onLine line: Int) -> DiagnosticSeverity? {389        var found: DiagnosticSeverity?390        for d in diagnostics where d.location.line == line {391            if d.severity == .error { return .error }392            if d.severity == .warning || found == nil { found = d.severity }393        }394        return found395    }396397    // MARK: Brackets and folds398399    /// Background marks: the bracket pair next to the caret and the braces of folded blocks.400    private func refreshMarks() {401        let length = textView.textStorage?.length ?? 0402        layout.removeTemporaryAttribute(.backgroundColor, forCharacterRange: NSRange(location: 0, length: length))403        for f in folding.folds where f.location >= 1 && NSMaxRange(f) < length {404            let mark = NSColor(ORIX.Palette.accentSecondary).withAlphaComponent(0.3)405            layout.addTemporaryAttribute(.backgroundColor, value: mark, forCharacterRange: NSRange(location: f.location - 1, length: 1))406            layout.addTemporaryAttribute(.backgroundColor, value: mark, forCharacterRange: NSRange(location: NSMaxRange(f), length: 1))407        }408        matchedBrackets = []409        let sel = textView.selectedRange()410        guard sel.length == 0 else { return }411        let pair = bracketPairs.first { $0.open == sel.location || $0.close == sel.location - 1 } ?? bracketPairs.first { $0.open == sel.location - 1 || $0.close == sel.location }412        guard let pair, pair.close < length else { return }413        matchedBrackets = [pair.open, pair.close]414        for i in matchedBrackets {415            layout.addTemporaryAttribute(.backgroundColor, value: NSColor(ORIX.Palette.accent).withAlphaComponent(0.35), forCharacterRange: NSRange(location: i, length: 1))416        }417    }418419    /// The brace block that can be folded from this line: an opening brace whose partner is on a later line.420    func foldablePair(onLine line: Int) -> (open: Int, close: Int)? {421        guard let r = range(ofLine: line) else { return nil }422        let s = textView.string as NSString423        return bracketPairs.filter { NSLocationInRange($0.open, r) && s.character(at: $0.open) == 123 && self.line(at: $0.close) > line }.max { $0.open < $1.open }424    }425426    func isFolded(line: Int) -> Bool {427        guard let p = foldablePair(onLine: line) else { return false }428        return folding.folds.contains { $0.location == p.open + 1 }429    }430431    func toggleFold(line: Int) {432        guard let p = foldablePair(onLine: line) else { return }433        var folds = folding.folds434        if let i = folds.firstIndex(where: { $0.location == p.open + 1 }) { folds.remove(at: i) }435        else {436            let range = NSRange(location: p.open + 1, length: p.close - p.open - 1)437            guard range.length > 0 else { return }438            // Folding an outer block absorbs folds inside it; the caret leaves the hidden text.439            folds.removeAll { NSIntersectionRange($0, range).length > 0 }440            folds.append(range)441            let sel = textView.selectedRange()442            if NSIntersectionRange(sel, range).length > 0 || NSLocationInRange(sel.location, range) { textView.setSelectedRange(NSRange(location: p.open, length: 0)) }443        }444        setFolds(folds)445        refreshMarks()446    }447448    private func setFolds(_ folds: [NSRange]) {449        folding.folds = folds450        let full = NSRange(location: 0, length: textView.textStorage?.length ?? 0)451        layout.invalidateGlyphs(forCharacterRange: full, changeInLength: 0, actualCharacterRange: nil)452        layout.invalidateLayout(forCharacterRange: full, actualCharacterRange: nil)453        textView.needsDisplay = true454        gutter?.needsDisplay = true455    }456457    private func unfold(containing offset: Int) {458        let remaining = folding.folds.filter { !NSLocationInRange(offset, $0) }459        if remaining.count != folding.folds.count { setFolds(remaining); refreshMarks() }460    }461462    var foldCount: Int { folding.folds.count }463464    // MARK: Selection, documentation465466    func textViewDidChangeSelection(_ notification: Notification) {467        let sel = textView.selectedRange()468        // A caret that lands in hidden text (search, go to line) opens the fold.469        if folding.folds.contains(where: { sel.location > $0.location && sel.location < NSMaxRange($0) }) { unfold(containing: sel.location) }470        refreshMarks()471        textView.needsDisplay = true472        gutter?.needsDisplay = true473        let l = line(at: sel.location)474        let lineStart = lineStarts[l - 1]475        let column = (textView.string as NSString).substring(with: NSRange(location: lineStart, length: max(0, min(sel.location, (textView.string as NSString).length) - lineStart))).count + 1476        onCaret?(path(at: sel.location), l, column)477        if let c = completion, !(sel.length == 0 && sel.location >= c.prefixRange.location && sel.location <= NSMaxRange(c.prefixRange) + 64) { completion = nil }478    }479480    private static func isPathCharacter(_ c: unichar) -> Bool {481        (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 || c == 46482    }483484    /// The dotted path around a UTF-16 offset, e.g. "deck.A.filter.highpass".485    func path(at offset: Int) -> String? {486        let s = textView.string as NSString487        guard offset >= 0, offset <= s.length else { return nil }488        var start = offset, end = offset489        while start > 0, Self.isPathCharacter(s.character(at: start - 1)) { start -= 1 }490        while end < s.length, Self.isPathCharacter(s.character(at: end)) { end += 1 }491        guard end > start else { return nil }492        let text = s.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: CharacterSet(charactersIn: "."))493        guard let first = text.unicodeScalars.first, !CharacterSet.decimalDigits.contains(first) else { return nil }494        return text.isEmpty ? nil : text495    }496497    func hover(at point: NSPoint) {498        guard let container = textView.textContainer else { return }499        let p = NSPoint(x: point.x - textView.textContainerOrigin.x, y: point.y - textView.textContainerOrigin.y)500        var fraction: CGFloat = 0501        let glyph = layout.glyphIndex(for: p, in: container, fractionOfDistanceThroughGlyph: &fraction)502        let rect = layout.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: container)503        guard rect.insetBy(dx: -2, dy: -2).contains(p) else { onHover?(nil); return }504        onHover?(path(at: layout.characterIndexForGlyph(at: glyph)))505    }506507    // MARK: Breakpoints508509    func toggleBreakpoint(line: Int) {510        if breakpoints.contains(line) { breakpoints.remove(line) } else { breakpoints.insert(line) }511        gutter.needsDisplay = true512        onBreakpointsChange?(breakpoints)513    }514515    // MARK: Autocomplete516517    /// Names declared with `let`, `var`, `for` or as function parameters, offered next to the keywords.518    private func declaredNames() -> [String] {519        var names: [String] = []520        var lexer = Lexer(textView.string)521        let tokens = lexer.tokenize()522        for (i, t) in tokens.enumerated() where i + 1 < tokens.count {523            if case let .identifier(word) = t.kind, ["let", "var", "for", "fn"].contains(word), case let .identifier(name) = tokens[i + 1].kind, !names.contains(name) { names.append(name) }524        }525        return names526    }527528    func updateCompletion(force: Bool) {529        let sel = textView.selectedRange()530        guard sel.length == 0, let container = textView.textContainer else { completion = nil; return }531        let s = textView.string as NSString532        var start = sel.location533        while start > 0, Self.isPathCharacter(s.character(at: start - 1)) { start -= 1 }534        let prefixRange = NSRange(location: start, length: sel.location - start)535        let prefix = s.substring(with: prefixRange)536        if prefix.isEmpty, !force { completion = nil; return }537        if let first = prefix.unicodeScalars.first, CharacterSet.decimalDigits.contains(first) || first == "." { completion = nil; return }538        let items = Autocomplete.completions(for: prefix, variables: declaredNames())539        guard !items.isEmpty else { completion = nil; return }540        let glyphRange = layout.glyphRange(forCharacterRange: NSRange(location: start, length: 0), actualCharacterRange: nil)541        var rect = layout.boundingRect(forGlyphRange: glyphRange, in: container)542        if start >= s.length, s.length > 0, s.character(at: s.length - 1) == 10 { rect = layout.extraLineFragmentRect }543        rect.origin.x += textView.textContainerOrigin.x; rect.origin.y += textView.textContainerOrigin.y544        let inHost = scrollView.convert(rect, from: textView)545        // The scroll view is not flipped: convert to a top-left origin for SwiftUI.546        let top = scrollView.isFlipped ? inHost.minY : scrollView.bounds.height - inHost.maxY547        let selected = completion.map { old in items.firstIndex { $0.id == old.items[min(old.selected, old.items.count - 1)].id } ?? 0 } ?? 0548        completion = CompletionPopup(items: items, selected: selected, anchor: CGPoint(x: inHost.minX, y: top + inHost.height), lineHeight: max(14, inHost.height), prefixRange: prefixRange)549    }550551    func moveCompletion(_ delta: Int) {552        guard var c = completion else { return }553        c.selected = (c.selected + delta + c.items.count) % c.items.count554        completion = c555    }556557    func acceptCompletion(index: Int? = nil) {558        guard let c = completion else { return }559        let item = c.items[min(index ?? c.selected, c.items.count - 1)]560        completion = nil561        // Actions and builtins arrive as signatures ("seek(position: duration)"): insert the call with the caret inside.562        var insert = item.insert563        var caretBack = 0564        if let paren = insert.firstIndex(of: "(") {565            let hasParameters = !insert[insert.index(after: paren)...].hasPrefix(")")566            insert = String(insert[..<paren]) + "()"567            caretBack = hasParameters ? 1 : 0568        }569        let sel = textView.selectedRange()570        let range = NSRange(location: c.prefixRange.location, length: max(0, sel.location - c.prefixRange.location))571        guard NSMaxRange(range) <= (textView.string as NSString).length, textView.shouldChangeText(in: range, replacementString: insert) else { return }572        textView.textStorage?.replaceCharacters(in: range, with: insert)573        textView.didChangeText()574        textView.setSelectedRange(NSRange(location: range.location + (insert as NSString).length - caretBack, length: 0))575        focus()576    }577578    /// Drives the editor for screenshots and UI tests (`-ORIXAutomationEditorActions`): "caret=L:C", "type=text",579    /// "fold=L", "complete", "return", separated by ";". Typing goes through the same path as the keyboard.580    func perform(actions: String) {581        for action in actions.split(separator: ";") {582            let parts = action.split(separator: "=", maxSplits: 1).map(String.init)583            switch parts[0] {584            case "caret":585                let lc = (parts.count > 1 ? parts[1] : "1:1").split(separator: ":").compactMap { Int($0) }586                reveal(line: lc.first ?? 1, column: lc.count > 1 ? lc[1] : 1)587            case "type": for c in parts.count > 1 ? parts[1] : "" { textView.insertText(String(c), replacementRange: textView.selectedRange()) }588            case "fold": if let l = parts.count > 1 ? Int(parts[1]) : nil { toggleFold(line: l) }589            case "complete": updateCompletion(force: true)590            case "return": textView.insertNewline(nil)591            default: break592            }593        }594    }595596    func appearanceChanged() {597        textView.backgroundColor = NSColor(ORIX.Palette.surface)598        scrollView.backgroundColor = NSColor(ORIX.Palette.surface)599        rehighlight()600        gutter.needsDisplay = true601    }602603    // Drawing helpers used by the text view and the gutter.604    func lineRect(forLine line: Int) -> NSRect? {605        guard let r = range(ofLine: line), let container = textView.textContainer else { return nil }606        let s = textView.string as NSString607        if r.location >= s.length, layout.extraLineFragmentTextContainer != nil {608            return layout.extraLineFragmentRect.offsetBy(dx: 0, dy: textView.textContainerOrigin.y)609        }610        guard s.length > 0 else { return NSRect(x: 0, y: textView.textContainerOrigin.y, width: container.size.width, height: layout.defaultLineHeight(for: EditorColors.font)) }611        let glyph = layout.glyphIndexForCharacter(at: min(r.location, s.length - 1))612        return layout.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil).offsetBy(dx: 0, dy: textView.textContainerOrigin.y)613    }614615    var layoutManager: NSLayoutManager { layout }616}617618final class CodeTextView: NSTextView {619    weak var controller: CodeEditorController?620    private var hoverArea: NSTrackingArea?621622    private static let pairs: [String: String] = ["{": "}", "(": ")", "[": "]", "\"": "\""]623624    override func viewDidChangeEffectiveAppearance() {625        super.viewDidChangeEffectiveAppearance()626        controller?.appearanceChanged()627    }628629    // MARK: Typing630631    private func character(at index: Int) -> String? {632        let s = string as NSString633        guard index >= 0, index < s.length else { return nil }634        return s.substring(with: NSRange(location: index, length: 1))635    }636637    override func insertText(_ insertString: Any, replacementRange: NSRange) {638        guard let typed = insertString as? String, typed.count == 1, selectedRange().length == 0 else {639            super.insertText(insertString, replacementRange: replacementRange); return640        }641        let location = selectedRange().location642        let next = character(at: location)643        // Typing a closer that is already there steps over it.644        if ["}", ")", "]", "\""].contains(typed), next == typed {645            setSelectedRange(NSRange(location: location + 1, length: 0)); return646        }647        if let closer = Self.pairs[typed] {648            let nextIsOpen = next == nil || next == "\n" || next == " " || next == ")" || next == "]" || next == "}" || next == ","649            let previous = character(at: location - 1)650            let quoteInsideWord = typed == "\"" && (previous.map { $0.rangeOfCharacter(from: .alphanumerics) != nil } ?? false)651            if nextIsOpen, !quoteInsideWord {652                super.insertText(typed + closer, replacementRange: replacementRange)653                setSelectedRange(NSRange(location: location + 1, length: 0))654                return655            }656        }657        // A closing brace typed on an empty line moves back one level.658        if typed == "}" {659            let s = string as NSString660            let lineRange = s.lineRange(for: NSRange(location: location, length: 0))661            let before = s.substring(with: NSRange(location: lineRange.location, length: location - lineRange.location))662            if !before.isEmpty, before.allSatisfy({ $0 == " " }) {663                let keep = max(0, before.count - 4)664                super.insertText(String(repeating: " ", count: keep) + "}", replacementRange: NSRange(location: lineRange.location, length: before.count))665                return666            }667        }668        super.insertText(insertString, replacementRange: replacementRange)669        if typed == "." { controller?.updateCompletion(force: false) }670    }671672    override func insertNewline(_ sender: Any?) {673        if controller?.completion != nil { controller?.acceptCompletion(); return }674        let location = selectedRange().location675        let s = string as NSString676        let lineRange = s.lineRange(for: NSRange(location: location, length: 0))677        let before = s.substring(with: NSRange(location: lineRange.location, length: location - lineRange.location))678        let indent = String(before.prefix { $0 == " " })679        let previous = before.trimmingCharacters(in: .whitespaces).last680        let next = character(at: location)681        if let previous, "{([".contains(previous) {682            let closer = previous == "{" ? "}" : (previous == "(" ? ")" : "]")683            let inner = indent + "    "684            if next == closer {685                super.insertText("\n" + inner + "\n" + indent, replacementRange: selectedRange())686                setSelectedRange(NSRange(location: location + 1 + inner.count, length: 0))687            } else {688                super.insertText("\n" + inner, replacementRange: selectedRange())689            }690            return691        }692        super.insertText("\n" + indent, replacementRange: selectedRange())693    }694695    override func insertTab(_ sender: Any?) {696        if controller?.completion != nil { controller?.acceptCompletion(); return }697        let sel = selectedRange()698        let s = string as NSString699        if sel.length > 0, s.substring(with: sel).contains("\n") { shiftLines(by: 4); return }700        let lineStart = s.lineRange(for: NSRange(location: sel.location, length: 0)).location701        let column = sel.location - lineStart702        super.insertText(String(repeating: " ", count: 4 - column % 4), replacementRange: sel)703    }704705    override func insertBacktab(_ sender: Any?) { shiftLines(by: -4) }706707    /// Indents or outdents every selected line by four spaces, as one undoable edit.708    private func shiftLines(by amount: Int) {709        let s = string as NSString710        let lines = s.lineRange(for: selectedRange())711        let text = s.substring(with: lines)712        var parts = text.components(separatedBy: "\n")713        let trailingEmpty = parts.last == ""714        if trailingEmpty { parts.removeLast() }715        parts = parts.map { line in716            if amount > 0 { return line.isEmpty ? line : String(repeating: " ", count: amount) + line }717            let strip = min(-amount, line.prefix { $0 == " " }.count)718            return String(line.dropFirst(strip))719        }720        let replaced = parts.joined(separator: "\n") + (trailingEmpty ? "\n" : "")721        guard replaced != text, shouldChangeText(in: lines, replacementString: replaced) else { return }722        textStorage?.replaceCharacters(in: lines, with: replaced)723        didChangeText()724        setSelectedRange(NSRange(location: lines.location, length: (replaced as NSString).length))725    }726727    override func deleteBackward(_ sender: Any?) {728        let sel = selectedRange()729        if sel.length == 0, sel.location > 0, let previous = character(at: sel.location - 1), let next = character(at: sel.location), Self.pairs[previous] == next {730            // Deleting an opener removes the closer typed with it.731            if shouldChangeText(in: NSRange(location: sel.location - 1, length: 2), replacementString: "") {732                textStorage?.replaceCharacters(in: NSRange(location: sel.location - 1, length: 2), with: "")733                didChangeText()734                return735            }736        }737        super.deleteBackward(sender)738    }739740    // MARK: Keys741742    override func keyDown(with event: NSEvent) {743        let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)744        if flags.contains(.control), event.charactersIgnoringModifiers == " " { controller?.updateCompletion(force: true); return }745        if controller?.completion != nil {746            switch event.keyCode {747            case 125: controller?.moveCompletion(1); return748            case 126: controller?.moveCompletion(-1); return749            case 53: controller?.completion = nil; return750            default: break751            }752        }753        super.keyDown(with: event)754    }755756    override func cancelOperation(_ sender: Any?) {757        // Esc opens the completion list (and closes it from keyDown when it is showing).758        controller?.updateCompletion(force: true)759    }760761    override func complete(_ sender: Any?) { controller?.updateCompletion(force: true) }762763    override func performKeyEquivalent(with event: NSEvent) -> Bool {764        guard window?.firstResponder === self else { return super.performKeyEquivalent(with: event) }765        let flags = event.modifierFlags.intersection([.command, .shift, .option, .control])766        let key = event.charactersIgnoringModifiers?.lowercased() ?? ""767        func finder(_ action: NSTextFinder.Action) -> Bool {768            let item = NSMenuItem(); item.tag = action.rawValue769            performTextFinderAction(item); return true770        }771        switch (flags, key) {772        case ([.command], "f"): return finder(.showFindInterface)773        case ([.command, .option], "f"): return finder(.showReplaceInterface)774        case ([.command], "g"): return finder(.nextMatch)775        case ([.command, .shift], "g"): return finder(.previousMatch)776        case ([.command], "s"): controller?.onCommand?(.save); return true777        case ([.command, .shift], "s"): controller?.onCommand?(.saveAs); return true778        case ([.command], "r"): controller?.onCommand?(.run); return true779        case ([.command], "."): controller?.onCommand?(.stop); return true780        case ([.command], "b"): controller?.onCommand?(.validate); return true781        case ([.command], "d"): controller?.onCommand?(.simulate); return true782        case ([.command, .option], "l"), ([.command, .option], "¬"): controller?.onCommand?(.format); return true783        default: return super.performKeyEquivalent(with: event)784        }785    }786787    // MARK: Drawing and hover788789    override func drawBackground(in rect: NSRect) {790        super.drawBackground(in: rect)791        guard let controller else { return }792        let sel = selectedRange()793        if sel.length == 0, let r = controller.lineRect(forLine: controller.line(at: sel.location)) {794            NSColor(ORIX.Palette.surfaceRaised).withAlphaComponent(0.7).setFill()795            NSRect(x: 0, y: r.minY, width: bounds.width, height: r.height).fill()796        }797        if let paused = controller.pausedLine, let r = controller.lineRect(forLine: paused) {798            NSColor(ORIX.Palette.warning).withAlphaComponent(0.22).setFill()799            NSRect(x: 0, y: r.minY, width: bounds.width, height: r.height).fill()800            NSColor(ORIX.Palette.warning).setFill()801            NSRect(x: 0, y: r.minY, width: 3, height: r.height).fill()802        }803    }804805    override func updateTrackingAreas() {806        super.updateTrackingAreas()807        if let hoverArea { removeTrackingArea(hoverArea) }808        let area = NSTrackingArea(rect: .zero, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self, userInfo: nil)809        addTrackingArea(area)810        hoverArea = area811    }812813    override func mouseMoved(with event: NSEvent) {814        super.mouseMoved(with: event)815        controller?.hover(at: convert(event.locationInWindow, from: nil))816    }817818    override func mouseExited(with event: NSEvent) {819        super.mouseExited(with: event)820        controller?.onHover?(nil)821    }822}823824/// The gutter: breakpoints, diagnostics markers, line numbers and fold controls.825final class CodeGutterView: NSRulerView {826    private weak var controller: CodeEditorController?827    private let breakpointColumn: CGFloat = 16828    private let markerColumn: CGFloat = 12829    private let foldColumn: CGFloat = 14830831    init(scrollView: NSScrollView, controller: CodeEditorController) {832        self.controller = controller833        super.init(scrollView: scrollView, orientation: .verticalRuler)834        clientView = controller.textView835        ruleThickness = 68836        clipsToBounds = true837        setAccessibilityLabel(String(localized: "Editor gutter: breakpoints and folding"))838    }839840    @available(*, unavailable)841    required init(coder: NSCoder) { fatalError("init(coder:) is not used") }842843    override var isFlipped: Bool { true }844845    /// Calls `body` with the 1-based line and its rectangle (gutter coordinates) for every line start visible in `rect`.846    private func forEachVisibleLine(in rect: NSRect, _ body: (Int, NSRect) -> Void) {847        guard let controller, let container = controller.textView.textContainer else { return }848        let textView = controller.textView849        let layout = controller.layoutManager850        let origin = convert(NSPoint.zero, from: textView)851        let visible = textView.visibleRect852        let glyphs = layout.glyphRange(forBoundingRect: visible, in: container)853        let length = (textView.string as NSString).length854        var lastLine = 0855        var fragments: [(Int, NSRect)] = []856        layout.enumerateLineFragments(forGlyphRange: glyphs) { fragment, _, _, glyphRange, _ in857            fragments.append((layout.characterIndexForGlyph(at: glyphRange.location), fragment))858        }859        for (charIndex, fragment) in fragments {860            let line = controller.line(at: charIndex)861            guard line != lastLine, controller.lineStarts[line - 1] == charIndex else { continue }862            lastLine = line863            body(line, NSRect(x: 0, y: fragment.minY + textView.textContainerOrigin.y + origin.y, width: ruleThickness, height: fragment.height))864        }865        // The empty last line has no glyph.866        if layout.extraLineFragmentTextContainer != nil {867            let r = layout.extraLineFragmentRect868            let line = controller.line(at: length)869            if line != lastLine { body(line, NSRect(x: 0, y: r.minY + textView.textContainerOrigin.y + origin.y, width: ruleThickness, height: r.height)) }870        }871        if length == 0, layout.extraLineFragmentTextContainer == nil {872            body(1, NSRect(x: 0, y: textView.textContainerOrigin.y + origin.y, width: ruleThickness, height: layout.defaultLineHeight(for: EditorColors.font)))873        }874    }875876    override func drawHashMarksAndLabels(in rect: NSRect) {877        NSColor(ORIX.Palette.surface).setFill()878        bounds.fill()879        NSColor(ORIX.Palette.hairline).setFill()880        NSRect(x: bounds.maxX - 1, y: bounds.minY, width: 1, height: bounds.height).fill()881        guard let controller else { return }882        let caretLine = controller.line(at: controller.textView.selectedRange().location)883        let numberFont = NSFont.monospacedDigitSystemFont(ofSize: 10.5, weight: .regular)884        forEachVisibleLine(in: rect) { line, r in885            let midY = r.midY886            if controller.pausedLine == line {887                NSColor(ORIX.Palette.warning).withAlphaComponent(0.22).setFill()888                r.fill()889            }890            // Breakpoint: a filled tag pointing at the code.891            if controller.breakpoints.contains(line) {892                let tag = NSBezierPath()893                tag.move(to: NSPoint(x: 3, y: midY - 5)); tag.line(to: NSPoint(x: 10, y: midY - 5)); tag.line(to: NSPoint(x: 14, y: midY))894                tag.line(to: NSPoint(x: 10, y: midY + 5)); tag.line(to: NSPoint(x: 3, y: midY + 5)); tag.close()895                NSColor(ORIX.Palette.accent).setFill(); tag.fill()896            }897            // Diagnostics: a circle for an error, a triangle for a warning, a square for a note.898            if let severity = controller.severity(onLine: line) {899                let x = self.breakpointColumn900                let color = EditorColors.severity(severity)901                color.setFill()902                switch severity {903                case .error: NSBezierPath(ovalIn: NSRect(x: x, y: midY - 4, width: 8, height: 8)).fill()904                case .warning:905                    let t = NSBezierPath()906                    t.move(to: NSPoint(x: x + 4, y: midY - 4.5)); t.line(to: NSPoint(x: x + 8.5, y: midY + 4)); t.line(to: NSPoint(x: x - 0.5, y: midY + 4)); t.close(); t.fill()907                case .note: NSBezierPath(rect: NSRect(x: x + 1, y: midY - 3, width: 6, height: 6)).fill()908                }909            }910            let label = "\(line)" as NSString911            let attributes: [NSAttributedString.Key: Any] = [.font: numberFont, .foregroundColor: NSColor(line == caretLine ? ORIX.Palette.textPrimary : ORIX.Palette.textTertiary)]912            let size = label.size(withAttributes: attributes)913            label.draw(at: NSPoint(x: self.ruleThickness - self.foldColumn - 4 - size.width, y: midY - size.height / 2), withAttributes: attributes)914            // Fold control, only on lines that open a multi-line block.915            if controller.foldablePair(onLine: line) != nil {916                let folded = controller.isFolded(line: line)917                let cx = self.ruleThickness - self.foldColumn / 2 - 2918                let chevron = NSBezierPath()919                if folded {920                    chevron.move(to: NSPoint(x: cx - 2, y: midY - 3.5)); chevron.line(to: NSPoint(x: cx + 2, y: midY)); chevron.line(to: NSPoint(x: cx - 2, y: midY + 3.5))921                } else {922                    chevron.move(to: NSPoint(x: cx - 3.5, y: midY - 2)); chevron.line(to: NSPoint(x: cx, y: midY + 2)); chevron.line(to: NSPoint(x: cx + 3.5, y: midY - 2))923                }924                chevron.lineWidth = 1.4; chevron.lineCapStyle = .round; chevron.lineJoinStyle = .round925                NSColor(folded ? ORIX.Palette.accentSecondary : ORIX.Palette.textTertiary).setStroke()926                chevron.stroke()927            }928        }929    }930931    override func mouseDown(with event: NSEvent) {932        guard let controller else { return }933        let p = convert(event.locationInWindow, from: nil)934        var hit: Int?935        forEachVisibleLine(in: bounds) { line, r in if p.y >= r.minY, p.y < r.maxY { hit = line } }936        guard let line = hit else { return }937        if p.x >= ruleThickness - foldColumn - 3, controller.foldablePair(onLine: line) != nil { controller.toggleFold(line: line) }938        else { controller.toggleBreakpoint(line: line) }939    }940}941942/// Hosts the editor of the active document; editors of other tabs stay alive with their undo history.943struct ScriptEditorView: NSViewRepresentable {944    let controller: CodeEditorController945    var source: String946    var diagnostics: [Diagnostic]947    var breakpoints: Set<Int>948    var pausedLine: Int?949950    final class Host: NSView {951        override var isFlipped: Bool { true }952        func show(_ view: NSView) {953            guard view.superview !== self else { return }954            subviews.forEach { $0.removeFromSuperview() }955            view.frame = bounds956            view.autoresizingMask = [.width, .height]957            addSubview(view)958        }959    }960961    func makeNSView(context: Context) -> Host { Host() }962963    func updateNSView(_ host: Host, context: Context) {964        host.show(controller.scrollView)965        controller.sync(source: source, diagnostics: diagnostics, breakpoints: breakpoints, pausedLine: pausedLine)966    }967}968969/// The completion list drawn over the editor.970struct CompletionPopupView: View {971    let controller: CodeEditorController972    var size: CGSize973974    var body: some View {975        if let c = controller.completion {976            let width: CGFloat = 380977            let rows = min(c.items.count, 8)978            let doc = c.items[min(c.selected, c.items.count - 1)].doc979            let height = CGFloat(rows) * 22 + (doc.isEmpty ? 0 : 46) + 8980            let below = c.anchor.y + height + 4 <= size.height981            VStack(alignment: .leading, spacing: 0) {982                ScrollViewReader { proxy in983                    ScrollView {984                        VStack(spacing: 0) {985                            ForEach(Array(c.items.enumerated()), id: \.offset) { i, item in986                                HStack(spacing: 8) {987                                    Image(systemName: i == c.selected ? "chevron.right" : "circle.fill")988                                        .font(.system(size: i == c.selected ? 8 : 3, weight: .bold)).frame(width: 10)989                                        .foregroundStyle(i == c.selected ? ORIX.Palette.accent : ORIX.Palette.textTertiary)990                                    Text(verbatim: item.label).font(ORIX.Typeface.mono).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)991                                    Spacer(minLength: 6)992                                    Text(verbatim: item.detail).font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)993                                }994                                .padding(.horizontal, 6).frame(height: 22)995                                .background(i == c.selected ? ORIX.Palette.surfaceRaised : .clear)996                                .contentShape(Rectangle())997                                .onTapGesture { controller.acceptCompletion(index: i) }998                                .id(i)999                                .accessibilityElement(children: .combine)1000                                .accessibilityAddTraits(i == c.selected ? [.isSelected, .isButton] : [.isButton])1001                            }1002                        }1003                    }1004                    .frame(height: CGFloat(rows) * 22)1005                    .onChange(of: c.selected) { _, new in proxy.scrollTo(new) }1006                }1007                if !doc.isEmpty {1008                    Divider().overlay(ORIX.Palette.hairline)1009                    Text(verbatim: doc).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(3)1010                        .frame(maxWidth: .infinity, alignment: .leading).padding(6).frame(height: 46, alignment: .topLeading)1011                }1012            }1013            .padding(.vertical, 4)1014            .frame(width: width)1015            .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))1016            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline))1017            .shadow(color: .black.opacity(0.3), radius: 10, y: 4)1018            .offset(x: min(max(4, c.anchor.x), max(4, size.width - width - 8)), y: below ? c.anchor.y + 2 : max(2, c.anchor.y - c.lineHeight - height - 2))1019            .accessibilityIdentifier("automation-completions")1020            .accessibilityLabel("Completions")1021        }1022    }1023}1024
Files main
Menu

Theme