// SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI import AppKit struct BASICDevelopmentView: View { @ObservedObject var model: BASICDevelopmentModel @StateObject private var finder = SourceFind() let reference: BASICReferenceModel? @ObservedObject private var menu: MachineMenuState @Environment(\.openWindow) private var openWindow @State private var exportKind: BASICExportKind? @State private var editingSheet: BASICEditingSheet? @State private var diagnosticsExpanded = true @State private var pendingEditingAction: (() -> Void)? @State private var pendingExport: (kind: BASICExportKind, name: String, dosBoot: Bool)? init(model: BASICDevelopmentModel, reference: BASICReferenceModel? = nil) { self.model = model; self.reference = reference; menu = model.machine.menuState } private func quickHelp(_ keyword: String?) { if let keyword { reference?.show(keyword: keyword, dialect: model.machine.basicReferenceDialect) } openWindow(id: "basic-reference") } private var unavailable: Bool { model.busy || menu.values.busy || ![VCCMachineState.running, .paused].contains(menu.values.state) } var body: some View { GeometryReader { geometry in VStack(alignment: .leading, spacing: 0) { HStack(spacing: 12) { Image(systemName: "terminal").font(.largeTitle).foregroundStyle(.tint) VStack(alignment: .leading, spacing: 3) { Text("BASIC Development").font(.title2.bold()) Text("Edit on your Mac · Run in your CoCo").font(.callout).foregroundStyle(.secondary) } Spacer() Button { openWindow(id: "basic-reference") } label: { Label("Reference", systemImage: "book.closed") } .accessibilityIdentifier("basic.reference.open") Button { openWindow(id: "machine") } label: { Label("Show CoCo", systemImage: "desktopcomputer") } .accessibilityIdentifier("basic.show-machine") }.padding(16) Divider() HStack(spacing: 10) { Button { model.newProgram() } label: { Label("New", systemImage: "doc.badge.plus") }.accessibilityIdentifier("basic.new") Button { model.open() } label: { Label("Open…", systemImage: "folder") }.accessibilityIdentifier("basic.open") Button { model.save() } label: { Label("Save", systemImage: "square.and.arrow.down") } .keyboardShortcut("s", modifiers: .command).accessibilityIdentifier("basic.save") Menu { Button("Save As…") { model.save(as: true) } Button("Local Assistant Access…", systemImage: "link") { MCPAccess.shared.show(for: model) } .accessibilityIdentifier("basic.assistant.access") Divider() Button("Export Disk…", systemImage: "externaldrive") { exportKind = .disk } .disabled(unavailable).accessibilityIdentifier("basic.export-disk") Button("Export Cassette…", systemImage: "recordingtape") { exportKind = .cassette } .disabled(unavailable).accessibilityIdentifier("basic.export-cassette") } label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).frame(width: 25).help("Show more BASIC file actions").accessibilityLabel("More file actions").accessibilityIdentifier("basic.file-actions") Spacer(minLength: 12) Button { model.readFromCoCo() } label: { Label("Read from CoCo", systemImage: "arrow.down.doc") } .disabled(unavailable).accessibilityIdentifier("basic.read") Button { model.transfer(run: false) } label: { Label("Load into CoCo", systemImage: "arrow.up.doc") } .disabled(unavailable).accessibilityIdentifier("basic.load") Button { model.transfer(run: true) } label: { Label("Run", systemImage: "play.fill") } .buttonStyle(.borderedProminent).disabled(unavailable).accessibilityIdentifier("basic.run") }.controlSize(.regular).padding(.horizontal,16).padding(.vertical,10).disabled(model.editorLocked) HStack { Label(model.title, systemImage: "doc.text").fontWeight(.medium).lineLimit(1) if model.dirty { Text("Edited").foregroundStyle(.secondary) } Spacer() SourceFindButton(finder: finder) Button { model.toggleBreakpointAtCursor() } label: { Image(systemName: "record.circle") } .help(model.cursorBreakpointHelp) .accessibilityLabel(model.cursorBreakpointHelp) .accessibilityIdentifier("basic.toggle-breakpoint").disabled(model.editorLocked) Button { model.continueProgram() } label: { Label("Continue", systemImage: "play.fill") } .disabled(!model.canContinue).accessibilityIdentifier("basic.continue") Button { model.stepProgram(over: false) } label: { Image(systemName: "arrow.down.to.line") } .help("Run one BASIC statement, following GOSUB into its subroutine") .accessibilityLabel("Step Into BASIC statement").accessibilityIdentifier("basic.step-into") .disabled(!model.canStep) Button { model.stepProgram(over: true) } label: { Image(systemName: "arrow.turn.up.right") } .help("Run one BASIC statement, continuing through a GOSUB unless a breakpoint is hit") .accessibilityLabel("Step Over BASIC subroutine").accessibilityIdentifier("basic.step-over") .disabled(!model.canStep) Button { model.stepProgram(over: false, out: true) } label: { Image(systemName: "arrow.up.to.line") } .help("Run until this GOSUB returns to its caller or a breakpoint is hit") .accessibilityLabel("Step Out of BASIC subroutine").accessibilityIdentifier("basic.step-out") .disabled(!model.canStepOut) if model.stepping { Button { model.cancelStep() } label: { Image(systemName: "pause.fill") } .help("Pause the current BASIC step").accessibilityLabel("Pause BASIC step") .accessibilityIdentifier("basic.pause-step") } Menu { Button("Clear All Breakpoints", systemImage: "record.circle") { model.clearBreakpoints() } .disabled(model.breakpoints.isEmpty).accessibilityIdentifier("basic.clear-breakpoints") Divider() Button("Check Source", systemImage: "checkmark.circle") { model.checkSource(); diagnosticsExpanded = true } .accessibilityIdentifier("basic.check-source") Button("Go to Line…", systemImage: "arrow.turn.down.right") { editingSheet = .goToLine } .accessibilityIdentifier("basic.go-to-line") Button("Renumber…", systemImage: "list.number") { editingSheet = .renumber } .accessibilityIdentifier("basic.renumber") } label: { Label("Editing", systemImage: "pencil.line") } .disabled(model.editorLocked).accessibilityIdentifier("basic.editing-actions") Button { model.completionRequest = UUID() } label: { Label("Complete", systemImage: "text.badge.plus") } .help("Complete a BASIC keyword (Control–Space)").accessibilityIdentifier("basic.complete") .disabled(model.editorLocked) }.font(.callout).padding(.horizontal,16).padding(.bottom,8) Divider() if let message = model.message { Label(message, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange) .textSelection(.enabled).padding(10).frame(maxWidth:.infinity,alignment:.leading) .background(.orange.opacity(0.08)).accessibilityIdentifier("basic.message") } if let line = model.runtimeErrorLine { HStack(spacing: 10) { Label("BASIC \(model.runtimeErrorCode.isEmpty ? "runtime" : model.runtimeErrorCode) error on line \(line)", systemImage: "exclamationmark.circle.fill") .foregroundStyle(.red).accessibilityIdentifier("basic.runtime-error") Text("The program ended. Continue returns to the prompt.").foregroundStyle(.secondary) Spacer(minLength: 0) Button { reference?.showError(code: model.runtimeErrorCode); openWindow(id: "basic-reference") } label: { Image(systemName: "questionmark.circle") }.help("Explain this BASIC error").accessibilityLabel("Explain BASIC error") .accessibilityIdentifier("basic.reference.error") Button("Show Line \(line)") { model.goToLine(line) } .disabled(model.editorLocked).accessibilityIdentifier("basic.show-runtime-error") }.font(.callout).padding(10).background(.red.opacity(0.06)) } SourceFindBar(finder: finder, source: model.source, readOnly: model.editorLocked) BASICSourceEditor(finder: finder, text: $model.source, readOnly: model.editorLocked, completionRequest: model.completionRequest, editorAction: model.editorAction, breakpoints: model.breakpoints, stoppedLine: model.stoppedLine, stoppedToken: model.stoppedToken, toggleBreakpoint: model.toggleBreakpoint, actionHandled: { id, applied in model.editorActionHandled(id: id, applied: applied) }, cursorChanged: model.cursorChanged, assistance: { model.statusMessage($0) }, quickHelp: quickHelp, attach: { model.assistantEditor = $0 }) .id(model.documentID).frame(minHeight:120).accessibilityIdentifier("basic.editor") HStack(spacing: 8) { Image(systemName: model.stoppedLine == nil ? "record.circle" : "arrow.right.circle.fill") .foregroundStyle(model.stoppedLine == nil ? Color.secondary : Color.orange) Text(model.debugStatus).font(.caption).lineLimit(2) .accessibilityIdentifier("basic.debug-status") Spacer() if !model.breakpoints.isEmpty { Text("\(model.breakpoints.count) breakpoint\(model.breakpoints.count == 1 ? "" : "s")") .font(.caption).foregroundStyle(.secondary) } }.padding(.horizontal, 12).padding(.vertical, 7) // Reserve the window chrome and a useful editor height before // allocating rows to the independently scrolling inspector. BASICInspectionView(model: model, valuesHeight: max(36, min(160, geometry.size.height - 560 - (!model.diagnostics.isEmpty && diagnosticsExpanded ? 130 : 0)))) if !model.diagnostics.isEmpty { Divider() DisclosureGroup(isExpanded: $diagnosticsExpanded) { ScrollView { LazyVStack(alignment: .leading, spacing: 5) { ForEach(model.diagnostics) { diagnostic in Button { model.selectDiagnostic(diagnostic) } label: { HStack(alignment: .top, spacing: 8) { Image(systemName: diagnostic.severity == .error ? "exclamationmark.circle" : "exclamationmark.triangle") .foregroundStyle(diagnostic.severity == .error ? Color.red : Color.orange) Text("Row \(diagnostic.row)").monospacedDigit().fontWeight(.medium) Text(diagnostic.message).frame(maxWidth: .infinity, alignment: .leading) }.contentShape(Rectangle()) }.buttonStyle(.plain).font(.callout).disabled(model.editorLocked) .accessibilityLabel("Source row \(diagnostic.row): \(diagnostic.message). Go to source.") .accessibilityIdentifier("basic.diagnostic.\(diagnostic.id)") } }.padding(.vertical, 6) }.frame(maxHeight: 100) } label: { Text("Source checks · \(model.diagnostics.count)").font(.callout.bold()) }.padding(.horizontal, 14).padding(.vertical, 8) .accessibilityIdentifier("basic.diagnostics") } HStack(alignment:.top,spacing:8) { Image(systemName: "info.circle").foregroundStyle(.secondary) Text(model.hint ?? "Return continues line numbering. Tab accepts a faint keyword suggestion; Control–Space shows all matches.") .font(.system(.caption,design:.monospaced)).textSelection(.enabled) .frame(maxWidth:.infinity,alignment:.leading).accessibilityIdentifier("basic.hint") Button { quickHelp(BASICReferenceContext.keyword(in: model.source, at: model.editorOffset)) } label: { Label("Quick Help", systemImage: "questionmark.circle") }.keyboardShortcut("h", modifiers: [.control, .shift]) .help("Look up the command at the insertion point (Control–Shift–H)") .accessibilityIdentifier("basic.reference.context") }.padding(10).frame(minHeight:42,alignment:.top) Divider() VStack(alignment:.leading,spacing:5) { HStack(alignment:.top) { if model.busy { ProgressView().controlSize(.small) } Text(model.status).font(.callout).textSelection(.enabled).accessibilityIdentifier("basic.status") } Text("Direct loading supports Disk BASIC, Hard Drive BASIC and CoCo SDC at the BASIC OK prompt. Use CoCo Break to stop before replacing a running program. Read from CoCo retrieves program text, not variables.") .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal:false,vertical:true) .accessibilityIdentifier("basic.preset-support") }.padding(14) }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) }.frame(minWidth:850,minHeight:560) .focusedSceneValue(\.sourceFind, finder) .onDisappear { model.persistDraft() } .sheet(item: $editingSheet, onDismiss: { let action = pendingEditingAction; pendingEditingAction = nil; action?() }) { kind in BASICEditingOptions(kind: kind, goToLine: { number in pendingEditingAction = { model.goToLine(number) }; editingSheet = nil }, renumber: { start, increment in pendingEditingAction = { model.renumber(start: start, increment: increment) }; editingSheet = nil }, cancel: { editingSheet = nil }) } .sheet(item: $exportKind, onDismiss: { if let request = pendingExport { pendingExport = nil; model.chooseExport(request.kind, name: request.name, dosBoot: request.dosBoot) } }) { kind in BASICExportOptions(kind: kind, initialName: model.suggestedExportName, confirm: { name, boot in pendingExport = (kind, name, boot); exportKind = nil }, cancel: { exportKind = nil }) } } } private enum BASICEditingSheet: String, Identifiable { case goToLine, renumber var id: String { rawValue } } private struct BASICEditingOptions: View { let kind: BASICEditingSheet let goToLine: (Int) -> Void let renumber: (Int, Int) -> Void let cancel: () -> Void @State private var line = "10" @State private var increment = "10" @FocusState private var firstFieldFocused: Bool private var firstNumber: Int? { Int(line.trimmingCharacters(in: .whitespaces)) } private var step: Int? { Int(increment.trimmingCharacters(in: .whitespaces)) } private var valid: Bool { guard let firstNumber, (0...63999).contains(firstNumber) else { return false } return kind == .goToLine || step.map { (1...63999).contains($0) } == true } var body: some View { VStack(alignment: .leading, spacing: 16) { Label(kind == .goToLine ? "Go to BASIC Line" : "Renumber Program", systemImage: kind == .goToLine ? "arrow.turn.down.right" : "list.number").font(.title2.bold()) if kind == .goToLine { Text("Find a BASIC line number in your editor source. This does not move the running CoCo program.") .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) TextField("BASIC line number", text: $line).textFieldStyle(.roundedBorder) .focused($firstFieldFocused).accessibilityIdentifier("basic.go-line-number") } else { Text("Renumber the entire editor program and update its recognized line references. Strings, comments, and DATA values stay unchanged.") .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 10) { GridRow { Text("Start at") TextField("Starting line number", text: $line).textFieldStyle(.roundedBorder) .focused($firstFieldFocused).accessibilityIdentifier("basic.renumber-start") } GridRow { Text("Increment") TextField("Line number increment", text: $increment).textFieldStyle(.roundedBorder) .accessibilityIdentifier("basic.renumber-increment") } } Text("The CoCo program is not changed. You can undo this edit with ⌘Z.") .font(.callout).fixedSize(horizontal: false, vertical: true) } Text(kind == .goToLine ? "BASIC line numbers range from 0 to 63999." : "Use line numbers from 0 to 63999 and a positive increment. Source problems must be corrected before renumbering.") .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) HStack { Spacer() Button("Cancel", action: cancel).keyboardShortcut(.cancelAction) Button(kind == .goToLine ? "Go to Line" : "Renumber") { guard let firstNumber, valid else { return } if kind == .goToLine { goToLine(firstNumber) } else if let step { renumber(firstNumber, step) } }.keyboardShortcut(.defaultAction).disabled(!valid) .accessibilityIdentifier("basic.editing-confirm") } }.padding(22).frame(width: 430).task { firstFieldFocused = true } } } private struct BASICExportOptions: View { let kind: BASICExportKind let confirm: (String, Bool) -> Void let cancel: () -> Void @State private var name: String @State private var dosBoot = false @FocusState private var nameFocused: Bool init(kind: BASICExportKind, initialName: String, confirm: @escaping (String, Bool) -> Void, cancel: @escaping () -> Void) { self.kind = kind; self.confirm = confirm; self.cancel = cancel _name = State(initialValue: initialName) } private var validName: String? { BASICExportName.normalized(name) } var body: some View { VStack(alignment: .leading, spacing: 16) { Label(kind.title, systemImage: kind.symbol).font(.title2.bold()) Text(kind == .disk ? "Create a fresh 35-track Disk BASIC disk with your current editor program." : "Create a cassette image with your current editor program.") .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) VStack(alignment: .leading, spacing: 6) { TextField("CoCo program name", text: $name).textFieldStyle(.roundedBorder) .focused($nameFocused).accessibilityIdentifier("basic.export-name") Text("Use 1–8 letters or numbers, without an extension. The CoCo name will be uppercase.") .font(.caption).foregroundStyle(.secondary) } if let validName { Label(kind == .disk ? validName + ".BAS" : validName, systemImage: "doc.text") .font(.system(.callout, design: .monospaced)) } if kind == .disk { Toggle("Install DOS bootloader", isOn: $dosBoot) .accessibilityIdentifier("basic.export-dos") } if let validName { Text(kind.instructions(name: validName, dosBoot: dosBoot)) .accessibilityIdentifier("basic.export-commands") .font(.callout).fixedSize(horizontal: false, vertical: true) } HStack { Spacer() Button("Cancel", action: cancel).keyboardShortcut(.cancelAction) Button("Choose Location…") { if let validName { confirm(validName, dosBoot) } } .keyboardShortcut(.defaultAction).disabled(validName == nil) .accessibilityIdentifier("basic.export-location") } }.padding(22).frame(width: 430).task { nameFocused = true } } } /// Stable AppKit text editor: only explicit document changes reset Undo. struct BASICSourceEditor: NSViewRepresentable { let finder: SourceFind @Binding var text: String let readOnly: Bool let completionRequest: UUID let editorAction: BASICEditorAction? let breakpoints: Set let stoppedLine: Int? let stoppedToken: NSRange? let toggleBreakpoint: (Int) -> Void let actionHandled: (UUID, Bool) -> Void let cursorChanged: (Int) -> Void let assistance: (String) -> Void let quickHelp: (String?) -> Void var attach: (BASICTextView) -> Void = { _ in } func makeCoordinator() -> Coordinator { Coordinator(self) } func makeNSView(context: Context) -> NSScrollView { let scroll=NSScrollView(); scroll.hasVerticalScroller=true; scroll.hasHorizontalScroller=true; scroll.autohidesScrollers=true // AppKit ruler decorations must not paint into the surrounding SwiftUI // toolbar, inspector or footer when this representable resizes. scroll.wantsLayer = true; scroll.layer?.masksToBounds = true let editor=BASICTextView(frame:.zero) // Highlighting and breakpoint geometry use TextKit 1. Establish it // before setting up the unwrapped container, even for an empty draft. _ = editor.layoutManager attach(editor) editor.delegate=context.coordinator; editor.string=text; editor.allowsUndo=true; editor.isRichText=false editor.isAutomaticQuoteSubstitutionEnabled=false; editor.isAutomaticDashSubstitutionEnabled=false editor.isAutomaticTextReplacementEnabled=false; editor.isAutomaticSpellingCorrectionEnabled=false editor.isContinuousSpellCheckingEnabled=false; editor.isGrammarCheckingEnabled=false editor.isVerticallyResizable=true; editor.isHorizontallyResizable=true editor.minSize=NSSize(width:0,height:0); editor.maxSize=NSSize(width:CGFloat.greatestFiniteMagnitude,height:CGFloat.greatestFiniteMagnitude) editor.textContainer?.widthTracksTextView=false editor.textContainer?.containerSize=editor.maxSize editor.autoresizingMask = [.width] editor.textContainerInset=NSSize(width:16,height:14) editor.font = .monospacedSystemFont(ofSize:14,weight:.regular) editor.backgroundColor = .textBackgroundColor; editor.textColor = .textColor finder.editor = editor editor.setAccessibilityLabel("BASIC source editor") editor.setAccessibilityIdentifier("basic.source-text") editor.assistance=assistance; editor.quickHelp = quickHelp; scroll.documentView=editor scroll.verticalRulerView = BASICBreakpointRuler(textView: editor) scroll.hasVerticalRuler = true; scroll.rulersVisible = true editor.configureDebug(points: breakpoints, stoppedLine: stoppedLine, token: stoppedToken, toggle: toggleBreakpoint) context.coordinator.highlight(editor) return scroll } func updateNSView(_ scroll:NSScrollView,context:Context) { context.coordinator.parent=self guard let editor=scroll.documentView as? BASICTextView else { return } finder.editor = editor editor.assistance=assistance; editor.quickHelp = quickHelp; editor.isEditable = !readOnly editor.refreshInlineSuggestion() if !editor.string.utf8.elementsEqual(text.utf8) { editor.string=text; editor.undoManager?.removeAllActions(); context.coordinator.highlight(editor) } editor.configureDebug(points: breakpoints, stoppedLine: stoppedLine, token: stoppedToken, toggle: toggleBreakpoint) if let action = editorAction, context.coordinator.actionID != action.id { context.coordinator.actionID = action.id let coordinator = context.coordinator DispatchQueue.main.async { [weak editor, weak coordinator] in guard let coordinator else { return } let applied = editor?.applyEditorAction(action) ?? false coordinator.parent.actionHandled(action.id, applied) } } if context.coordinator.completionRequest != completionRequest { context.coordinator.completionRequest=completionRequest DispatchQueue.main.async { [weak editor] in guard let editor, editor.isEditable else { return } editor.window?.makeFirstResponder(editor); editor.complete(nil) } } } @MainActor final class Coordinator: NSObject,NSTextViewDelegate { var parent:BASICSourceEditor var completionRequest:UUID var actionID:UUID? init(_ parent:BASICSourceEditor) { self.parent=parent; completionRequest=parent.completionRequest } func textDidChange(_ notification:Notification) { guard let editor=notification.object as? BASICTextView else { return } parent.text=editor.string; highlight(editor); reportCursor(editor) editor.configureDebug(points: parent.breakpoints, stoppedLine: parent.stoppedLine, token: parent.stoppedToken, toggle: parent.toggleBreakpoint) } func textViewDidChangeSelection(_ notification:Notification) { guard let editor=notification.object as? BASICTextView else { return }; reportCursor(editor) } func reportCursor(_ editor:NSTextView) { let offset=editor.selectedRange().location DispatchQueue.main.async { [weak self,weak editor] in guard let self,let editor,editor.selectedRange().location == offset else { return }; self.parent.cursorChanged(offset) } } func textView(_ textView:NSTextView,shouldChangeTextIn affectedCharRange:NSRange,replacementString:String?) -> Bool { guard let replacementString else { return true } let current=textView.string as NSString guard affectedCharRange.location <= current.length, NSMaxRange(affectedCharRange) <= current.length else { return false } guard current.replacingCharacters(in:affectedCharRange,with:replacementString).utf8.count <= BASICLanguage.maximumSourceBytes else { parent.assistance("BASIC source is limited to 1 MB."); return false }; return true } func highlight(_ editor:NSTextView) { guard let storage=editor.textStorage else { return } storage.beginEditing() let full=NSRange(location:0,length:storage.length) storage.addAttributes([.foregroundColor:NSColor.textColor,.font:NSFont.monospacedSystemFont(ofSize:14,weight:.regular)],range:full) for span in BASICLanguage.spans(editor.string) { let color:NSColor switch span.kind { case .keyword: color = .systemPurple case .number: color = .systemBlue case .string: color = .systemRed case .comment: color = .secondaryLabelColor case .data: color = .systemBrown } storage.addAttribute(.foregroundColor,value:color,range:span.range) } storage.endEditing() editor.typingAttributes=[.foregroundColor:NSColor.textColor,.font:NSFont.monospacedSystemFont(ofSize:14,weight:.regular)] } } } /// Native completion with an explicit acceptance operation, so Escape and moving /// through candidates never alter the source or its Undo history. final class BASICTextView: NSTextView, SourceFindEditor { weak var sourceFind: SourceFind? var assistance:((String)->Void)? var quickHelp: ((String?) -> Void)? private var helpOffset: Int? override func menu(for event: NSEvent) -> NSMenu? { let menu = super.menu(for: event) ?? NSMenu() helpOffset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil)) let item = NSMenuItem(title: "Quick Help for BASIC Command", action: #selector(showCommandHelp), keyEquivalent: "") item.target = self menu.insertItem(.separator(), at: 0); menu.insertItem(item, at: 0) return menu } @objc private func showCommandHelp() { quickHelp?(BASICReferenceContext.keyword(in: string, at: helpOffset ?? selectedRange().location)) helpOffset = nil } override func mouseDown(with event: NSEvent) { if event.modifierFlags.contains(.option), event.clickCount == 1 { let offset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil)) if let keyword = BASICReferenceContext.keyword(in: string, at: offset) { quickHelp?(keyword); return } } super.mouseDown(with: event) } private var sourceForCompletion:String? private var completion:BASICLanguage.Completion? private var completionOffset=0 private(set) var numberedRows: [BASICLanguage.NumberedLine] = [] private(set) var breakpointLines: Set = [] private var decoratedSource = "" private var executionLine: Int? private var executionToken: NSRange? func configureDebug(points: Set, stoppedLine: Int?, token: NSRange? = nil, toggle: @escaping (Int) -> Void) { let ruler = enclosingScrollView?.verticalRulerView as? BASICBreakpointRuler ruler?.onClick = toggle ruler?.active = isEditable ruler?.points = points let sourceChanged = decoratedSource != string let lineChanged = executionLine != stoppedLine || executionToken != token guard sourceChanged || lineChanged || breakpointLines != points else { return } decoratedSource = string; breakpointLines = points; executionLine = stoppedLine; executionToken = token if sourceChanged { numberedRows = BASICLanguage.analyze(string).lines } let full = NSRange(location: 0, length: (string as NSString).length) layoutManager?.removeTemporaryAttribute(.backgroundColor, forCharacterRange: full) if let stoppedLine, let row = numberedRows.first(where: { $0.number == stoppedLine }) { layoutManager?.addTemporaryAttribute(.backgroundColor, value: NSColor.systemYellow.withAlphaComponent(0.2), forCharacterRange: row.range) if let token, token.location >= row.range.location, NSMaxRange(token) <= NSMaxRange(row.range) { layoutManager?.addTemporaryAttribute(.backgroundColor, value: NSColor.systemOrange.withAlphaComponent(0.5), forCharacterRange: token) } if lineChanged { scrollRangeToVisible(token ?? row.range) } } ruler?.invalidateMarkers() } private(set) var inlineSuggestion: BASICLanguage.InlineCompletion? private var inlineSource = "" private var inlineSelection = NSRange(location: NSNotFound, length: 0) private var inlineDismissed = false func refreshInlineSuggestion() { let selection = selectedRange() if let sourceForCompletion, sourceForCompletion != string || selection != NSRange(location: completionOffset, length: 0) { self.sourceForCompletion = nil; completion = nil } if inlineSource != string || inlineSelection != selection { inlineDismissed = false inlineSource = string; inlineSelection = selection } inlineSuggestion = isEditable && !hasMarkedText() && selection.length == 0 && !inlineDismissed && sourceForCompletion == nil ? BASICLanguage.inlineCompletion(string, at: selection.location) : nil setAccessibilityHelp(inlineSuggestion.map { "Suggested keyword \($0.word). Press Tab to accept or Escape to dismiss." } ?? "Numbered BASIC source. Return continues line numbering. Control–Space shows keyword completions.") needsDisplay = true } override func didChangeText() { super.didChangeText() refreshInlineSuggestion() } override func setSelectedRange(_ charRange: NSRange, affinity: NSSelectionAffinity, stillSelecting flag: Bool) { super.setSelectedRange(charRange, affinity: affinity, stillSelecting: flag) refreshInlineSuggestion() } override func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder(); refreshInlineSuggestion(); return result } override func resignFirstResponder() -> Bool { let result = super.resignFirstResponder(); needsDisplay = true; return result } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) guard isEditable, !hasMarkedText(), window?.firstResponder === self, let window, let suggestion = inlineSuggestion, inlineSource == string, inlineSelection == selectedRange() else { return } // Draw separately: previews never enter text storage, saves, transfers, // accessibility's source value, or the Undo history. let screenRect = firstRect(forCharacterRange: selectedRange(), actualRange: nil) let rect = convert(window.convertFromScreen(screenRect), from: nil) (suggestion.suffix as NSString).draw(at: rect.origin, withAttributes: [ .font: font ?? NSFont.monospacedSystemFont(ofSize: 14, weight: .regular), .foregroundColor: NSColor.secondaryLabelColor ]) } override func insertTab(_ sender: Any?) { refreshInlineSuggestion() guard let suggestion = inlineSuggestion else { super.insertTab(sender); return } breakUndoCoalescing() insertText(suggestion.word, replacementRange: suggestion.range) breakUndoCoalescing() undoManager?.setActionName("Complete BASIC Keyword") } override func cancelOperation(_ sender: Any?) { if inlineSuggestion != nil { inlineDismissed = true; refreshInlineSuggestion() } else { // AppKit owns a native completion popup's Escape. Cached candidates // alone do not mean that a popup is still handling the command. sourceForCompletion = nil; completion = nil if sourceFind?.cancel(from: self) != true { // cancelOperation is optional; NSTextView need not implement a // superclass method for this standard text command. _ = nextResponder?.tryToPerform(#selector(NSResponder.cancelOperation(_:)), with: sender) } } } override func insertNewline(_ sender: Any?) { guard isEditable, !hasMarkedText(), selectedRange().length == 0, let insertion = BASICLanguage.nextLineInsertion(string, at: selectedRange().location) else { super.insertNewline(sender); return } breakUndoCoalescing() insertText(insertion, replacementRange: selectedRange()) breakUndoCoalescing() undoManager?.setActionName("Insert BASIC Line") } /// Apply an explicit source edit through AppKit so the ordinary Undo stack, /// source binding, selection and syntax highlighting remain synchronized. @discardableResult func applyEditorAction(_ action: BASICEditorAction, revealReplacementAt offset: Int? = nil) -> Bool { guard isEditable, !hasMarkedText(), string == action.expectedSource else { return false } switch action.operation { case .replace(let source, let undoName): guard source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false } if source != string { breakUndoCoalescing() insertText(source, replacementRange: NSRange(location: 0, length: (string as NSString).length)) breakUndoCoalescing() guard string == source else { return false } undoManager?.setActionName(undoName) } if let offset { setSelectedRange(NSRange(location: min(max(0, offset), (source as NSString).length), length: 0)) } case .select(let range): let length = (string as NSString).length guard range.location >= 0, range.location <= length, range.length >= 0, range.length <= length - range.location else { return false } setSelectedRange(range) } scrollRangeToVisible(selectedRange()) window?.makeFirstResponder(self) return true } override func complete(_ sender:Any?) { guard prepareCompletion() else { return }; super.complete(sender) } @discardableResult func prepareCompletion() -> Bool { sourceForCompletion=nil; completion=nil guard isEditable,!hasMarkedText(),selectedRange().length == 0, let next=BASICLanguage.completion(string,at:selectedRange().location) else { assistance?("Type the beginning of a BASIC keyword, then choose Complete."); return false } sourceForCompletion=string; completion=next; completionOffset=selectedRange().location refreshInlineSuggestion() assistance?("\(next.words.count) BASIC keyword suggestions. Return accepts; Escape cancels.") return true } override var rangeForUserCompletion:NSRange { sourceForCompletion == string ? completion?.range ?? NSRange(location:NSNotFound,length:0) : NSRange(location:NSNotFound,length:0) } override func completions(forPartialWordRange charRange:NSRange,indexOfSelectedItem index:UnsafeMutablePointer?) -> [String]? { guard sourceForCompletion == string, completion?.range == charRange else { return [] } // Highlight the first choice so Return accepts it immediately. // insertCompletion still refuses provisional list navigation. index?.pointee = 0; return completion?.words } override func insertCompletion(_ word:String,forPartialWordRange charRange:NSRange,movement:Int,isFinal flag:Bool) { guard flag else { return } defer { sourceForCompletion=nil; completion=nil; refreshInlineSuggestion() } guard movement != NSTextMovement.cancel.rawValue,isEditable,!hasMarkedText(),sourceForCompletion == string, selectedRange() == NSRange(location:completionOffset,length:0),completion?.range == charRange, completion?.words.contains(word) == true else { return } breakUndoCoalescing(); insertText(word,replacementRange:charRange); breakUndoCoalescing() undoManager?.setActionName("Complete BASIC Keyword") } override func performKeyEquivalent(with event:NSEvent) -> Bool { let modifiers=event.modifierFlags.intersection([.command,.control,.option,.shift]) if event.keyCode == 49,modifiers == [.control] { complete(nil); return true } return super.performKeyEquivalent(with:event) } } /// Visual gutter plus the native toolbar action provide mouse and keyboard /// alternatives. Line numbers remain ordinary editable source text. final class BASICBreakpointRuler: BreakpointRuler { private weak var editor: BASICTextView? init(textView: BASICTextView) { editor = textView super.init(scrollView: textView.enclosingScrollView!, orientation: .verticalRuler) clientView = textView; ruleThickness = 30 setAccessibilityLabel("BASIC breakpoint gutter") setAccessibilityHelp("Click beside a numbered statement to toggle its breakpoint. The toolbar offers the same action at the insertion point.") } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func targets() -> [(Int, NSRect)] { guard let editor, let layout = editor.layoutManager, let container = editor.textContainer else { return [] } let origin = editor.textContainerOrigin // Horizontal scrolling must not change which rows appear in the gutter. let viewport = NSRect(x: 0, y: editor.visibleRect.minY - origin.y, width: max(1, editor.bounds.width), height: editor.visibleRect.height) let glyphs = layout.glyphRange(forBoundingRect: viewport, in: container) let visible = layout.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil) return editor.numberedRows.compactMap { row in guard NSLocationInRange(row.labelRange.location, visible) else { return nil } let glyph = layout.glyphIndexForCharacter(at: row.labelRange.location) let fragment = layout.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) let point = convert(NSPoint(x: 0, y: fragment.midY + editor.textContainerOrigin.y), from: editor) return (row.number, NSRect(x: 8, y: point.y - 6, width: 12, height: 12)) } } override var wantsDefaultClipping: Bool { true } override func draw(_ dirtyRect: NSRect) { // NSRulerView's standard edge treatment can extend outside its frame. // This gutter has no native ruler ticks or markers: draw its own edge. NSGraphicsContext.saveGraphicsState() NSBezierPath(rect: bounds).addClip() drawHashMarksAndLabels(in: dirtyRect) NSColor.separatorColor.setFill() NSRect(x: bounds.maxX - 1, y: bounds.minY, width: 1, height: bounds.height).fill() NSGraphicsContext.restoreGraphicsState() } override func drawHashMarksAndLabels(in rect: NSRect) { NSColor.windowBackgroundColor.setFill(); bounds.fill() guard let editor else { return } for (line, target) in targets() where target.intersects(bounds) { let path = NSBezierPath(ovalIn: target) if editor.breakpointLines.contains(line) { NSColor.systemRed.setFill(); path.fill() } else { NSColor.separatorColor.setStroke(); path.lineWidth = 1; path.stroke() } } } override func visibleRows() -> [Row] { targets().compactMap { line, marker in let hit = marker.insetBy(dx: -8, dy: -3).intersection(bounds) return hit.isEmpty ? nil : (line, hit) } } } private struct BASICInspectionView: View { @ObservedObject var model: BASICDevelopmentModel let valuesHeight: CGFloat @State private var expanded = true @State private var showingWatches = false var body: some View { Divider() DisclosureGroup(isExpanded: $expanded) { VStack(alignment: .leading, spacing: 6) { HStack { Picker("Inspect", selection: $showingWatches) { Text("Variables").tag(false); Text("Watches").tag(true) }.pickerStyle(.segmented).labelsHidden().frame(width: 210).accessibilityIdentifier("basic.inspector-tabs") Text(model.inspectionStatus).font(.caption).foregroundStyle(.secondary).lineLimit(2) .accessibilityIdentifier("basic.inspection-status") Spacer(minLength: 0) Button { model.refreshInspection() } label: { Image(systemName: "arrow.clockwise") } .accessibilityLabel("Refresh BASIC variables").help("Refresh values at the current BASIC stop") .disabled(!model.inspectionAvailable).accessibilityIdentifier("basic.refresh-variables") } if showingWatches { HStack { TextField("Variable or array element, e.g. NAME$ or A(2)", text: $model.watchEntry) .textFieldStyle(.roundedBorder).onSubmit { model.addWatch() } .accessibilityIdentifier("basic.watch-entry") Button { model.addWatch() } label: { Label("Add", systemImage: "plus") } .disabled(model.watchEntry.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) .accessibilityIdentifier("basic.add-watch") } if let error = model.watchError { Text(error).font(.caption).foregroundStyle(.orange) } } ScrollView { LazyVStack(alignment: .leading, spacing: 5) { if showingWatches { if model.watches.isEmpty { Text("Watch a variable or a specific array element without changing the program.").foregroundStyle(.secondary) } ForEach(model.watches, id: \.self) { name in HStack(alignment: .top) { Text(name).fontWeight(.medium).frame(width: 160, alignment: .leading) Text(model.watchValue(name)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) .accessibilityIdentifier("basic.watch-value.\(name)") Button { model.removeWatch(name) } label: { Image(systemName: "minus.circle") } .buttonStyle(.borderless).help("Remove watch \(name)").accessibilityLabel("Remove watch \(name)") }.font(.system(.callout, design: .monospaced)) } } else if model.variables.isEmpty { Text(model.inspectionAvailable ? "Variables appear here as statements assign them." : "Run to a breakpoint or use Step to see current values.") .foregroundStyle(.secondary) } else { ForEach(model.variables) { variable in BASICVariableView(variable: variable) } } }.frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 4).padding(.horizontal, 8) }.frame(height: max(36, valuesHeight - (showingWatches ? 60 : 0))) .accessibilityIdentifier("basic.inspector-values") }.padding(.top, 6) } label: { Label("Variables and Watches", systemImage: "list.bullet.rectangle").font(.callout.bold()) }.padding(.horizontal, 14).padding(.vertical, 8) } } private struct BASICVariableView: View { let variable: BASICVariable @State private var expanded = false @State private var page = 0 private let pageSize = 32 private var first: Int { min(page * pageSize, max(0, variable.elements.count - 1) / pageSize * pageSize) } var body: some View { if variable.dimensions.isEmpty { row(variable.name, variable.value) } else { VStack(alignment: .leading, spacing: 4) { Button { expanded.toggle() } label: { HStack { Image(systemName: expanded ? "chevron.down" : "chevron.right").frame(width: 12) Text(variable.title).fontWeight(.medium).frame(width: 140, alignment: .leading) Text(variable.value).frame(maxWidth: .infinity, alignment: .leading) }.font(.system(.callout, design: .monospaced)).padding(.vertical, 3).contentShape(Rectangle()) }.buttonStyle(.plain).accessibilityIdentifier("basic.array.\(variable.name)") .accessibilityLabel("Array \(variable.title)").accessibilityValue(expanded ? "Expanded" : "Collapsed") .help("Show array elements. Bounds are inclusive; subscripts start at zero.") if expanded { VStack(alignment: .leading, spacing: 4) { ForEach(first.. pageSize { HStack { Button("Previous", systemImage: "chevron.left") { page = max(0, page - 1) }.disabled(first == 0) Text("\(first + 1)–\(min(first + pageSize, variable.elements.count)) of \(variable.elements.count)").font(.caption) Button("Next", systemImage: "chevron.right") { page = first / pageSize + 1 }.disabled(first + pageSize >= variable.elements.count) } } }.padding(.leading, 20) } } } } private func row(_ name: String, _ value: String) -> some View { HStack(alignment: .top) { Text(name).fontWeight(.medium).frame(width: 160, alignment: .leading) Text(value).frame(maxWidth: .infinity, alignment: .leading) .accessibilityIdentifier("basic.variable-value.\(name)") }.font(.system(.callout, design: .monospaced)).textSelection(.enabled) } }