-
Notifications
You must be signed in to change notification settings - Fork 83
/
RichTextView.swift
966 lines (806 loc) · 39.6 KB
/
RichTextView.swift
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
//
// RichTextView.swift
// Proton
//
// Created by Rajdeep Kwatra on 4/1/20.
// Copyright © 2020 Rajdeep Kwatra. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import ProtonCore
class RichTextView: AutogrowingTextView {
/// Equivalent, strongly-typed alternative to `textStorage`
private let richTextStorage = PRTextStorage()
private let _undoManager: UndoManager?
static let defaultListLineFormatting = LineFormatting(indentation: 25, spacingBefore: 0)
weak var richTextViewDelegate: RichTextViewDelegate?
weak var richTextViewListDelegate: RichTextViewListDelegate?
weak var richTextScrollViewDelegate: UIScrollViewDelegate?
weak var lineNumberProvider: LineNumberProvider?
private var delegateOverrides = [GestureRecognizerDelegateOverride]()
private(set) var ignoreSelectedRangeChangeCallback = false
private var _canBecomeFirstResponder = true
override var canBecomeFirstResponder: Bool {
return _canBecomeFirstResponder
}
func disableFirstResponder() {
_canBecomeFirstResponder = false
}
func enableFirstResponder() {
_canBecomeFirstResponder = true
}
var preserveBlockAttachmentNewline: PreserveBlockAttachmentNewline = .none {
didSet {
richTextStorage.preserveNewlineBeforeBlock = false
richTextStorage.preserveNewlineAfterBlock = false
if preserveBlockAttachmentNewline.contains(.before) {
richTextStorage.preserveNewlineBeforeBlock = true
}
if preserveBlockAttachmentNewline.contains(.after) {
richTextStorage.preserveNewlineAfterBlock = true
}
}
}
var showsInvisibleCharacters = false {
didSet {
layoutManager.invalidateGlyphs(forCharacterRange: richTextStorage.fullRange, changeInLength: 0, actualCharacterRange: nil)
setNeedsDisplay()
}
}
weak var defaultTextFormattingProvider: DefaultTextFormattingProviding?
{
get { richTextStorage.defaultTextFormattingProvider }
set {
richTextStorage.defaultTextFormattingProvider = newValue
// typingAttributes[.font] = defaultTypingAttributes[.font]
// typingAttributes[.paragraphStyle] = defaultTypingAttributes[.paragraphStyle]
// typingAttributes[.foregroundColor] = defaultTypingAttributes[.foregroundColor]
}
}
private lazy var placeholderLabel: UILabel = {
let placeholderLabel = UILabel()
placeholderLabel.accessibilityIdentifier = "RichTextView.placeholderLabel"
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
placeholderLabel.numberOfLines = 0
placeholderLabel.lineBreakMode = .byTruncatingTail
return placeholderLabel
}()
var placeholderText: NSAttributedString? {
didSet {
placeholderLabel.attributedText = placeholderText
updatePlaceholderVisibility()
}
}
var editorView: EditorView? {
return superview as? EditorView
}
var defaultTypingAttributes: RichTextAttributes {
return [
.font: defaultTextFormattingProvider?.font ?? richTextStorage.defaultFont,
.paragraphStyle: defaultTextFormattingProvider?.paragraphStyle ?? richTextStorage.defaultParagraphStyle,
.foregroundColor: defaultTextFormattingProvider?.textColor ?? richTextStorage.defaultTextColor
]
}
var defaultFont: UIFont { richTextStorage.defaultFont }
var defaultTextColor: UIColor { richTextStorage.defaultTextColor }
var defaultBackgroundColor: UIColor {
return .systemBackground
}
override var attributedText: NSAttributedString! {
willSet {
// Remove all attachment subviews else we may run into PRTextStorage "in middle of editing" crash
subviews.filter { $0 is AttachmentContentView }.forEach { $0.removeFromSuperview() }
}
}
var lineNumberFormatting = LineNumberFormatting.default {
didSet {
let gutterOffset = lineNumberFormatting.gutter.width + lineNumberFormatting.gutter.lineWidth
let adjustedLeftInset = isLineNumbersEnabled ? (gutterOffset + textContainerInset.left - oldValue.gutter.width): nil
textContainerInset = UIEdgeInsets(
top: textContainerInset.top,
left: adjustedLeftInset ?? textContainerInset.left,
bottom: textContainerInset.bottom,
right: textContainerInset.right
)
setNeedsDisplay()
}
}
var isLineNumbersEnabled = false {
didSet {
let gutterOffset = lineNumberFormatting.gutter.width + lineNumberFormatting.gutter.lineWidth
let adjustedLeftInset: CGFloat
switch (oldValue, isLineNumbersEnabled) {
case (false, true):
adjustedLeftInset = gutterOffset + textContainerInset.left
case (true, false):
adjustedLeftInset = textContainerInset.left - gutterOffset
default:
adjustedLeftInset = textContainerInset.left
}
textContainerInset = UIEdgeInsets(
top: textContainerInset.top,
left: adjustedLeftInset,
bottom: textContainerInset.bottom,
right: textContainerInset.right
)
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
guard isLineNumbersEnabled,
let currentCGContext = UIGraphicsGetCurrentContext() else {
super.draw(rect)
return
}
let height = max(contentSize.height, bounds.height)
let rect = CGRect(x: 0, y: 0, width: lineNumberFormatting.gutter.width, height: height)
let rectanglePath = UIBezierPath(rect: rect)
currentCGContext.saveGState()
currentCGContext.addPath(rectanglePath.cgPath)
if let lineColor = lineNumberFormatting.gutter.lineColor {
currentCGContext.setStrokeColor(lineColor.cgColor)
currentCGContext.setLineWidth(lineNumberFormatting.gutter.lineWidth)
currentCGContext.drawPath(using: .stroke)
}
currentCGContext.setFillColor(lineNumberFormatting.gutter.backgroundColor.cgColor)
currentCGContext.fill(rect)
// Draw line number if textView is empty
if let layoutManager = layoutManager as? LayoutManager,
attributedText.length == 0 {
let lineNumberToDisplay = lineNumberString(for: 1) ?? "1"
let width = lineNumberFormatting.gutter.width
let height = defaultFont.lineHeight
layoutManager.drawLineNumber(lineNumber: lineNumberToDisplay, rect: CGRect(origin: .zero, size: CGSize(width: width, height: height)), lineNumberFormatting: lineNumberFormatting, currentCGContext: currentCGContext)
}
currentCGContext.restoreGState()
super.draw(rect)
}
func drawDefaultLineNumberIfRequired() {
guard isLineNumbersEnabled else { return }
draw(CGRect(origin: .zero, size: contentSize))
}
override func becomeFirstResponder() -> Bool {
let didBecomeFirstResponder = super.becomeFirstResponder()
if didBecomeFirstResponder {
context?.selectedTextView = self
context?.activeTextView = self
}
return didBecomeFirstResponder
}
func updateSelectedRangeIgnoringCallback(_ selectedRange: NSRange) {
ignoreSelectedRangeChangeCallback = true
self.selectedRange = selectedRange
ignoreSelectedRangeChangeCallback = false
}
override var selectedTextRange: UITextRange? {
didSet{
let old = oldValue?.toNSRange(in: self)
let new = selectedTextRange?.toNSRange(in: self)
if let range = adjustedTextBlockRangeOnSelectionChange(oldRange: old, newRange: new) {
selectedRange = range
}
richTextViewDelegate?.richTextView(self, selectedRangeChangedFrom: old, to: selectedTextRange?.toNSRange(in: self))
}
}
override var selectedRange: NSRange {
didSet{
if let range = adjustedTextBlockRangeOnSelectionChange(oldRange: oldValue, newRange: selectedRange) {
selectedRange = range
richTextViewDelegate?.richTextView(self, selectedRangeChangedFrom: oldValue, to: selectedRange)
}
}
}
override var contentInset: UIEdgeInsets {
didSet {
updatePlaceholderVisibility()
}
}
override var textContainerInset: UIEdgeInsets {
didSet {
updatePlaceholderVisibility()
}
}
var nestedTextViews: [RichTextView] {
getNestedEditors(for: self)
}
override var isScrollEnabled: Bool {
didSet {
guard isScrollEnabled != oldValue else { return }
richTextViewDelegate?.richTextView(self, didChangeScrollEnabled: isScrollEnabled)
}
}
override public func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
guard let key = presses.first?.key else {
super.pressesBegan(presses, with: event)
return
}
var handled: Bool = false
guard let editorKey = EditorKey(key) else { return }
richTextViewDelegate?.richTextView(self, shouldHandle: editorKey, modifierFlags: key.modifierFlags, at: self.selectedRange, handled: &handled)
if handled == false {
super.pressesBegan(presses, with: event)
}
}
private func getNestedEditors(for containerView: UIView) -> [RichTextView] {
var textViews = [RichTextView]()
for view in containerView.subviews {
if let textView = view as? RichTextView {
textViews.append(textView)
}
textViews.append(contentsOf: getNestedEditors(for: view))
}
return textViews
}
private func adjustedTextBlockRangeOnSelectionChange(oldRange: NSRange?, newRange: NSRange?) -> NSRange? {
guard let old = oldRange,
let new = newRange,
old != new
else { return nil }
let isReverseTraversal = (new.location < old.location) || (new.endLocation < old.endLocation)
guard new.length > 0 else {
if let textBlockRange = attributedText.rangeOf(attribute: .textBlock, at: new.location),
textBlockRange.location != new.location {
let location = isReverseTraversal ? textBlockRange.location : textBlockRange.endLocation
return NSRange(location: location, length: 0)
}
return nil
}
let isLocationChanged = new.location != old.location
let location = isLocationChanged ? new.location : max(0, new.endLocation - 1)
guard let textBlockRange = attributedText.rangeOf(attribute: .textBlock, at: location),
textBlockRange.contains(location)
else { return nil }
// return textblock range if new range is entirely contained within textblock range
if textBlockRange.intersection(new) == new {
return textBlockRange
}
if isReverseTraversal {
return adjustedTextBlockRangeReverse(new: new, old: old, textBlockRange: textBlockRange)
} else {
return adjustedTextBlockRangeForward(new: new, old: old, textBlockRange: textBlockRange)
}
}
private func adjustedTextBlockRangeReverse(new: NSRange, old: NSRange, textBlockRange: NSRange) -> NSRange {
let range: NSRange
if textBlockRange.union(new) == textBlockRange, new.endLocation == old.endLocation, textBlockRange.contains(new.location) == false {
range = NSRange(location: textBlockRange.location, length: old.endLocation - textBlockRange.endLocation)
} else if new.endLocation < textBlockRange.endLocation && new.endLocation > textBlockRange.location {
range = NSRange(location: new.location, length: textBlockRange.location - new.location)
} else {
range = textBlockRange.union(new)
}
return range
}
private func adjustedTextBlockRangeForward(new: NSRange, old: NSRange, textBlockRange: NSRange) -> NSRange {
let range: NSRange
let isLocationChanged = new.location != old.location
if (new.contains(textBlockRange.location) && new.contains(textBlockRange.endLocation - 1)
|| (textBlockRange.union(new) == textBlockRange && new.length > 0 && isLocationChanged == false)
|| isLocationChanged == false) {
range = new.union(textBlockRange)
} else {
range = NSRange(location: textBlockRange.endLocation, length: new.endLocation - textBlockRange.endLocation)
}
return range
}
private func adjustRangeOnNonFocus(oldRange: UITextRange?) {
guard let currentRange = selectedTextRange?.toNSRange(in: self),
let previousRange = oldRange?.toNSRange(in: self)
else { return }
var rangeToSet: NSRange?
let isReverseTraversal = currentRange.location < previousRange.location
var rangeToTraverse = NSRange(location: currentRange.location, length: attributedText.length - (currentRange.location + currentRange.length))
if isReverseTraversal {
rangeToTraverse = NSRange(location: 0, length: currentRange.location)
attributedText.enumerateAttribute(.textBlock, in: rangeToTraverse, options: [.longestEffectiveRangeNotRequired, .reverse]) { val, range, stop in
if (val as? Bool != true), rangeToSet == nil {
rangeToSet = NSRange(location: range.location + range.length, length: 0)
stop.pointee = true
}
}
} else {
attributedText.enumerateAttribute(.textBlock, in: rangeToTraverse, options: [.longestEffectiveRangeNotRequired]) { val, range, stop in
if (val as? Bool != true), rangeToSet == nil {
rangeToSet = NSRange(location: range.location, length: 0)
stop.pointee = true
}
}
}
selectedTextRange = rangeToSet?.toTextRange(textInput: self) ?? oldRange
}
var context: RichTextViewContext? {
delegate as? RichTextViewContext
}
init(
frame: CGRect = .zero,
context: RichTextViewContext,
allowAutogrowing: Bool = false,
undoManager: UndoManager? = nil) {
let textContainer = TextContainer()
let layoutManager = LayoutManager()
layoutManager.addTextContainer(textContainer)
richTextStorage.addLayoutManager(layoutManager)
_undoManager = undoManager
super.init(frame: frame, textContainer: textContainer, allowAutogrowing: allowAutogrowing)
delegateOverrides = [GestureRecognizerDelegateOverride]()
layoutManager.delegate = self
layoutManager.layoutManagerDelegate = self
textContainer.textView = self
textContainer.heightTracksTextView = true
textContainer.widthTracksTextView = true
self.delegate = context
richTextStorage.textStorageDelegate = self
self.backgroundColor = defaultBackgroundColor
self.textColor = defaultTextColor
// self.typingAttributes = defaultTypingAttributes
}
override var undoManager: UndoManager? {
_undoManager ?? super.undoManager
}
var contentLength: Int {
return textStorage.length
}
weak var textProcessor: TextProcessor? {
didSet {
richTextStorage.delegate = textProcessor
}
}
var textEndRange: NSRange {
return NSRange(location: contentLength, length: 0)
}
var currentLineRange: NSRange? {
return lineRange(from: selectedRange.location)
}
var viewport: CGRect {
return bounds.inset(by: textContainerInset)
}
var visibleRange: NSRange? {
return rangeForRect(viewport)
}
func contentLinesInRange(_ range: NSRange) -> [EditorLine] {
guard range.isValidIn(self) else { return [] }
var lines = [EditorLine]()
var startingRange = NSRange(location: range.location, length: 0)
let endLocation = max(startingRange.location, range.location + range.length - 1)
while startingRange.location <= endLocation {
let paraRange = rangeOfParagraph(at: startingRange.location)
let text = self.attributedText.attributedSubstring(from: paraRange)
let editorLine = EditorLine(text: text, range: paraRange)
lines.append(editorLine)
startingRange = NSRange(location: paraRange.length + paraRange.location + 1, length: 0)
}
return lines
}
func rangeOfParagraph(at location: Int) -> NSRange {
guard let position = self.position(from: beginningOfDocument, offset: location),
let paraRange = tokenizer.rangeEnclosingPosition(position, with: .paragraph, inDirection: UITextDirection(rawValue: UITextStorageDirection.backward.rawValue)),
let range = paraRange.toNSRange(in: self)
else {
return NSRange(location: location, length: 0)
}
return range
}
func previousContentLine(from location: Int) -> EditorLine? {
let currentLineRange = rangeOfParagraph(at: location)
guard let position = self.position(from: beginningOfDocument, offset: currentLineRange.location - 1),
let paraRange = tokenizer.rangeEnclosingPosition(position, with: .paragraph, inDirection: UITextDirection(rawValue: UITextStorageDirection.backward.rawValue)),
let range = paraRange.toNSRange(in: self)
else { return nil }
return EditorLine(text: attributedText.attributedSubstring(from: range), range: range)
}
func nextContentLine(from location: Int) -> EditorLine? {
let currentLineRange = rangeOfParagraph(at: location)
guard let position = self.position(from: beginningOfDocument, offset: currentLineRange.endLocation + 1),
let paraRange = tokenizer.rangeEnclosingPosition(position, with: .paragraph, inDirection: UITextDirection(rawValue: UITextStorageDirection.forward.rawValue)),
let range = paraRange.toNSRange(in: self)
else { return nil }
return EditorLine(text: attributedText.attributedSubstring(from: range), range: range)
}
override var keyCommands: [UIKeyCommand]? {
let tab = "\t"
let enter = "\r"
return [
UIKeyCommand(input: tab, modifierFlags: [], action: #selector(handleKeyCommand(command:))),
UIKeyCommand(input: tab, modifierFlags: .shift, action: #selector(handleKeyCommand(command:))),
UIKeyCommand(input: enter, modifierFlags: .shift, action: #selector(handleKeyCommand(command:))),
UIKeyCommand(input: enter, modifierFlags: .control, action: #selector(handleKeyCommand(command:))),
UIKeyCommand(input: enter, modifierFlags: .alternate, action: #selector(handleKeyCommand(command:))),
]
}
@available(*, unavailable, message: "init(coder:) unavailable, use init")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#if targetEnvironment(macCatalyst)
@objc(_focusRingType)
var focusRingType: UInt {
return 1 //NSFocusRingTypeNone
}
#endif
@objc
func handleKeyCommand(command: UIKeyCommand) {
guard let input = command.input,
let key = EditorKey(input)
else { return }
let modifierFlags = command.modifierFlags
richTextViewDelegate?.richTextView(self, didReceive: key, modifierFlags: modifierFlags, at: selectedRange)
}
private func setupPlaceholder() {
placeholderLabel.removeFromSuperview()
addSubview(placeholderLabel)
placeholderLabel.attributedText = placeholderText
let placeholderLabelWidthConstraint = placeholderLabel.widthAnchor.constraint(equalTo: self.widthAnchor, constant: -textContainer.lineFragmentPadding - textContainerInset.right)
placeholderLabelWidthConstraint.priority = .init(UILayoutPriority.required.rawValue - 1)
NSLayoutConstraint.activate([
placeholderLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: textContainerInset.top),
placeholderLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -textContainerInset.bottom),
placeholderLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: textContainer.lineFragmentPadding + textContainerInset.left),
placeholderLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -textContainer.lineFragmentPadding - textContainerInset.right),
placeholderLabelWidthConstraint
])
}
func wordAt(_ location: Int) -> NSAttributedString? {
guard let position = self.position(from: beginningOfDocument, offset: location),
let wordRange = tokenizer.rangeEnclosingPosition(position, with: .word, inDirection: UITextDirection(rawValue: UITextStorageDirection.backward.rawValue)),
let range = wordRange.toNSRange(in: self)
else { return nil }
return attributedText.attributedSubstring(from: range)
}
func lineRange(from location: Int) -> NSRange? {
var currentLocation = location
guard contentLength > 0 else { return .zero }
var range = NSRange()
// In case this is called before layout has completed, e.g. from TextProcessor, the last entered glyph
// will not have been laid out by layoutManager but would be present in TextStorage. It can also happen
// when deleting multiple characters where layout is pending in the same case. Following logic finds the
// last valid glyph that is already laid out.
while currentLocation > 0 && layoutManager.isValidGlyphIndex(currentLocation) == false {
currentLocation -= 1
}
guard layoutManager.isValidGlyphIndex(currentLocation) else { return NSRange(location: 0, length: 1) }
layoutManager.lineFragmentUsedRect(forGlyphAt: currentLocation, effectiveRange: &range)
guard range.location != NSNotFound else { return nil }
// As mentioned above, in case of this getting called before layout is completed,
// we need to account for the range that has been changed. storage.changeInLength provides
// the change that might not have been laid already
return NSRange(location: range.location, length: range.length + textStorage.changeInLength)
}
func invalidateLayout(for range: NSRange) {
layoutManager.invalidateLayout(forCharacterRange: range.clamped(upperBound: textStorage.length), actualCharacterRange: nil)
}
func invalidateDisplay(for range: NSRange) {
// invalidateDisplay does not need clamping like required by invalidateLayout
layoutManager.invalidateDisplay(forCharacterRange: range)
}
func resetTypingAttributes() {
self.typingAttributes = defaultTypingAttributes
}
override func deleteBackward() {
defer {
if contentLength == 0 {
resetTypingAttributes()
}
richTextViewDelegate?.richTextView(self, didReceive: .backspace, modifierFlags: [], at: selectedRange)
}
guard contentLength > 0 else { return }
let proposedRange = NSRange(location: max(0, selectedRange.location - 1), length: 0)
let attributedText: NSAttributedString = self.attributedText // single allocation
let attributeExists = (attributedText.attribute(.textBlock, at: proposedRange.location, effectiveRange: nil)) != nil
guard attributeExists,
let textRange = adjustedTextBlockRangeOnSelectionChange(oldRange: selectedRange, newRange: proposedRange)
else {
// if the character getting deleted is a list item spacer, do a double delete
let textToBeDeleted = attributedText.substring(from: NSRange(location: proposedRange.location, length: 1))
if textToBeDeleted == ListTextProcessor.blankLineFiller {
super.deleteBackward()
}
super.deleteBackward()
return
}
let rangeToDelete = NSRange(location: textRange.location, length: selectedRange.location - textRange.location)
replaceCharacters(in: rangeToDelete, with: NSAttributedString())
selectedRange = NSRange(location: textRange.location, length: 0)
}
func insertAttachment(in range: NSRange, attachment: Attachment) {
richTextStorage.insertAttachment(in: range, attachment: attachment, withSpacer: attachment.spacer)
// TODO: Temporary workaround to get around the issue of adding content type to attachments
// This needs to be done outside PRTextStorage from ProtonCore as it can no longer depend on Proton framework
// Ideally, attachment.string should be used - possibly consider using richTextStorage.replaceCharacters
richTextStorage.addAttributes(attachment.attributes, range: NSRange(location: range.location, length: 1))
if let rangeInContainer = attachment.rangeInContainer() {
edited(range: rangeInContainer)
}
// scrollRangeToVisible(NSRange(location: range.location, length: 1))
}
func edited(range: NSRange) {
textStorage.beginEditing()
textStorage.edited([.editedCharacters, .editedAttributes], range: range, changeInLength: 0)
textStorage.endEditing()
}
func transformContents<T: EditorContentEncoding>(in range: NSRange? = nil, using transformer: T) -> [T.EncodedType] {
return contents(in: range).compactMap(transformer.encode)
}
func replaceCharacters(in range: NSRange, with attrString: NSAttributedString) {
textStorage.replaceCharacters(in: range, with: attrString)
ensuringValidSelectedRange()
}
func replaceCharacters(in range: NSRange, with string: String) {
// Delegate to function with attrString so that default attributes are automatically applied
textStorage.replaceCharacters(in: range, with: NSAttributedString(string: string))
}
@discardableResult
func ensuringValidSelectedRange() -> NSRange {
let clamped = selectedRange.clamped(upperBound: attributedText.length)
if clamped != selectedRange {
selectedRange = clamped
}
return selectedRange
}
private func updatePlaceholderVisibility() {
guard (placeholderText ?? NSAttributedString(string: "")).string.count > 0,
self.attributedText.length == 0 else {
if placeholderLabel.superview != nil {
placeholderLabel.removeFromSuperview()
}
return
}
setupPlaceholder()
if isLineNumbersEnabled {
//TODO: else use default
contentMode = .redraw
}
}
func attributeValue(at location: CGPoint, for attribute: NSAttributedString.Key) -> Any? {
let characterIndex = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
guard characterIndex < textStorage.length else {
return nil
}
let attributes = textStorage.attributes(at: characterIndex, longestEffectiveRange: nil, in: textStorage.fullRange)
return attributes[attribute]
}
func glyphRange(forCharacterRange range: NSRange) -> NSRange {
return layoutManager.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
}
func rects(for range: NSRange) -> [CGRect] {
guard let textRange = range.toTextRange(textInput: self) else { return [] }
let rects = selectionRects(for: textRange)
return rects.map { $0.rect }
}
func boundingRect(forGlyphRange range: NSRange) -> CGRect {
return layoutManager.boundingRect(forGlyphRange: range, in: textContainer)
}
func rangeForRect(_ rect: CGRect, performingLayout: Bool = false) -> NSRange? {
let range = performingLayout
? layoutManager.glyphRange(forBoundingRect: rect, in: textContainer)
: layoutManager.glyphRange(forBoundingRectWithoutAdditionalLayout: rect, in: textContainer)
return range == .zero ? nil : range
}
func contents(in range: NSRange? = nil) -> AnySequence<EditorContent> {
return self.attributedText.enumerateContents(in: range)
}
func setAttributes(_ attrs: [NSAttributedString.Key: Any], range: NSRange) {
textStorage.setAttributes(attrs, range: range)
}
func addAttributes(_ attrs: [NSAttributedString.Key: Any], range: NSRange) {
textStorage.addAttributes(attrs, range: range)
}
func removeAttributes(_ attrs: [NSAttributedString.Key], range: NSRange) {
richTextStorage.removeAttributes(attrs, range: range)
}
func enumerateAttribute(_ attrName: NSAttributedString.Key, in enumerationRange: NSRange, options opts: NSAttributedString.EnumerationOptions = [], using block: (Any?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
textStorage.enumerateAttribute(attrName, in: enumerationRange, options: opts, using: block)
}
func rangeOfCharacter(at point: CGPoint) -> NSRange? {
return characterRange(at: point)?.toNSRange(in: self)
}
func didTap(at location: CGPoint) {
context?.selectedTextView = self
let characterRange = rangeOfCharacter(at: location)
richTextViewDelegate?.richTextView(self, didTapAtLocation: location, characterRange: characterRange)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: self)
didTap(at: position)
}
}
// When a user enables `Use keyboard navigation to move focus between controls` it enables the focus system in the app.
// It means focused item also becomes the first responder. UITextView is focusable by default, but if isEditable is set to false, it cannot be focussed anymore.
// This leads to an issue where if a user selects text in non-editable text view and right clicks the text view loses the first responder to the focused menu, and therefore no actions are provided, and it is not possible to copy.
// Returning true will make it focusable regardless if it is editable, and it will not be losing responder because it will stay focused.
// It is not perfect, as a user can focus this view with Tab and make no actions on it.
override var canBecomeFocused: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
// Check if the range is valid, as in some cases, if the range happens to be invalid, it
// may result in a crash with [NSBigMutableString substringWithRange:]: Range out of bounds
guard selectedRange.isValidIn(self) else { return false }
guard editorView?.canPerformMenuAction(action, withSender: sender) == true else {
return false
}
return super.canPerformAction(action, withSender: sender)
}
override func copy(_ sender: Any?) {
if editorView?.responds(to: #selector(copy(_:))) ?? false {
editorView?.copy(sender)
} else {
super.copy(sender)
}
}
override func paste(_ sender: Any?) {
if editorView?.responds(to: #selector(paste(_:))) ?? false {
editorView?.paste(sender)
} else {
super.paste(sender)
}
}
override func cut(_ sender: Any?) {
if editorView?.responds(to: #selector(cut)) ?? false {
editorView?.cut(sender)
} else {
super.cut(sender)
}
}
override func select(_ sender: Any?) {
if editorView?.responds(to: #selector(select)) ?? false {
editorView?.select(sender)
} else {
super.select(sender)
}
}
override func selectAll(_ sender: Any?) {
if editorView?.responds(to: #selector(selectAll)) ?? false {
editorView?.selectAll(sender)
} else {
super.selectAll(sender)
}
}
override func toggleUnderline(_ sender: Any?) {
if editorView?.responds(to: #selector(toggleUnderline)) ?? false {
editorView?.toggleUnderline(sender)
} else {
super.toggleUnderline(sender)
}
}
override func toggleItalics(_ sender: Any?) {
if editorView?.responds(to: #selector(toggleItalics)) ?? false {
editorView?.toggleItalics(sender)
} else {
super.toggleItalics(sender)
}
}
override func toggleBoldface(_ sender: Any?) {
if editorView?.responds(to: #selector(toggleBoldface)) ?? false {
editorView?.toggleBoldface(sender)
} else {
super.toggleBoldface(sender)
}
}
override func caretRect(for position: UITextPosition) -> CGRect {
guard isEditable else {
return super.caretRect(for: position)
}
let location = offset(from: beginningOfDocument, to: position)
let lineRect = layoutManager.boundingRect(forGlyphRange: NSRange(location: location, length: 0), in: textContainer)
var caretRect = super.caretRect(for: position)
caretRect.origin.y = lineRect.minY + textContainerInset.top
caretRect.size.height = lineRect.height
return caretRect
}
override func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.delegate is UIScrollView {
super.addGestureRecognizer(gestureRecognizer)
} else {
// Add an override for gesture recognizer to handle long-press in attachments.
// In absence of override, ling press on attachment will cause attachment to be lifted up
// instead of allowing to select text in editor
if let delegate = gestureRecognizer.delegate {
let delegateOverride = GestureRecognizerDelegateOverride(baseDelegate: delegate)
gestureRecognizer.delegate = delegateOverride
delegateOverrides.append(delegateOverride)
}
super.addGestureRecognizer(gestureRecognizer)
}
}
override func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {
let firstCharacterRect = caretRect(for: range.start)
let lastCharacterRect = caretRect(for: range.end)
return super.selectionRects(for: range).map { selectionRect -> UITextSelectionRect in
if selectionRect.containsStart {
return TextSelectionRect(selection: selectionRect, caretRect: firstCharacterRect)
} else if selectionRect.containsEnd {
return TextSelectionRect(selection: selectionRect, caretRect: lastCharacterRect)
} else {
return selectionRect
}
}
}
}
extension RichTextView: NSLayoutManagerDelegate {
func layoutManager(_ layoutManager: NSLayoutManager, didCompleteLayoutFor textContainer: NSTextContainer?, atEnd layoutFinishedFlag: Bool) {
richTextViewDelegate?.richTextView(self, didFinishLayout: layoutFinishedFlag)
}
func layoutManager(_ layoutManager: NSLayoutManager, shouldBreakLineByHyphenatingBeforeCharacterAt charIndex: Int) -> Bool {
// Disable hyphenation for backgroundStyle as otherwise, in some cases, with hyphenations,
// layoutManager.glyphRange(forCharacterRange:) returns range with hyphenation and textstorage has
// corresponding ranges without hyphenation
// This will likely be revised in a future version to enable back hyphenation
return false
}
func layoutManager(_ layoutManager: NSLayoutManager, shouldGenerateGlyphs glyphs: UnsafePointer<CGGlyph>, properties props: UnsafePointer<NSLayoutManager.GlyphProperty>, characterIndexes charIndexes: UnsafePointer<Int>, font aFont: UIFont, forGlyphRange glyphRange: NSRange) -> Int {
guard showsInvisibleCharacters == false else { return 0 }
if let attribute = textStorage.attribute(.invisible, at: charIndexes.pointee, effectiveRange: nil) as? Int, attribute == 1 {
let nullProperties = Array(repeating: NSLayoutManager.GlyphProperty.null, count: glyphRange.length)
layoutManager.setGlyphs(glyphs, properties: nullProperties, characterIndexes: charIndexes, font: aFont, forGlyphRange: glyphRange)
return glyphRange.length
} else {
return 0
}
}
}
extension RichTextView: TextStorageDelegate {
func textStorage(_ textStorage: PRTextStorage, didDelete attachment: NSTextAttachment) {
guard let attachment = attachment as? Attachment else {
return
}
attachment.removeFromSuperview()
}
func textStorage(_ textStorage: PRTextStorage, will deleteText: NSAttributedString, insertText insertedText: NSAttributedString, in range: NSRange) {
textProcessor?.textStorage(textStorage, willProcessDeletedText: deleteText, insertedText: insertedText, range: range)
}
func textStorage(_ textStorage: PRTextStorage, edited actions: NSTextStorage.EditActions, in editedRange: NSRange, changeInLength delta: Int) {
updatePlaceholderVisibility()
drawDefaultLineNumberIfRequired()
}
}
extension RichTextView: LayoutManagerDelegate {
var lineNumberWrappingMarker: String? {
lineNumberProvider?.lineNumberWrappingMarker
}
var listLineFormatting: LineFormatting {
return richTextViewListDelegate?.listLineFormatting ?? RichTextView.defaultListLineFormatting
}
var paragraphStyle: NSMutableParagraphStyle? {
return defaultTextFormattingProvider?.paragraphStyle
}
func lineNumberString(for index: Int) -> String? {
lineNumberProvider?.lineNumberString(for: index)
}
func listMarkerForItem(at index: Int, level: Int, previousLevel: Int, attributeValue: Any?) -> ListLineMarker {
let font = UIFont.preferredFont(forTextStyle: .body)
let defaultValue = NSAttributedString(string: "*", attributes: [.font: font])
return richTextViewListDelegate?.richTextView(self, listMarkerForItemAt: index, level: level, previousLevel: previousLevel, attributeValue: attributeValue) ?? .string(defaultValue)
}
}
private final class TextSelectionRect: UITextSelectionRect {
override var rect: CGRect { _rect }
override var writingDirection: NSWritingDirection { _writingDirection }
override var containsStart: Bool { _containsStart }
override var containsEnd: Bool { _containsEnd }
override var isVertical: Bool { _isVertical }
private let _rect: CGRect
private let _writingDirection: NSWritingDirection
private let _containsStart: Bool
private let _containsEnd: Bool
private let _isVertical: Bool
init(selection: UITextSelectionRect, caretRect: CGRect) {
self._rect = .init(x: selection.rect.minX, y: caretRect.minY, width: selection.rect.width, height: caretRect.height)
self._writingDirection = selection.writingDirection
self._containsStart = selection.containsStart
self._containsEnd = selection.containsEnd
self._isVertical = selection.isVertical
}
}