-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathNSTextInteractionView.swift
More file actions
319 lines (264 loc) · 9.25 KB
/
Copy pathNSTextInteractionView.swift
File metadata and controls
319 lines (264 loc) · 9.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#if TEXTUAL_ENABLE_TEXT_SELECTION && canImport(AppKit) && !targetEnvironment(macCatalyst)
import SwiftUI
// MARK: - Overview
//
// `NSTextInteractionView` implements selection and link interaction on macOS.
//
// The view sits in an overlay above one or more rendered `Text` fragments. It uses
// `TextSelectionModel` for hit testing and range manipulation, and it respects `exclusionRects`
// so embedded scrollable regions continue to receive input events. Link taps are forwarded to
// `openURL`.
@available(macOS 15, *)
final class NSTextInteractionView: NSView {
var model: TextSelectionModel
var exclusionRects: [CGRect]
var openURL: OpenURLAction
override var acceptsFirstResponder: Bool { true }
override var isFlipped: Bool { true }
override var mouseDownCanMoveWindow: Bool { false }
private var dragStart: TextPosition?
private var selectionAnchor: TextPosition?
init(
model: TextSelectionModel,
exclusionRects: [CGRect],
openURL: OpenURLAction
) {
self.model = model
self.exclusionRects = exclusionRects
self.openURL = openURL
super.init(frame: .zero)
self.wantsLayer = false
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func hitTest(_ point: NSPoint) -> NSView? {
let localPoint = convert(point, from: superview)
let isExcluded = exclusionRects.contains {
$0.contains(localPoint)
}
if isExcluded {
return nil
} else {
return super.hitTest(point)
}
}
override func mouseDown(with event: NSEvent) {
window?.makeFirstResponder(self)
let location = convert(event.locationInWindow, from: nil)
switch event.clickCount {
case 1:
if let url = model.url(for: location) {
openURL(url)
} else {
resetSelection()
}
dragStart = model.closestPosition(to: location)
case 2:
if let position = model.closestPosition(to: location) {
model.selectedRange = model.wordRange(for: position)
}
dragStart = nil
case 3:
if let position = model.closestPosition(to: location) {
model.selectedRange = model.blockRange(for: position)
}
dragStart = nil
default:
break
}
}
override func mouseDragged(with event: NSEvent) {
guard let dragStart else {
return
}
let location = convert(event.locationInWindow, from: nil)
guard let currentPosition = model.closestPosition(to: location) else {
return
}
model.selectedRange = TextRange(from: dragStart, to: currentPosition)
autoscroll(with: event)
}
override func mouseUp(with event: NSEvent) {
dragStart = nil
}
override func rightMouseDown(with event: NSEvent) {
let location = convert(event.locationInWindow, from: nil)
updateSelectionForContextMenu(at: location)
NSMenu.popUpContextMenu(makeContextMenu(), with: event, for: self)
}
override func menu(for event: NSEvent) -> NSMenu? {
let location = convert(event.locationInWindow, from: nil)
updateSelectionForContextMenu(at: location)
return makeContextMenu()
}
override func selectAll(_ sender: Any?) {
model.selectedRange = TextRange(start: model.startPosition, end: model.endPosition)
}
override func keyDown(with event: NSEvent) {
interpretKeyEvents([event])
}
override func moveRightAndModifySelection(_ sender: Any?) {
modifySelection { position, _ in
model.position(from: position, offset: 1)
}
}
override func moveLeftAndModifySelection(_ sender: Any?) {
modifySelection { position, _ in
model.position(from: position, offset: -1)
}
}
override func moveUpAndModifySelection(_ sender: Any?) {
modifySelection { position, anchor in
model.positionAbove(position, anchor: anchor)
}
}
override func moveDownAndModifySelection(_ sender: Any?) {
modifySelection { position, anchor in
model.positionBelow(position, anchor: anchor)
}
}
override func moveWordRightAndModifySelection(_ sender: Any?) {
modifySelection { position, _ in
model.nextWord(from: position)
}
}
override func moveWordLeftAndModifySelection(_ sender: Any?) {
modifySelection { position, _ in
model.previousWord(from: position)
}
}
override func moveParagraphBackwardAndModifySelection(_ sender: Any?) {
modifySelection { position, _ in
model.blockStart(for: position)
}
}
override func moveParagraphForwardAndModifySelection(_ sender: Any?) {
modifySelection { position, _ in
model.blockEnd(for: position)
}
}
private func updateSelectionForContextMenu(at location: CGPoint) {
guard let position = model.closestPosition(to: location) else {
resetSelection()
return
}
if let selectedRange = model.selectedRange, selectedRange.contains(position) {
// do nothing
return
}
model.selectedRange = model.wordRange(for: position)
}
private func makeContextMenu() -> NSMenu {
let contextMenu = NSMenu()
guard let selectedRange = model.selectedRange, !selectedRange.isCollapsed else {
return contextMenu
}
// Get the localized title for the share action
let sharingPicker = NSSharingServicePicker(items: [])
let shareActionTitle = sharingPicker.standardShareMenuItem.title
// Get the localized title for the copy action
let copyActionTitle =
if let defaultMenu = NSTextView.defaultMenu,
let copyAction = defaultMenu.items.first(where: { $0.action == #selector(copy(_:)) })
{
copyAction.title
} else {
NSLocalizedString("Copy", bundle: .main, comment: "")
}
contextMenu.addItem(
.init(
title: shareActionTitle,
action: #selector(share(_:)),
keyEquivalent: ""
)
)
contextMenu.addItem(.separator())
contextMenu.addItem(
.init(
title: copyActionTitle,
action: #selector(copy(_:)),
keyEquivalent: ""
)
)
return contextMenu
}
private func modifySelection(
_ transform: (_ position: TextPosition, _ anchor: TextPosition) -> TextPosition?
) {
guard let selectedRange = model.selectedRange else {
return
}
// set anchor on first move
selectionAnchor = selectionAnchor ?? selectedRange.start
guard let selectionAnchor else {
return
}
// modify the non-anchor end of the selection
let position =
selectionAnchor == selectedRange.start
? selectedRange.end
: selectedRange.start
guard let newPosition = transform(position, selectionAnchor) else {
return
}
model.selectedRange = TextRange(from: selectionAnchor, to: newPosition)
// scroll to make the new position visible
let caretRect = model.caretRect(for: newPosition)
scrollToVisible(caretRect)
}
private func resetSelection() {
model.selectedRange = nil
selectionAnchor = nil
}
@objc private func share(_ sender: Any?) {
guard let selectedRange = model.selectedRange else {
return
}
let attributedText = model.attributedText(in: selectedRange)
let transferableText = TransferableText(attributedString: attributedText)
let itemProvider = NSItemProvider(object: transferableText)
let sharingPicker = NSSharingServicePicker(items: [itemProvider])
let rect =
model.selectionRects(for: selectedRange)
.last?.rect.integral ?? .zero
sharingPicker.show(relativeTo: rect, of: self, preferredEdge: .maxY)
}
@objc private func copy(_ sender: Any?) {
guard let selectedRange = model.selectedRange else {
return
}
let attributedText = model.attributedText(in: selectedRange)
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
let formatter = Formatter(attributedText)
pasteboard.setString(formatter.plainText(), forType: .string)
pasteboard.setString(formatter.html(), forType: .html)
}
}
@available(macOS 15, *)
extension NSTextInteractionView: NSUserInterfaceValidations {
func validateUserInterfaceItem(_ item: any NSValidatedUserInterfaceItem) -> Bool {
switch item.action {
case #selector(selectAll(_:)):
return model.hasText
case #selector(copy(_:)):
guard let selectedRange = model.selectedRange else {
return false
}
return !selectedRange.isCollapsed
case #selector(moveRightAndModifySelection(_:)),
#selector(moveLeftAndModifySelection(_:)),
#selector(moveUpAndModifySelection(_:)),
#selector(moveDownAndModifySelection(_:)),
#selector(moveWordRightAndModifySelection(_:)),
#selector(moveWordLeftAndModifySelection(_:)),
#selector(moveParagraphBackwardAndModifySelection(_:)),
#selector(moveParagraphForwardAndModifySelection(_:)):
return model.selectedRange != nil
default:
return true
}
}
}
#endif