Sources/OrgstarMobile/MobileEditor+Completion.swift
299 lines · 13843 bytes
1#if os(iOS)
2import OrgApp
3import GameController
4import OrgCore
5import UIKit
6
7/// The completion list under the caret, as on the Mac: keys on a hardware keyboard pick a
8/// row, and a tap inserts one.
9final class CompletionListView: UIView {
10 static let rows = 8
11 private(set) var list: CompletionList
12 private let stack = UIStackView()
13 var onChoose: ((String) -> Void)?
14
15 init(_ completion: Completion, selection: Int?) {
16 list = CompletionList(completion, selection: selection)
17 super.init(frame: .zero)
18 backgroundColor = .secondarySystemBackground
19 layer.borderColor = UIColor.separator.cgColor
20 layer.borderWidth = 1
21 layer.cornerRadius = 6
22 layer.shadowOpacity = 0.15
23 layer.shadowRadius = 6
24 stack.axis = .vertical
25 stack.alignment = .fill
26 addSubview(stack)
27 accessibilityIdentifier = "completion"
28 }
29
30 required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
31
32 var completion: Completion { list.completion }
33
34 func update(_ completion: Completion) { list.update(completion) }
35
36 func key(_ chord: KeyChord) -> CompletionList.Action { list.key(chord) }
37
38 /// Lays the rows out under `caret`, or above it when there isn't room below, kept inside
39 /// `bounds`: the part of the text view not under the keyboard and the key bar.
40 func show(under caret: CGRect, within bounds: CGRect, font: UIFont) {
41 stack.arrangedSubviews.forEach { $0.removeFromSuperview() }
42 var width: CGFloat = 80
43 for index in list.visible(rows: Self.rows) {
44 let candidate = completion.candidates[index]
45 let label = UILabel()
46 label.text = " " + completion.label(candidate) + (completion.kind == .snippet ? " " + String(localized: "snippet", comment: "Marks a snippet in the completion list") : "") + " "
47 label.font = font
48 label.lineBreakMode = .byTruncatingTail
49 label.isUserInteractionEnabled = true
50 label.backgroundColor = index == list.selection ? .tintColor : .clear
51 label.textColor = index == list.selection ? .white : .label
52 label.tag = index
53 label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped(_:))))
54 label.heightAnchor.constraint(equalToConstant: max(28, font.lineHeight + 6)).isActive = true
55 stack.addArrangedSubview(label)
56 width = max(width, label.intrinsicContentSize.width)
57 }
58 width = min(width, bounds.width - 16)
59 let height = stack.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
60 let x = min(max(bounds.minX + 8, caret.minX), bounds.maxX - width - 8)
61 let below = caret.maxY + 2
62 let y = below + height <= bounds.maxY || caret.minY - 2 - height < bounds.minY ? below : caret.minY - 2 - height
63 frame = CGRect(x: x, y: y, width: width, height: height)
64 stack.frame = CGRect(origin: .zero, size: frame.size)
65 }
66
67 @objc private func tapped(_ gesture: UITapGestureRecognizer) {
68 guard let index = gesture.view?.tag, completion.candidates.indices.contains(index) else { return }
69 onChoose?(completion.candidates[index])
70 }
71}
72
73extension MobileEditor {
74 /// Org files complete Org's positions; other files only words.
75 var completesOrg: Bool { fileName.map(DocumentSession.isOrgPath) ?? true }
76
77 /// `completion-at-point`: one candidate is inserted, several are listed.
78 func completeAtPoint() {
79 guard completesOrg, let completion = OrgCompletion.at(editContext()), !completion.candidates.isEmpty || completion.query != nil else {
80 closeCompletion()
81 onMessage?("No match")
82 return
83 }
84 if completion.query == nil, completion.candidates.count == 1 {
85 closeCompletion()
86 insertCompletion(completion, completion.candidates[0])
87 return
88 }
89 openCompletion(completion)
90 }
91
92 /// Words in a list, the first chosen, or with `last` the last.
93 func completeWord(last: Bool) {
94 guard let completion = Dabbrev.completion(editContext(), others: otherBuffers()) else {
95 closeCompletion()
96 return fail("No possible abbreviation preceding point")
97 }
98 if completion.candidates.isEmpty, completionSource == nil { return fail("No dynamic expansion for `\(completion.typed)' found") }
99 openCompletion(completion, select: last ? completion.candidates.count - 1 : 0)
100 }
101
102 func openCompletion(_ completion: Completion, select: Int? = nil) {
103 completionFetched = nil
104 suggestions.dismissed = false
105 if !completion.candidates.isEmpty { showCompletion(completion, select: select) }
106 guard let query = completion.query, let source = completionSource else {
107 if completion.candidates.isEmpty { closeCompletion() }
108 return
109 }
110 let start = completion.range.lowerBound, kind = completion.kind
111 completionTask?.cancel()
112 completionTask = Task { [weak self] in
113 let result = await source(query)
114 guard !Task.isCancelled, let self else { return }
115 self.completionFetched = (kind, start, result)
116 self.fetchedCompletion(kind: kind, start: start, select: select)
117 }
118 }
119
120 private func fetchedCompletion(kind: Completion.Kind, start: Int, select: Int?) {
121 guard textView.selectedRange.length == 0 else { return }
122 let open = completionList?.completion
123 guard open == nil || (open?.kind == kind && open?.range.lowerBound == start) else { return }
124 guard let current = CompletionFlow.current(editContext(), open: nil, words: kind == .word, others: otherBuffers, fetched: completionFetched),
125 current.kind == kind, current.range.lowerBound == start, !current.candidates.isEmpty else { return }
126 showCompletion(current, select: open == nil ? select.map { $0 < 0 || $0 >= current.candidates.count ? current.candidates.count - 1 : $0 } : nil)
127 }
128
129 func showCompletion(_ completion: Completion, select: Int? = nil) {
130 let view: CompletionListView
131 if let open = completionList {
132 open.update(completion)
133 view = open
134 } else {
135 view = CompletionListView(completion, selection: select)
136 view.onChoose = { [weak self, weak view] candidate in
137 guard let self, let view else { return }
138 let completion = view.completion
139 self.closeCompletion()
140 self.insertCompletion(completion, candidate)
141 }
142 completionList = view
143 textView.addSubview(view)
144 }
145 let row = SuggestionRow.usesRow(hardwareKeyboard: GCKeyboard.coalesced != nil)
146 view.isHidden = row
147 suggestions.completion = row ? view.completion : nil
148 guard !row, let position = textView.position(from: textView.beginningOfDocument, offset: completion.range.lowerBound) else { return }
149 let caret = textView.caretRect(for: position)
150 let insets = textView.adjustedContentInset
151 let visible = CGRect(x: textView.contentOffset.x, y: textView.contentOffset.y + insets.top,
152 width: textView.bounds.width, height: textView.bounds.height - insets.top - insets.bottom)
153 view.show(under: caret, within: visible, font: theme.font)
154 }
155
156 func closeCompletion() {
157 completionTimer?.invalidate()
158 completionTimer = nil
159 completionTask?.cancel()
160 completionList?.removeFromSuperview()
161 completionList = nil
162 suggestions.completion = nil
163 suggestions.dismissed = false
164 }
165
166 /// A candidate tapped in the suggestion row, inserted as one chosen from the list.
167 func chooseSuggestion(_ candidate: String) {
168 guard let completion = completionList?.completion else { return }
169 closeCompletion()
170 insertCompletion(completion, candidate)
171 }
172
173 /// After typing: the open list follows the text; otherwise, as the settings say, a list
174 /// opens after a pause once enough is typed.
175 func textTyped() {
176 completionTimer?.invalidate()
177 completionTimer = nil
178 if completionList != nil { return refreshCompletion() }
179 guard let delay = CompletionAuto.delay(options.completion, modal: modal, insertState: vim.mode == .insert, isOrg: completesOrg) else { return }
180 completionTimer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { [weak self] _ in
181 MainActor.assumeIsolated { self?.autoComplete() }
182 }
183 }
184
185 func autoComplete() {
186 guard completionList == nil, textView.selectedRange.length == 0, textView.markedTextRange == nil else { return }
187 let context = editContext()
188 var completion = completesOrg ? OrgCompletion.at(context) : nil
189 if options.completion.words, completion.map({ $0.candidates.isEmpty && $0.query == nil }) ?? true {
190 completion = Dabbrev.completion(context, others: otherBuffers())
191 }
192 guard CompletionAuto.opens(completion, options.completion), let completion else { return }
193 openCompletion(completion)
194 }
195
196 func refreshCompletion() {
197 guard let open = completionList else { return }
198 guard textView.selectedRange.length == 0,
199 let completion = CompletionFlow.current(editContext(), open: open.completion, words: false, others: otherBuffers, fetched: completionFetched),
200 completion.range.lowerBound == open.completion.range.lowerBound, !completion.candidates.isEmpty else {
201 closeCompletion()
202 return
203 }
204 showCompletion(completion)
205 }
206
207 func insertCompletion(_ completion: Completion, _ candidate: String) {
208 defer {
209 completionTimer?.invalidate()
210 completionTimer = nil
211 }
212 if completion.kind == .snippet {
213 textView.selectedRange = NSRange(location: completion.range.lowerBound, length: completion.range.count)
214 _ = perform(ExpandNamedSnippet(trigger: candidate))
215 return
216 }
217 if completion.kind == .idLink || completion.kind == .denoteLink { return insertLink(completion, candidate) }
218 let (text, caret) = completion.insertion(candidate)
219 applyEdits([TextEdit(range: completion.range, replacement: text)])
220 textView.selectedRange = NSRange(location: completion.range.lowerBound + caret, length: 0)
221 }
222
223 /// A link to the chosen heading or note, with an ID given to a heading without one.
224 func insertLink(_ completion: Completion, _ candidate: String) {
225 guard let item = completion.item(candidate) else { return }
226 var created: [TextEdit] = []
227 var id = item.id
228 if id == nil, completion.kind == .idLink {
229 if item.path == (options.filePath ?? "") {
230 let newID = UUID().uuidString.lowercased()
231 if let edits = CompletionFlow.createID(item, in: editContext(), newID: newID) {
232 applyEdits(edits)
233 created = edits
234 id = newID
235 }
236 } else {
237 id = createID?(item)
238 }
239 }
240 guard let id else { return fail("Can't give \(item.title) an ID") }
241 let edit = CompletionFlow.linkEdit(completion, item, id: id, after: created)
242 applyEdits([edit])
243 textView.selectedRange = NSRange(location: edit.range.lowerBound + edit.replacement.utf16.count, length: 0)
244 }
245
246 /// `dabbrev-expand`, repeated right after for the next expansion.
247 func dabbrevExpand() {
248 closeCompletion()
249 let caret = textView.selectedRange.location
250 let repeated = dabbrevRevision == document.revision && dabbrev?.end == caret
251 if !repeated {
252 guard let expansion = DabbrevExpansion(editContext(), others: otherBuffers()) else { return fail("No possible abbreviation preceding point") }
253 dabbrev = expansion
254 if let source = completionSource {
255 let abbrev = expansion.abbrev, start = expansion.start
256 completionTask = Task { [weak self] in
257 let result = await source(.words(abbrev))
258 guard !Task.isCancelled, let self, self.dabbrev?.start == start else { return }
259 self.dabbrev?.add(result.strings)
260 }
261 }
262 }
263 guard var expansion = dabbrev else { return }
264 let (edit, exhausted) = expansion.advance()
265 dabbrev = expansion
266 if (document.text as NSString).substring(with: NSRange(edit.range)) != edit.replacement { applyEdits([edit]) }
267 textView.selectedRange = NSRange(location: expansion.end, length: 0)
268 dabbrevRevision = document.revision
269 if exhausted { fail(expansion.failure) }
270 }
271
272 /// Keys while the list is open; nil lets the key through.
273 func completionKey(_ chord: KeyChord) -> Bool? {
274 guard let open = completionList else { return nil }
275 let completion = open.completion
276 switch open.key(chord) {
277 case .shown:
278 showCompletion(open.completion)
279 return true
280 case .insert(let candidate):
281 closeCompletion()
282 insertCompletion(completion, candidate)
283 return true
284 case .common(let common):
285 insertCompletion(completion, common)
286 refreshCompletion()
287 return true
288 case .close:
289 closeCompletion()
290 return true
291 case .closeAndPass:
292 closeCompletion()
293 return nil
294 case .pass:
295 return nil
296 }
297 }
298}
299#endif