forked from krzyzanowskim/STTextView
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSTTextView.swift
More file actions
1817 lines (1505 loc) · 69.5 KB
/
STTextView.swift
File metadata and controls
1817 lines (1505 loc) · 69.5 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Created by Marcin Krzyzanowski
// https://github.com/krzyzanowskim/STTextView/blob/main/LICENSE.md
//
//
// NSScrollView
// |---STTextView
// |---gutterView
// |---contentView
// |---STInsertionPointView
// |---selectionView (STSelectionView)
// |---(STLineHighlightView | STSelectionHighlightView)
// |---contentViewportView
// |---STTextLayoutFragmentView
//
//
// The default implementation of the NSView method inputContext manages
// an NSTextInputContext instance automatically if the view subclass conforms
// to the NSTextInputClient protocol.
//
// Although NSTextInput is deprecated, it seem to be check here and there
// whether view conforms to NSTextInput, hence it's here along the NSTextInputClient
import AppKit
import STTextKitPlus
import STTextViewCommon
import AVFoundation
/// A TextKit2 text view without NSTextView baggage
@objc
open class STTextView: NSView, NSTextInput, NSTextContent, STTextViewProtocol {
/// Posted before an object performs any operation that changes characters or formatting attributes.
public static let textWillChangeNotification = NSNotification.Name("NSTextWillChangeNotification")
/// Sent when the text in the receiving control changes.
public static let textDidChangeNotification = NSText.didChangeNotification
/// Sent when the selection range of characters changes.
public static let didChangeSelectionNotification = STTextLayoutManager.didChangeSelectionNotification
/// Installed plugins. events value is available after plugin is setup
var plugins: [Plugin] = []
/// A Boolean value that controls whether the text view allows the user to edit text.
@Invalidating(.insertionPoint, .cursorRects)
@objc
open dynamic var isEditable = true {
didSet {
if isEditable == true {
isSelectable = true
}
}
}
/// A Boolean value that controls whether the text views allows the user to select text.
@Invalidating(.insertionPoint, .cursorRects)
@objc
open dynamic var isSelectable = true {
didSet {
if isSelectable == false {
isEditable = false
}
}
}
@objc
public let isRichText = true
@objc
public let isFieldEditor = false
@objc
public let importsGraphics = false
/// A Boolean value that determines whether the text view should draw its insertion point.
open var shouldDrawInsertionPoint: Bool {
if !isFirstResponder {
return false
}
if !isEditable {
return false
}
if let window, window.isKeyWindow, window.firstResponder == self {
return true
}
return false
}
@Invalidating(.insertionPoint, .cursorRects)
var isFirstResponder = false
/// The color of the insertion point.
@Invalidating(.display, .insertionPoint)
@objc
open dynamic var insertionPointColor: NSColor = .defaultTextInsertionPoint
/// The font of the text. Default font.
///
/// Assigning a new value to this property causes the new font to be applied to the entire contents of the text view.
/// If you want to apply the font to only a portion of the text, you must create a new attributed string with the desired style information and assign it
@MainActor
@objc
public var font: NSFont {
get {
_defaultTypingAttributes[.font] as! NSFont
}
set {
_defaultTypingAttributes[.font] = newValue
// apply to the document
if !textLayoutManager.documentRange.isEmpty {
addAttributes([.font: newValue], range: textLayoutManager.documentRange)
needsLayout = true
needsDisplay = true
}
updateTypingAttributes()
}
}
/// The text color of the text view.
///
/// Default text color.
@MainActor
@objc
public var textColor: NSColor {
get {
_defaultTypingAttributes[.foregroundColor] as! NSColor
}
set {
_defaultTypingAttributes[.foregroundColor] = newValue
// apply to the document
if !textLayoutManager.documentRange.isEmpty {
addAttributes([.foregroundColor: newValue], range: textLayoutManager.documentRange)
needsLayout = true
needsDisplay = true
}
updateTypingAttributes()
}
}
/// Default paragraph style.
@MainActor
@objc
public var defaultParagraphStyle: NSParagraphStyle {
set {
_defaultTypingAttributes[.paragraphStyle] = newValue
}
get {
_defaultTypingAttributes[.paragraphStyle] as? NSParagraphStyle ?? NSParagraphStyle.default
}
}
/// Default typing attributes used in place of missing attributes of font, color and paragraph
var _defaultTypingAttributes: [NSAttributedString.Key: Any] = [
.paragraphStyle: NSParagraphStyle.default,
.font: NSFont.preferredFont(forTextStyle: .body),
.foregroundColor: NSColor.textColor
]
/// The attributes to apply to new text that the user enters.
///
/// This dictionary contains the attribute keys (and corresponding values) to apply to newly typed text.
/// When the text view’s selection changes, the contents of the dictionary are reset automatically.
@objc
public var typingAttributes: [NSAttributedString.Key: Any] {
get {
_typingAttributes.merging(_defaultTypingAttributes) { (current, _) in current }
}
set {
_typingAttributes = newValue.filter {
_allowedTypingAttributes.contains($0.key)
}
needsDisplay = true
}
}
private var _typingAttributes: [NSAttributedString.Key: Any]
private var _allowedTypingAttributes: [NSAttributedString.Key] = [
.paragraphStyle,
.font,
.foregroundColor,
.baselineOffset,
.kern,
.ligature,
.shadow,
.strikethroughColor,
.strikethroughStyle,
.superscript,
.languageIdentifier,
.tracking,
.writingDirection,
.textEffect,
.accessibilityFont,
.accessibilityForegroundColor,
.backgroundColor,
.underlineColor,
.underlineStyle,
.accessibilityUnderline,
.accessibilityUnderlineColor
]
func updateTypingAttributes(at location: NSTextLocation? = nil) {
if let location {
self.typingAttributes = typingAttributes(at: location)
} else {
// TODO: doesn't work work correctly (at all) for multiple insertion points where each has different typing attribute
if let insertionPointSelection = textLayoutManager.insertionPointSelections.first,
let startLocation = insertionPointSelection.textRanges.first?.location {
self.typingAttributes = typingAttributes(at: startLocation)
}
}
}
/// Resets typing attributes to default values.
open func resetTypingAttributes() {
_typingAttributes = [:]
}
func typingAttributes(at startLocation: NSTextLocation) -> [NSAttributedString.Key: Any] {
if textLayoutManager.documentRange.isEmpty {
return _defaultTypingAttributes
}
var typingAttrs: [NSAttributedString.Key: Any] = [:]
// The attribute is derived from the previous (upstream) location,
// except for the beginning of the document where it from whatever is at location 0
let options: NSTextContentManager.EnumerationOptions = startLocation == textLayoutManager.documentRange.location ? [] : [.reverse]
let offsetDiff = startLocation == textLayoutManager.documentRange.location ? 0 : -1
textContentManager.enumerateTextElements(from: startLocation, options: options) { textElement in
if let attributedTextElement = textElement as? STAttributedTextElement,
let elementRange = textElement.elementRange,
let textContentManager = textElement.textContentManager {
let offset = textContentManager.offset(from: elementRange.location, to: startLocation)
assert(offset != NSNotFound, "Unexpected location")
typingAttrs = attributedTextElement.attributedString.attributes(at: offset + offsetDiff, effectiveRange: nil)
}
return false
}
// fill in with missing typing attributes if needed
return typingAttrs.merging(_defaultTypingAttributes, uniquingKeysWith: { current, _ in current })
}
// line height based on current typing font and current typing paragraph
// Not used since extraLineFragmentAttributes workaround fixed most of measurements
@available(*, deprecated, message: "Use STTextLayoutFragment metrics")
var typingLineHeight: CGFloat {
let font = typingAttributes[.font] as? NSFont ?? _defaultTypingAttributes[.font] as! NSFont
let paragraphStyle = typingAttributes[.paragraphStyle] as? NSParagraphStyle ?? self._defaultTypingAttributes[.paragraphStyle] as! NSParagraphStyle
return calculateDefaultLineHeight(for: font) * paragraphStyle.stLineHeightMultiple
}
/// The characters of the receiver’s text.
///
/// For performance reasons, this value is the current backing store of the text object.
/// If you want to maintain a snapshot of this as you manipulate the text storage, you should make a copy of the appropriate substring.
@objc
open var text: String? {
set {
let prevLocation = textLayoutManager.insertionPointLocations.first
resetTypingAttributes()
setString(newValue)
if let prevLocation {
// restore selection location
setSelectedTextRange(NSTextRange(location: prevLocation), updateLayout: true)
} else {
// or try to set at the begining of the document
setSelectedTextRange(NSTextRange(location: textContentManager.documentRange.location), updateLayout: true)
}
}
get {
textContentManager.attributedString(in: nil)?.string ?? ""
}
}
/// The styled text that the text view displays.
///
/// Assigning a new value to this property also replaces the value of the `text` property with the same string data, albeit without any formatting information. In addition, the `font`, `textColor`, and `textAlignment` properties are updated to reflect the typing attributes of the text view.
@objc
open var attributedText: NSAttributedString? {
set {
let prevLocation = textLayoutManager.insertionPointLocations.first
resetTypingAttributes()
setString(newValue)
if let prevLocation {
// restore selection location
setSelectedTextRange(NSTextRange(location: prevLocation), updateLayout: true)
} else {
// or try to set at the begining of the document
setSelectedTextRange(NSTextRange(location: textContentManager.documentRange.location), updateLayout: true)
}
}
get {
textContentManager.attributedString(in: nil)
}
}
private var _isHorizontallyResizable = true
/// A Boolean that controls whether the receiver changes its width to fit the width of its text.
///
/// When `true` (default), text does not wrap and the view expands horizontally.
/// When `false`, text wraps at the view width.
@objc
public var isHorizontallyResizable: Bool {
set {
if _isHorizontallyResizable != newValue {
_isHorizontallyResizable = newValue
updateTextContainerSize()
needsLayout = true
}
}
get {
_isHorizontallyResizable
}
}
/// NSTextView compatibility. Equivalent to `!isHorizontallyResizable`.
@available(*, deprecated, renamed: "isHorizontallyResizable")
@objc
public var widthTracksTextView: Bool {
set { isHorizontallyResizable = !newValue }
get { !isHorizontallyResizable }
}
private var _isVerticallyResizable = true
/// A Boolean that controls whether the receiver changes its height to fit the height of its text.
/// When `true` (default), the view expands vertically to fit content.
/// When `false`, content is clipped at the view height.
@objc
public var isVerticallyResizable: Bool {
set {
if _isVerticallyResizable != newValue {
_isVerticallyResizable = newValue
updateTextContainerSize()
needsLayout = true
}
}
get {
_isVerticallyResizable
}
}
/// NSTextView compatibility. Equivalent to `!isVerticallyResizable`.
@available(*, deprecated, renamed: "isVerticallyResizable")
@objc
public var heightTracksTextView: Bool {
set { isVerticallyResizable = !newValue }
get { !isVerticallyResizable }
}
/// A Boolean that controls whether the text view highlights the currently selected line.
@MainActor @Invalidating(.layoutViewport)
@objc
open dynamic var highlightSelectedLine = false
/// Enable to show line numbers in the gutter.
@MainActor @Invalidating(.layout)
open var showsLineNumbers = false {
didSet {
isGutterVisible = showsLineNumbers
}
}
/// Gutter view
public var gutterView: STGutterView?
/// The highlight color of the selected line.
///
/// Note: Needs ``highlightSelectedLine`` to be set to `true`
@Invalidating(.display)
@objc
open dynamic var selectedLineHighlightColor = NSColor.selectedTextBackgroundColor.withAlphaComponent(0.25)
/// The text view's background color
@Invalidating(.display)
@objc
open dynamic var backgroundColor: NSColor? = nil {
didSet {
layer?.backgroundColor = backgroundColor?.cgColor
gutterView?.backgroundColor = backgroundColor
}
}
/// A Boolean value that indicates whether the receiver allows its background color to change.
@objc
open dynamic var allowsDocumentBackgroundColorChange = true
/// An action method used to set the background color.
@objc open func changeDocumentBackgroundColor(_ sender: Any?) {
guard allowsDocumentBackgroundColorChange, let color = sender as? NSColor else {
return
}
backgroundColor = color
}
/// The semantic meaning for a text input area.
open var contentType: NSTextContentType?
/// A Boolean value that indicates whether the receiver allows undo.
///
/// `true` if the receiver allows undo, otherwise `false`. Default `true`.
@objc
open dynamic var allowsUndo: Bool
var _undoManager: UndoManager?
var _yankingManager = YankingManager()
var markedText: STMarkedText?
/// The attributes used to draw marked text.
///
/// Text color, background color, and underline are the only supported attributes for marked text.
@objc
open var markedTextAttributes: [NSAttributedString.Key: Any] = [.underlineStyle: NSUnderlineStyle.single.rawValue]
/// A flag
var processingKeyEvent = false
/// The delegate for all text views sharing the same layout manager.
@available(*, deprecated, renamed: "textDelegate")
public weak var delegate: (any STTextViewDelegate)? {
set {
textDelegate = newValue
}
get {
textDelegate
}
}
/// The delegate for all text views sharing the same layout manager.
public weak var textDelegate: (any STTextViewDelegate)? {
set {
delegateProxy.source = newValue
}
get {
delegateProxy.source
}
}
/// Proxy for delegate calls
let delegateProxy = STTextViewDelegateProxy(source: nil)
/// The manager that lays out text for the text view's text container.
@objc
open dynamic var textLayoutManager: NSTextLayoutManager {
willSet {
textContentManager.primaryTextLayoutManager = nil
textContentManager.removeTextLayoutManager(newValue)
}
didSet {
textContentManager.addTextLayoutManager(textLayoutManager)
textContentManager.primaryTextLayoutManager = textLayoutManager
setupTextLayoutManager(textLayoutManager)
self.text = text
}
}
@available(*, deprecated, renamed: "textContentManager")
open var textContentStorage: NSTextContentStorage {
textContentManager as! NSTextContentStorage
}
/// The text view's text storage object.
@objc
open dynamic var textContentManager: NSTextContentManager {
willSet {
textContentManager.primaryTextLayoutManager = nil
}
didSet {
textContentManager.addTextLayoutManager(textLayoutManager)
textContentManager.primaryTextLayoutManager = textLayoutManager
self.text = text
}
}
/// The text view's text container
public var textContainer: NSTextContainer {
get {
textLayoutManager.textContainer!
}
set {
textLayoutManager.textContainer = newValue
}
}
/// Content view. Layout fragments content.
let contentView: STContentView
let contentViewportView: STContentViewportView
/// Content frame. Layout fragments content frame.
@_spi(Plugins)
public var contentFrame: CGRect {
contentView.frame
}
/// Selection highlight content view.
let selectionView: STSelectionView
var fragmentViewMap: NSMapTable<NSTextLayoutFragment, STTextLayoutFragmentView>
var lastUsedFragmentViews: Set<STTextLayoutFragmentView> = []
private var _usageBoundsForTextContainerObserver: NSKeyValueObservation?
lazy var _speechSynthesizer = AVSpeechSynthesizer()
var _speechSynthesizerIsSpeaking = false
private lazy var _defaultTextContainerSize: CGSize = NSTextContainer().size
var _completionWindowController: STCompletionWindowController?
var completionWindowController: STCompletionWindowController? {
if _completionWindowController == nil {
let completionViewController = delegateProxy.textViewCompletionViewController(self)
let completionWindowController = STCompletionWindowController(completionViewController)
_completionWindowController = completionWindowController
return completionWindowController
}
return _completionWindowController
}
/// Completion window is presented currently
open var isCompletionActive: Bool {
completionWindowController?.isVisible == true
}
/// Cancel completion task on selection change automatically. Default `true`.
///
/// Automatically call ``cancelComplete(_:)`` when `true`.
open var shouldDimissCompletionOnSelectionChange = true
var _completionTask: Task<Void, any Error>?
/// Search-and-replace find interface inside a view.
open private(set) var textFinder: NSTextFinder
/// NSTextFinderClient
let textFinderClient: STTextFinderClient
let textFinderBarContainer: STTextFinderBarContainer
var textCheckingController: NSTextCheckingController!
/// A Boolean value that indicates whether the receiver has continuous spell checking enabled.
///
/// true if the object has continuous spell-checking enabled; otherwise, false.
@objc
public var isContinuousSpellCheckingEnabled = false
/// Enables and disables grammar checking.
///
/// If true, grammar checking is enabled; if false, it is disabled.
@objc
public var isGrammarCheckingEnabled = false
/// A Boolean value that indicates whether the text view supplies autocompletion suggestions as the user types.
@objc
public lazy var isAutomaticTextCompletionEnabled: Bool = NSSpellChecker.isAutomaticTextCompletionEnabled
/// A Boolean value that indicates whether automatic spelling correction is enabled.
@objc
public lazy var isAutomaticSpellingCorrectionEnabled: Bool = NSSpellChecker.isAutomaticSpellingCorrectionEnabled
/// A Boolean value that indicates whether automatic text replacement is enabled.
@objc
public lazy var isAutomaticTextReplacementEnabled = NSSpellChecker.isAutomaticTextReplacementEnabled
/// A Boolean value that enables and disables automatic quotation mark substitution.
@objc
public lazy var isAutomaticQuoteSubstitutionEnabled = NSSpellChecker.isAutomaticQuoteSubstitutionEnabled
/// A Boolean value that indicates whether to substitute visible glyphs for whitespace and other typically invisible characters.
@Invalidating(.layoutViewport, .display)
public var showsInvisibleCharacters = false {
willSet {
textLayoutManager.invalidateLayout(for: textLayoutManager.textViewportLayoutController.viewportRange ?? textLayoutManager.documentRange)
}
}
/// A Boolean value that indicates whether incremental searching is enabled.
///
/// See `NSTextFinder` for information about the find bar.
///
/// The default value is false.
public var isIncrementalSearchingEnabled: Bool {
get {
textFinder.isIncrementalSearchingEnabled
}
set {
textFinder.isIncrementalSearchingEnabled = newValue
}
}
/// A Boolean value that controls whether the text views sharing the receiver’s layout manager use the Font panel and Font menu.
open var usesFontPanel = true
/// A one-shot action executed after the next layout viewport pass completes, then cleared.
var postLayoutAction: (() -> Void)? {
didSet {
if postLayoutAction != nil {
needsLayout = true
}
}
}
private var liveResizeLayoutSuppression = false
private var inLayout = false
private var needsRelayout = false
private var shouldUpdateLayout: Bool {
if liveResizeLayoutSuppression {
let controller = textLayoutManager.textViewportLayoutController
let newBounds = viewportBounds(for: controller)
let currentViewportBounds = controller.viewportBounds
let verticallyContained =
newBounds.minY >= currentViewportBounds.minY &&
newBounds.maxY <= currentViewportBounds.maxY
return !verticallyContained
}
return true
}
override open var isFlipped: Bool {
true
}
/// Generates and returns a scroll view with a STTextView set as its document view.
open class func scrollableTextView(frame: NSRect = .zero) -> NSScrollView {
let scrollView = NSScrollView(frame: frame)
let textView = Self()
scrollView.wantsLayer = true
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = true
scrollView.drawsBackground = false
scrollView.documentView = textView
return scrollView
}
var scrollView: NSScrollView? {
guard let result = enclosingScrollView, result.documentView == self else {
return nil
}
return result
}
/// A dragging selection anchor
///
/// FB11898356 - Something if wrong with textSelectionsInteractingAtPoint
/// it expects that the dragging operation does not change anchor selections
/// significantly. Specifically it does not play well if anchor and current
/// location is too close to each other, therefore `mouseDraggingSelectionAnchors`
/// keep the anchors unchanged while dragging.
var mouseDraggingSelectionAnchors: [NSTextSelection]?
var draggingSession: NSDraggingSession?
var originalDragSelections: [NSTextRange]?
override open class var defaultMenu: NSMenu? {
// evaluated once, and cached
let menu = super.defaultMenu ?? NSMenu()
let pasteAsPlainText = NSMenuItem(title: NSLocalizedString("Paste and Match Style", comment: ""), action: #selector(pasteAsPlainText(_:)), keyEquivalent: "V")
pasteAsPlainText.keyEquivalentModifierMask = [.option, .command, .shift]
menu.items = [
NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cut(_:)), keyEquivalent: "x"),
NSMenuItem(title: NSLocalizedString("Copy", comment: ""), action: #selector(copy(_:)), keyEquivalent: "c"),
NSMenuItem(title: NSLocalizedString("Paste", comment: ""), action: #selector(paste(_:)), keyEquivalent: "v"),
pasteAsPlainText,
NSMenuItem.separator(),
NSMenuItem(title: NSLocalizedString("Select All", comment: ""), action: #selector(selectAll(_:)), keyEquivalent: "a"),
]
return menu
}
/// Initializes a text view.
/// - Parameter frameRect: The frame rectangle of the text view.
override public init(frame frameRect: NSRect) {
fragmentViewMap = .weakToWeakObjects()
textContentManager = STTextContentStorage()
textLayoutManager = STTextLayoutManager()
textLayoutManager.textContainer = STTextContainer()
textContentManager.addTextLayoutManager(textLayoutManager)
textContentManager.primaryTextLayoutManager = textLayoutManager
contentView = STContentView()
if ProcessInfo().environment["ST_LAYOUT_DEBUG"] == "YES" {
contentView.layer?.borderColor = NSColor.magenta.cgColor
contentView.layer?.borderWidth = 4
}
contentViewportView = STContentViewportView()
contentViewportView.autoresizingMask = [.width, .height]
selectionView = STSelectionView()
selectionView.autoresizingMask = [.width, .height]
allowsUndo = true
_undoManager = CoalescingUndoManager()
textFinderClient = STTextFinderClient()
textFinderBarContainer = STTextFinderBarContainer()
textFinder = NSTextFinder()
textFinder.client = textFinderClient
_typingAttributes = [:]
super.init(frame: frameRect)
_speechSynthesizer.delegate = self
textFinderBarContainer.client = self
textFinder.findBarContainer = textFinderBarContainer
textFinderClient.textView = self
textCheckingController = NSTextCheckingController(client: self)
postsBoundsChangedNotifications = true
postsFrameChangedNotifications = true
wantsLayer = true
autoresizingMask = [.width, .height]
addSubview(contentView)
contentView.addSubview(selectionView)
contentView.addSubview(contentViewportView)
do {
let recognizer = DragSelectedTextGestureRecognizer(target: self, action: #selector(_dragSelectedTextGestureRecognizer(gestureRecognizer:)))
recognizer.minimumPressDuration = NSEvent.doubleClickInterval / 3
recognizer.isEnabled = isSelectable
addGestureRecognizer(recognizer)
}
setupTextLayoutManager(textLayoutManager)
setSelectedTextRange(NSTextRange(location: textLayoutManager.documentRange.location), updateLayout: false)
registerForDraggedTypes(readablePasteboardTypes)
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
guard !plugins.isEmpty else { return }
Task { @MainActor [plugins] in
for plugin in plugins {
plugin.instance.tearDown()
}
}
}
private var didChangeSelectionNotificationObserver: NSObjectProtocol?
private func setupTextLayoutManager(_ textLayoutManager: NSTextLayoutManager) {
textLayoutManager.delegate = self
textLayoutManager.textViewportLayoutController.delegate = self
// Forward didChangeSelectionNotification from STTextLayoutManager
if let didChangeSelectionNotificationObserver {
NotificationCenter.default.removeObserver(didChangeSelectionNotificationObserver)
}
didChangeSelectionNotificationObserver = NotificationCenter.default.addObserver(forName: STTextLayoutManager.didChangeSelectionNotification, object: textLayoutManager, queue: .main) { [weak self] notification in
guard let self else { return }
_yankingManager.selectionChanged()
let textViewNotification = Notification(name: Self.didChangeSelectionNotification, object: self, userInfo: notification.userInfo)
NotificationCenter.default.post(textViewNotification)
self.delegateProxy.textViewDidChangeSelection(textViewNotification)
NSAccessibility.post(element: self, notification: .selectedTextChanged)
// Cancel completinon on selection change
if self.shouldDimissCompletionOnSelectionChange {
if NSApp.currentEvent == nil ||
(NSApp.currentEvent?.type != .keyDown && NSApp.currentEvent?.type != .keyUp) ||
NSApp.currentEvent?.characters == nil ||
!(NSApp.currentEvent?.characters?.contains(where: \.isLetter) ?? false) {
self.cancelComplete(textViewNotification.object)
}
}
// textCheckingController.didChangeSelectedRange()
}
_usageBoundsForTextContainerObserver = nil
_usageBoundsForTextContainerObserver = textLayoutManager.observe(\.usageBoundsForTextContainer, options: [.initial, .new]) { [weak self] _, _ in
// FB13291926: Notification no longer works. Fixed again in macOS 15.6
self?.needsUpdateConstraints = true
}
}
override open func resetCursorRects() {
super.resetCursorRects()
let contentViewVisibleRect = contentView.convert(contentView.visibleRect, to: self)
if isSelectable, contentViewVisibleRect != .zero {
addCursorRect(contentViewVisibleRect, cursor: .iBeam)
// This iteration may be performance intensive. I think it can be debounced without
// affecting the correctness
if let viewportRange = textLayoutManager.textViewportLayoutController.viewportRange,
let viewportAttributedString = textContentManager.attributedString(in: viewportRange) {
viewportAttributedString.enumerateAttribute(.link, in: viewportAttributedString.range, options: .longestEffectiveRangeNotRequired) { attributeValue, attributeRange, stop in
guard attributeValue != nil else {
return
}
if let startLocation = textLayoutManager.location(viewportRange.location, offsetBy: attributeRange.location),
let endLocation = textLayoutManager.location(startLocation, offsetBy: attributeRange.length),
let linkTextRange = NSTextRange(location: startLocation, end: endLocation),
let linkTypographicBounds = textLayoutManager.typographicBounds(in: linkTextRange) {
addCursorRect(contentView.convert(linkTypographicBounds, to: self), cursor: .pointingHand)
} else {
stop.pointee = true
}
}
viewportAttributedString.enumerateAttribute(.cursor, in: viewportAttributedString.range, options: .longestEffectiveRangeNotRequired) { attributeValue, attributeRange, stop in
guard let cursorValue = attributeValue as? NSCursor else {
return
}
if let startLocation = textLayoutManager.location(viewportRange.location, offsetBy: attributeRange.location),
let endLocation = textLayoutManager.location(startLocation, offsetBy: attributeRange.length),
let linkTextRange = NSTextRange(location: startLocation, end: endLocation),
let linkTypographicBounds = textLayoutManager.typographicBounds(in: linkTextRange) {
addCursorRect(contentView.convert(linkTypographicBounds, to: self), cursor: cursorValue)
} else {
stop.pointee = true
}
}
}
}
}
override open func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance()
effectiveAppearance.performAsCurrentDrawingAppearance { [weak self] in
guard let self else { return }
self.backgroundColor = self.backgroundColor
self.updateSelectedRangeHighlight()
self.updateSelectedLineHighlight()
self.layoutGutter()
}
}
override open func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
if let scrollView {
NotificationCenter.default.addObserver(self, selector: #selector(didLiveScrollNotification(_:)), name: NSScrollView.didLiveScrollNotification, object: scrollView)
}
}
override open func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if self.window != nil {
// setup registerd plugins
setupPlugins()
}
}
override open func hitTest(_ point: NSPoint) -> NSView? {
let result = super.hitTest(point)
// click-through `contentView`, `contentViewportView`, `selectionView` subviews
// that makes first responder properly redirect to main view
// and ignore utility subviews that should remain transparent
// for interaction.
if let view = result, view != self,
(view.isDescendant(of: contentView) || view.isDescendant(of: contentViewportView) || view.isDescendant(of: selectionView)) {
// Check if this is an attachment view - allow it to handle its own events
if isTextAttachmentView(view) {
return view
}
// For non-attachment views, proxy to text view
return self
}
return result
}
private func isTextAttachmentView(_ view: NSView) -> Bool {
// Walk up the view hierarchy to find if this view is part of an attachment
var currentView: NSView? = view
while let parentView = currentView?.superview {
if let fragmentView = parentView as? STTextLayoutFragmentView {
// Check if view is an attachment view
for provider in fragmentView.layoutFragment.textAttachmentViewProviders {
if let attachmentView = provider.view {
if attachmentView == view || view.isDescendant(of: attachmentView) {
return true
}
}
}
break
}
currentView = parentView
}
return false
}
override open var canBecomeKeyView: Bool {
super.canBecomeKeyView && acceptsFirstResponder && !isHiddenOrHasHiddenAncestor
}
override open var needsPanelToBecomeKey: Bool {
isSelectable || isEditable
}
override open var acceptsFirstResponder: Bool {
isSelectable
}
override open func becomeFirstResponder() -> Bool {
if isEditable {
dispatchPrecondition(condition: .onQueue(.main))
NotificationCenter.default.post(name: NSText.didBeginEditingNotification, object: self, userInfo: nil)
}
let result = super.becomeFirstResponder()
isFirstResponder = true
if isSelectable {
updateSelectedRangeHighlight()
updateSelectedLineHighlight()
}
return result
}
override open func resignFirstResponder() -> Bool {
if isEditable {
NotificationCenter.default.post(name: NSText.didEndEditingNotification, object: self, userInfo: [NSText.didEndEditingNotification: NSTextMovement.other.rawValue])
}
let result = super.resignFirstResponder()
isFirstResponder = false
if isSelectable {
updateSelectedRangeHighlight()
updateSelectedLineHighlight()
}
return result
}
/// Resigns the window’s key window status.
///
/// Swift documentation to NSWindow.resignKey() is wrong about selector sent to the first responder.
/// It uses resignKeyWindow(), not resignKey() selector.
///
/// Never invoke this method directly.
@objc private func resignKeyWindow() {
updateInsertionPointStateAndRestartTimer()
}
@objc private func becomeKeyWindow() {
updateInsertionPointStateAndRestartTimer()
}
override open var intrinsicContentSize: NSSize {
// usageBoundsForTextContainer already includes lineFragmentPadding via STTextLayoutManager workaround
let textSize = textLayoutManager.usageBoundsForTextContainer.size
let gutterWidth = gutterView?.frame.width ?? 0
return NSSize(
width: textSize.width + gutterWidth,
height: textSize.height
)
}
override open func updateConstraints() {
updateTextContainerSize()
super.updateConstraints()
}
override open class var isCompatibleWithResponsiveScrolling: Bool {
false
}