// SPDX-License-Identifier: GPL-3.0-or-later import AppKit import SwiftUI /// Source editors keep a weak link to their window's finder. An inactive tab /// may retain that link, so cancellation also checks the active editor identity. @MainActor protocol SourceFindEditor: AnyObject { var sourceFind: SourceFind? { get set } } /// Window-local search of the live source buffer. Commands resolve the editor again /// after a tab change; they never edit the search field, disk file, or guest. @MainActor final class SourceFind: ObservableObject { weak var editor: NSTextView? { didSet { (editor as? SourceFindEditor)?.sourceFind = self } } @Published var query = "" { didSet { if !query.utf8.elementsEqual(oldValue.utf8) { selectMatch(includingSelection: true) } } } @Published var matchCase = false { didSet { selectMatch(includingSelection: true) } } @Published var replacement = "" @Published private(set) var message: String? @Published private(set) var visible = false @Published private(set) var replacing = false @Published private(set) var focusRequest = 0 private var cachedSource: String? private var cachedQuery = "" private var cachedCase = false private var cachedRanges: [NSRange] = [] func matches(in source: String) -> [NSRange] { if let cachedSource, source.utf8.elementsEqual(cachedSource.utf8), query.utf8.elementsEqual(cachedQuery.utf8), cachedCase == matchCase { return cachedRanges } let text = source as NSString var ranges: [NSRange] = [] var start = 0 let options: NSString.CompareOptions = matchCase ? [.literal] : [.literal, .caseInsensitive] while !query.isEmpty && start < text.length { let range = text.range(of: query, options: options, range: NSRange(location: start, length: text.length - start)) guard range.location != NSNotFound, range.length > 0 else { break } ranges.append(range) start = NSMaxRange(range) } cachedSource = String(decoding: source.utf8, as: UTF8.self); cachedQuery = query; cachedCase = matchCase; cachedRanges = ranges return ranges } func show(replace: Bool = false) { message = nil visible = true; replacing = replace; focusRequest += 1 } func close() { visible = false if let editor { editor.window?.makeFirstResponder(editor) } } func cancel(from source: NSTextView) -> Bool { guard visible, editor === source else { return false } close() return true } func useSelection() { guard let editor, editor.selectedRange().length > 0 else { return } query = (editor.string as NSString).substring(with: editor.selectedRange()) show() } func selectMatch(backward: Bool = false, includingSelection: Bool = false) { guard let editor else { return } message = nil if query.isEmpty { if !visible { show() }; return } let ranges = matches(in: editor.string) let selection = editor.selectedRange() let range: NSRange? if backward { range = ranges.last(where: { NSMaxRange($0) <= selection.location }) ?? ranges.last } else { let start = includingSelection ? selection.location : NSMaxRange(selection) range = ranges.first(where: { $0.location >= start }) ?? ranges.first } if let range { editor.setSelectedRange(range) editor.scrollRangeToVisible(range) } } func replace(all: Bool) { guard let editor, editor.isEditable, !editor.hasMarkedText(), !query.isEmpty else { return } let source = editor.string as NSString let originalLength = source.length message = nil let ranges = matches(in: editor.string) guard let first = ranges.first, let last = ranges.last else { return } let range: NSRange let newText: String if all { // One native edit gives the editor's existing size checks, debug // invalidation, recovery and Undo one consistent document change. range = NSUnionRange(first, last) // The workspaces support 1 MiB source files. Check a potentially large // expansion before constructing it (for example replacing each space // in a large source with a pasted paragraph). let sourceBytes = editor.string.utf8.count let limit = max(sourceBytes, CMOCProject.maximumSourceBytes) let (insertedBytes, overflow) = replacement.utf8.count.multipliedReportingOverflow(by: ranges.count) if overflow || insertedBytes > limit { message = "Replacement would exceed the source size limit." return } let removedBytes = ranges.reduce(0) { $0 + source.substring(with: $1).utf8.count } guard sourceBytes - removedBytes <= limit - insertedBytes else { message = "Replacement would exceed the source size limit." return } var pieces: [String] = [] var cursor = first.location for match in ranges { pieces.append(source.substring(with: NSRange(location: cursor, length: match.location - cursor))) pieces.append(replacement) cursor = NSMaxRange(match) } newText = pieces.joined() } else { range = editor.selectedRange() guard ranges.contains(range) else { selectMatch(includingSelection: true); return } newText = replacement } if source.substring(with: range).utf8.elementsEqual(newText.utf8) { if !all { selectMatch() } return } editor.breakUndoCoalescing() editor.insertText(newText, replacementRange: range) editor.breakUndoCoalescing() // The delegate can reject oversized edits. Don't rename an unrelated undo. let result = editor.string as NSString let inserted = NSRange(location: range.location, length: newText.utf16.count) guard result.length == originalLength - range.length + inserted.length, result.substring(with: inserted).utf8.elementsEqual(newText.utf8) else { return } editor.window?.makeFirstResponder(editor) editor.undoManager?.setActionName(all ? "Replace All in File" : "Replace") if !all { selectMatch() } } } private struct SourceFindFocusKey: FocusedValueKey { typealias Value = SourceFind } private struct ProjectSearchFocusKey: FocusedValueKey { typealias Value = () -> Void } private struct EmulatorWindowFocusKey: FocusedValueKey { typealias Value = Bool } extension FocusedValues { var sourceFind: SourceFind? { get { self[SourceFindFocusKey.self] } set { self[SourceFindFocusKey.self] = newValue } } var projectSearch: (() -> Void)? { get { self[ProjectSearchFocusKey.self] } set { self[ProjectSearchFocusKey.self] = newValue } } var emulatorWindow: Bool? { get { self[EmulatorWindowFocusKey.self] } set { self[EmulatorWindowFocusKey.self] = newValue } } } struct SourceFindCommands: Commands { @FocusedValue(\.sourceFind) private var finder @FocusedValue(\.manualPageFind) private var pageFind @FocusedValue(\.projectSearch) private var projectSearch var body: some Commands { CommandGroup(after: .textEditing) { if let finder { Menu("Find") { Button("Find…") { finder.show() }.keyboardShortcut("f") Button("Find and Replace…") { finder.show(replace: true) }.keyboardShortcut("f", modifiers: [.command, .option]) Divider() Button("Find Next") { finder.selectMatch() }.keyboardShortcut("g") Button("Find Previous") { finder.selectMatch(backward: true) }.keyboardShortcut("g", modifiers: [.command, .shift]) Button("Use Selection for Find") { finder.useSelection() }.keyboardShortcut("e") if let projectSearch { Divider() Button("Find in Project…", action: projectSearch).keyboardShortcut("f", modifiers: [.command, .shift]) } } } else if let pageFind { Menu("Find") { Button("Find on This Page…") { pageFind.show() }.keyboardShortcut("f") Button("Find Next") { pageFind.move() }.keyboardShortcut("g") Button("Find Previous") { pageFind.move(backward: true) } .keyboardShortcut("g", modifiers: [.command, .shift]) } } } } } struct SourceFindButton: View { let finder: SourceFind var body: some View { Button { finder.show() } label: { Image(systemName: "magnifyingglass") } .help("Find text in the current file (⌘F)").accessibilityLabel("Find in File") .accessibilityIdentifier("source.find.open") } } /// The search field owns Return/Shift-Return while its AppKit field editor is /// active. Request focus after attachment, including when a menu opens the bar. private struct SourceFindField: NSViewRepresentable { @ObservedObject var finder: SourceFind final class Field: NSTextField { var wantsSearchFocus = false func requestSearchFocus() { wantsSearchFocus = true DispatchQueue.main.async { [weak self] in self?.applyFocus() } } private func applyFocus() { guard wantsSearchFocus, let window, window.isKeyWindow else { return } wantsSearchFocus = false window.makeFirstResponder(self) selectText(nil) } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() if wantsSearchFocus { requestSearchFocus() } } } final class Coordinator: NSObject, NSTextFieldDelegate { let finder: SourceFind var focusRequest: Int? init(_ finder: SourceFind) { self.finder = finder } func controlTextDidChange(_ notification: Notification) { guard let field = notification.object as? NSTextField else { return } finder.query = field.stringValue } func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { switch selector { case #selector(NSResponder.insertNewline(_:)), #selector(NSResponder.insertNewlineIgnoringFieldEditor(_:)), #selector(NSResponder.insertLineBreak(_:)): finder.selectMatch(backward: NSApp.currentEvent?.modifierFlags.contains(.shift) == true) return true case #selector(NSResponder.cancelOperation(_:)): finder.close() return true default: return false } } } func makeCoordinator() -> Coordinator { Coordinator(finder) } func makeNSView(context: Context) -> Field { let field = Field() field.placeholderString = "Find in File" field.isBezeled = true; field.bezelStyle = .roundedBezel field.controlSize = .small; field.font = .systemFont(ofSize: NSFont.smallSystemFontSize) field.setContentHuggingPriority(.defaultLow, for: .horizontal) field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) field.setAccessibilityLabel("Find in File"); field.setAccessibilityIdentifier("source.find.query") field.delegate = context.coordinator return field } func updateNSView(_ field: Field, context: Context) { if !field.stringValue.utf8.elementsEqual(finder.query.utf8) { field.stringValue = finder.query } if context.coordinator.focusRequest != finder.focusRequest { context.coordinator.focusRequest = finder.focusRequest field.requestSearchFocus() } } } struct SourceFindBar: View { @ObservedObject var finder: SourceFind let source: String let readOnly: Bool var body: some View { if finder.visible { VStack(alignment: .leading, spacing: 4) { HStack(spacing: 6) { SourceFindField(finder: finder).frame(minWidth: 64) let count = finder.matches(in: source).count if !finder.query.isEmpty { Text(count == 0 ? "No matches" : "\(count) \(count == 1 ? "match" : "matches")") .font(.caption).foregroundStyle(.secondary).accessibilityIdentifier("source.find.count") } Button { finder.selectMatch(backward: true) } label: { Image(systemName: "chevron.up") } .disabled(count == 0).help("Find previous occurrence (⇧⌘G)").accessibilityLabel("Find Previous") Button { finder.selectMatch() } label: { Image(systemName: "chevron.down") } .disabled(count == 0).help("Find next occurrence (⌘G)").accessibilityLabel("Find Next") Toggle("Match Case", isOn: $finder.matchCase).toggleStyle(.checkbox) Button(finder.replacing ? "Hide Replace" : "Show Replace") { finder.show(replace: !finder.replacing) } Button("Done") { finder.close() }.keyboardShortcut(.escape, modifiers: []) } if let message = finder.message { Text(message).font(.caption).foregroundStyle(.secondary) } if finder.replacing { HStack(spacing: 6) { TextField("Replace with", text: $finder.replacement) .accessibilityLabel("Replace with").accessibilityIdentifier("source.find.replacement") Group { Button("Replace") { finder.replace(all: false) } Button("Replace All in File") { finder.replace(all: true) } }.disabled(readOnly || finder.matches(in: source).isEmpty) } } }.textFieldStyle(.roundedBorder).controlSize(.small).padding(.horizontal, 10).padding(.vertical, 5) .background(.bar) .onExitCommand { finder.close() } } } }