summaryrefslogtreecommitdiffstats
path: root/editor/libeditor/TextEditSubActionHandler.cpp
blob: bc6ce9894f1b98379d1fe2df18b92c774a59a094 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "TextEditor.h"

#include "mozilla/Assertions.h"
#include "mozilla/EditAction.h"
#include "mozilla/EditorDOMPoint.h"
#include "mozilla/EditorUtils.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_editor.h"
#include "mozilla/TextComposition.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/HTMLBRElement.h"
#include "mozilla/dom/NodeFilterBinding.h"
#include "mozilla/dom/NodeIterator.h"
#include "mozilla/dom/Selection.h"
#include "nsAString.h"
#include "nsCOMPtr.h"
#include "nsCRT.h"
#include "nsCRTGlue.h"
#include "nsComponentManagerUtils.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsGkAtoms.h"
#include "nsIContent.h"
#include "nsIHTMLCollection.h"
#include "nsINode.h"
#include "nsISupportsBase.h"
#include "nsLiteralString.h"
#include "nsNameSpaceManager.h"
#include "nsPrintfCString.h"
#include "nsTextNode.h"
#include "nsUnicharUtils.h"

namespace mozilla {

using namespace dom;

#define CANCEL_OPERATION_AND_RETURN_EDIT_ACTION_RESULT_IF_READONLY \
  if (IsReadonly()) {                                              \
    return EditActionCanceled(NS_OK);                              \
  }

nsresult TextEditor::InitEditorContentAndSelection() {
  MOZ_ASSERT(IsEditActionDataAvailable());

  nsresult rv = MaybeCreatePaddingBRElementForEmptyEditor();
  if (NS_FAILED(rv)) {
    NS_WARNING(
        "EditorBase::MaybeCreatePaddingBRElementForEmptyEditor() failed");
    return rv;
  }

  // If the selection hasn't been set up yet, set it up collapsed to the end of
  // our editable content.
  // XXX I think that this shouldn't do it in `HTMLEditor` because it maybe
  //     removed by the web app and if they call `Selection::AddRange()`,
  //     it may cause multiple selection ranges.
  if (!SelectionRefPtr()->RangeCount()) {
    nsresult rv = CollapseSelectionToEnd();
    if (NS_FAILED(rv)) {
      NS_WARNING("EditorBase::CollapseSelectionToEnd() failed");
      return rv;
    }
  }

  if (IsPlaintextEditor() && !IsSingleLineEditor()) {
    nsresult rv = EnsurePaddingBRElementInMultilineEditor();
    if (NS_FAILED(rv)) {
      NS_WARNING(
          "TextEditor::EnsurePaddingBRElementInMultilineEditor() failed");
      return rv;
    }
  }

  return NS_OK;
}

void TextEditor::OnStartToHandleTopLevelEditSubAction(
    EditSubAction aTopLevelEditSubAction,
    nsIEditor::EDirection aDirectionOfTopLevelEditSubAction, ErrorResult& aRv) {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(!AsHTMLEditor());
  MOZ_ASSERT(!aRv.Failed());

  EditorBase::OnStartToHandleTopLevelEditSubAction(
      aTopLevelEditSubAction, aDirectionOfTopLevelEditSubAction, aRv);

  MOZ_ASSERT(GetTopLevelEditSubAction() == aTopLevelEditSubAction);
  MOZ_ASSERT(GetDirectionOfTopLevelEditSubAction() ==
             aDirectionOfTopLevelEditSubAction);

  if (NS_WARN_IF(Destroyed())) {
    aRv.Throw(NS_ERROR_EDITOR_DESTROYED);
    return;
  }

  if (NS_WARN_IF(!mInitSucceeded)) {
    return;
  }

  if (aTopLevelEditSubAction == EditSubAction::eSetText) {
    // SetText replaces all text, so spell checker handles starting from the
    // start of new value.
    SetSpellCheckRestartPoint(EditorDOMPoint(mRootElement, 0));
    return;
  }

  if (aTopLevelEditSubAction == EditSubAction::eInsertText ||
      aTopLevelEditSubAction == EditSubAction::eInsertTextComingFromIME) {
    // For spell checker, previous selected node should be text node if
    // possible. If anchor is root of editor, it may become invalid offset
    // after inserting text.
    EditorRawDOMPoint point = FindBetterInsertionPoint(
        EditorRawDOMPoint(SelectionRefPtr()->AnchorRef()));
    NS_WARNING_ASSERTION(
        point.IsSet(),
        "EditorBase::FindBetterInsertionPoint() failed, but ignored");
    if (point.IsSet()) {
      SetSpellCheckRestartPoint(point);
      return;
    }
  }
  if (SelectionRefPtr()->AnchorRef().IsSet()) {
    SetSpellCheckRestartPoint(
        EditorRawDOMPoint(SelectionRefPtr()->AnchorRef()));
  }
}

nsresult TextEditor::OnEndHandlingTopLevelEditSubAction() {
  MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
  MOZ_ASSERT(!AsHTMLEditor());

  nsresult rv;
  while (true) {
    if (NS_WARN_IF(Destroyed())) {
      rv = NS_ERROR_EDITOR_DESTROYED;
      break;
    }

    // XXX Probably, we should spellcheck again after edit action (not top-level
    //     sub-action) is handled because the ranges can be referred only by
    //     users.
    if (NS_FAILED(rv = HandleInlineSpellCheckAfterEdit())) {
      NS_WARNING("TextEditor::HandleInlineSpellCheckAfterEdit() failed");
      break;
    }

    if (NS_FAILED(rv = EnsurePaddingBRElementForEmptyEditor())) {
      NS_WARNING("TextEditor::EnsurePaddingBRElementForEmptyEditor() failed");
      break;
    }

    if (!IsSingleLineEditor() &&
        NS_FAILED(rv = EnsurePaddingBRElementInMultilineEditor())) {
      NS_WARNING(
          "TextEditor::EnsurePaddingBRElementInMultilineEditor() failed");
      break;
    }

    rv = EnsureCaretNotAtEndOfTextNode();
    if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
      break;
    }
    NS_WARNING_ASSERTION(
        NS_SUCCEEDED(rv),
        "TextEditor::EnsureCaretNotAtEndOfTextNode() failed, but ignored");
    rv = NS_OK;
    break;
  }
  DebugOnly<nsresult> rvIgnored =
      EditorBase::OnEndHandlingTopLevelEditSubAction();
  NS_WARNING_ASSERTION(
      NS_SUCCEEDED(rvIgnored),
      "EditorBase::OnEndHandlingTopLevelEditSubAction() failed, but ignored");
  MOZ_ASSERT(!GetTopLevelEditSubAction());
  MOZ_ASSERT(GetDirectionOfTopLevelEditSubAction() == eNone);
  return rv;
}

EditActionResult TextEditor::InsertLineFeedCharacterAtSelection() {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(IsTextEditor());
  MOZ_ASSERT(!IsSingleLineEditor());

  UndefineCaretBidiLevel();

  CANCEL_OPERATION_AND_RETURN_EDIT_ACTION_RESULT_IF_READONLY

  if (mMaxTextLength >= 0) {
    nsAutoString insertionString(u"\n"_ns);
    EditActionResult result =
        MaybeTruncateInsertionStringForMaxLength(insertionString);
    if (result.Failed()) {
      NS_WARNING(
          "TextEditor::MaybeTruncateInsertionStringForMaxLength() failed");
      return result;
    }
    if (result.Handled()) {
      // Don't return as handled since we stopped inserting the line break.
      return EditActionCanceled();
    }
  }

  // if the selection isn't collapsed, delete it.
  if (!SelectionRefPtr()->IsCollapsed()) {
    nsresult rv =
        DeleteSelectionAsSubAction(nsIEditor::eNone, nsIEditor::eNoStrip);
    if (NS_FAILED(rv)) {
      NS_WARNING(
          "EditorBase::DeleteSelectionAsSubAction(eNone, eNoStrip) failed");
      return EditActionIgnored(rv);
    }
  }

  nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
  if (NS_FAILED(rv)) {
    NS_WARNING("EditorBase::EnsureNoPaddingBRElementForEmptyEditor() failed");
    return EditActionIgnored(rv);
  }

  // get the (collapsed) selection location
  const nsRange* firstRange = SelectionRefPtr()->GetRangeAt(0);
  if (NS_WARN_IF(!firstRange)) {
    return EditActionIgnored(NS_ERROR_FAILURE);
  }

  EditorRawDOMPoint pointToInsert(firstRange->StartRef());
  if (NS_WARN_IF(!pointToInsert.IsSet())) {
    return EditActionIgnored(NS_ERROR_FAILURE);
  }
  MOZ_ASSERT(pointToInsert.IsSetAndValid());
  MOZ_ASSERT(!pointToInsert.IsContainerHTMLElement(nsGkAtoms::br));

  RefPtr<Document> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return EditActionIgnored(NS_ERROR_NOT_INITIALIZED);
  }

  // Don't change my selection in sub-transactions.
  AutoTransactionsConserveSelection dontChangeMySelection(*this);

  // Insert a linefeed character.
  EditorRawDOMPoint pointAfterInsertedLineFeed;
  rv = InsertTextWithTransaction(*document, u"\n"_ns, pointToInsert,
                                 &pointAfterInsertedLineFeed);
  if (!pointAfterInsertedLineFeed.IsSet()) {
    NS_WARNING(
        "EditorBase::InsertTextWithTransaction(\\n) didn't return position of "
        "inserted linefeed");
    return EditActionIgnored(NS_ERROR_FAILURE);
  }
  if (NS_FAILED(rv)) {
    NS_WARNING("TextEditor::InsertTextWithTransaction(\\n) failed");
    return EditActionIgnored(rv);
  }

  // set the selection to the correct location
  MOZ_ASSERT(
      !pointAfterInsertedLineFeed.GetChild(),
      "After inserting text into a text node, pointAfterInsertedLineFeed."
      "GetChild() should be nullptr");
  rv = MOZ_KnownLive(SelectionRefPtr())
           ->CollapseInLimiter(pointAfterInsertedLineFeed);
  if (NS_FAILED(rv)) {
    NS_WARNING("Selection::CollapseInLimiter() failed");
    return EditActionIgnored(rv);
  }

  // XXX I don't think we still need this.  This must have been required when
  //     `<textarea>` was implemented with text nodes and `<br>` elements.
  // see if we're at the end of the editor range
  EditorRawDOMPoint endPoint(EditorBase::GetEndPoint(*SelectionRefPtr()));
  if (endPoint == pointAfterInsertedLineFeed) {
    // SetInterlinePosition(true) means we want the caret to stick to the
    // content on the "right".  We want the caret to stick to whatever is
    // past the break.  This is because the break is on the same line we
    // were on, but the next content will be on the following line.
    IgnoredErrorResult ignoredError;
    SelectionRefPtr()->SetInterlinePosition(true, ignoredError);
    NS_WARNING_ASSERTION(
        !ignoredError.Failed(),
        "Selection::SetInterlinePosition(true) failed, but ignored");
  }

  return EditActionHandled();
}

nsresult TextEditor::EnsureCaretNotAtEndOfTextNode() {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(IsPlaintextEditor());

  // If there is no selection ranges, we should set to the end of the editor.
  // This is usually performed in InitEditorContentAndSelection(), however,
  // if the editor is reframed, this may be called by
  // OnEndHandlingTopLevelEditSubAction().
  if (!SelectionRefPtr()->RangeCount()) {
    DebugOnly<nsresult> rvIgnored = CollapseSelectionToEnd();
    if (NS_WARN_IF(Destroyed())) {
      return NS_ERROR_EDITOR_DESTROYED;
    }
    NS_WARNING_ASSERTION(
        NS_SUCCEEDED(rvIgnored),
        "EditorBase::CollapseSelectionToEnd() failed, but ignored");
  }

  // If we are at the end of the <textarea> element, we need to set the
  // selection to stick to the padding <br> element for empty last line at the
  // end of the <textarea>.
  EditorRawDOMPoint selectionStartPoint(
      EditorBase::GetStartPoint(*SelectionRefPtr()));
  if (NS_WARN_IF(!selectionStartPoint.IsSet())) {
    return NS_ERROR_FAILURE;
  }

  // Nothing to do if we're not at the end of the text node.
  if (!selectionStartPoint.IsInTextNode() ||
      !selectionStartPoint.IsEndOfContainer()) {
    return NS_OK;
  }

  Element* anonymousDivElement = GetRoot();
  if (NS_WARN_IF(!anonymousDivElement)) {
    return NS_ERROR_NULL_POINTER;
  }
  nsINode* parentNode = selectionStartPoint.GetContainer()->GetParentNode();
  if (parentNode != anonymousDivElement) {
    return NS_OK;
  }

  nsIContent* nextContent =
      selectionStartPoint.GetContainer()->GetNextSibling();
  if (!nextContent ||
      !EditorUtils::IsPaddingBRElementForEmptyLastLine(*nextContent)) {
    return NS_OK;
  }

  EditorRawDOMPoint afterStartContainer(
      EditorRawDOMPoint::After(*selectionStartPoint.GetContainer()));
  if (NS_WARN_IF(!afterStartContainer.IsSet())) {
    return NS_ERROR_FAILURE;
  }
  IgnoredErrorResult ignoredError;
  MOZ_KnownLive(SelectionRefPtr())
      ->CollapseInLimiter(afterStartContainer, ignoredError);
  if (NS_WARN_IF(Destroyed())) {
    return NS_ERROR_EDITOR_DESTROYED;
  }
  NS_WARNING_ASSERTION(!ignoredError.Failed(),
                       "Selection::CollapseInLimiter() failed");
  return ignoredError.StealNSResult();
}

void TextEditor::HandleNewLinesInStringForSingleLineEditor(
    nsString& aString) const {
  static const char16_t kLF = static_cast<char16_t>('\n');
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(IsPlaintextEditor());
  MOZ_ASSERT(aString.FindChar(static_cast<uint16_t>('\r')) == kNotFound);

  // First of all, check if aString contains '\n' since if the string
  // does not include it, we don't need to do nothing here.
  int32_t firstLF = aString.FindChar(kLF, 0);
  if (firstLF == kNotFound) {
    return;
  }

  switch (mNewlineHandling) {
    case nsIEditor::eNewlinesReplaceWithSpaces:
      // Default of Firefox:
      // Strip trailing newlines first so we don't wind up with trailing spaces
      aString.Trim(LFSTR, false, true);
      aString.ReplaceChar(kLF, ' ');
      break;
    case nsIEditor::eNewlinesStrip:
      aString.StripChar(kLF);
      break;
    case nsIEditor::eNewlinesPasteToFirst:
    default: {
      // we get first *non-empty* line.
      int32_t offset = 0;
      while (firstLF == offset) {
        offset++;
        firstLF = aString.FindChar(kLF, offset);
      }
      if (firstLF > 0) {
        aString.Truncate(firstLF);
      }
      if (offset > 0) {
        aString.Cut(0, offset);
      }
      break;
    }
    case nsIEditor::eNewlinesReplaceWithCommas:
      // Default of Thunderbird:
      aString.Trim(LFSTR, true, true);
      aString.ReplaceChar(kLF, ',');
      break;
    case nsIEditor::eNewlinesStripSurroundingWhitespace: {
      nsAutoString result;
      uint32_t offset = 0;
      while (offset < aString.Length()) {
        int32_t nextLF = !offset ? firstLF : aString.FindChar(kLF, offset);
        if (nextLF < 0) {
          result.Append(nsDependentSubstring(aString, offset));
          break;
        }
        uint32_t wsBegin = nextLF;
        // look backwards for the first non-white-space char
        while (wsBegin > offset && NS_IS_SPACE(aString[wsBegin - 1])) {
          --wsBegin;
        }
        result.Append(nsDependentSubstring(aString, offset, wsBegin - offset));
        offset = nextLF + 1;
        while (offset < aString.Length() && NS_IS_SPACE(aString[offset])) {
          ++offset;
        }
      }
      aString = result;
      break;
    }
    case nsIEditor::eNewlinesPasteIntact:
      // even if we're pasting newlines, don't paste leading/trailing ones
      aString.Trim(LFSTR, true, true);
      break;
  }
}

EditActionResult TextEditor::HandleInsertText(
    EditSubAction aEditSubAction, const nsAString& aInsertionString) {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(IsTextEditor());
  MOZ_ASSERT(aEditSubAction == EditSubAction::eInsertText ||
             aEditSubAction == EditSubAction::eInsertTextComingFromIME);

  UndefineCaretBidiLevel();

  if (aInsertionString.IsEmpty() &&
      aEditSubAction != EditSubAction::eInsertTextComingFromIME) {
    // HACK: this is a fix for bug 19395
    // I can't outlaw all empty insertions
    // because IME transaction depend on them
    // There is more work to do to make the
    // world safe for IME.
    return EditActionCanceled();
  }

  nsAutoString insertionString(aInsertionString);
  if (mMaxTextLength >= 0) {
    EditActionResult result =
        MaybeTruncateInsertionStringForMaxLength(insertionString);
    if (result.Failed()) {
      NS_WARNING(
          "TextEditor::MaybeTruncateInsertionStringForMaxLength() failed");
      return result.MarkAsHandled();
    }
    // If we're exceeding the maxlength when composing IME, we need to clean up
    // the composing text, so we shouldn't return early.
    if (result.Handled() && insertionString.IsEmpty() &&
        aEditSubAction != EditSubAction::eInsertTextComingFromIME) {
      return EditActionCanceled();
    }
  }

  uint32_t start = 0;
  if (IsPasswordEditor()) {
    if (GetComposition() && !GetComposition()->String().IsEmpty()) {
      start = GetComposition()->XPOffsetInTextNode();
    } else {
      uint32_t end = 0;
      nsContentUtils::GetSelectionInTextControl(SelectionRefPtr(), GetRoot(),
                                                start, end);
    }
  }

  // if the selection isn't collapsed, delete it.
  if (!SelectionRefPtr()->IsCollapsed()) {
    nsresult rv =
        DeleteSelectionAsSubAction(nsIEditor::eNone, nsIEditor::eNoStrip);
    if (NS_FAILED(rv)) {
      NS_WARNING(
          "EditorBase::DeleteSelectionAsSubAction(eNone, eNoStrip) failed");
      return EditActionHandled(rv);
    }
  }

  // XXX Why don't we cancel here?  Shouldn't we do this first?
  CANCEL_OPERATION_AND_RETURN_EDIT_ACTION_RESULT_IF_READONLY

  MaybeDoAutoPasswordMasking();

  nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
  if (NS_FAILED(rv)) {
    NS_WARNING("EditorBase::EnsureNoPaddingBRElementForEmptyEditor() failed");
    return EditActionHandled(rv);
  }

  // People have lots of different ideas about what text fields
  // should do with multiline pastes.  See bugs 21032, 23485, 23485, 50935.
  // The six possible options are:
  // 0. paste newlines intact
  // 1. paste up to the first newline (default)
  // 2. replace newlines with spaces
  // 3. strip newlines
  // 4. replace with commas
  // 5. strip newlines and surrounding white-space
  // So find out what we're expected to do:
  if (IsSingleLineEditor()) {
    // XXX Some callers of TextEditor::InsertTextAsAction()  already make the
    //     string use only \n as a linebreaker.  However, they are not hot
    //     path and nsContentUtils::PlatformToDOMLineBreaks() does nothing
    //     if the string doesn't include \r.  So, let's convert linebreakers
    //     here.  Note that there are too many callers of
    //     TextEditor::InsertTextAsAction().  So, it's difficult to keep
    //     maintaining all of them won't reach here without \r nor \r\n.
    // XXX Should we handle do this before truncating the string for
    //     `maxlength`?
    nsContentUtils::PlatformToDOMLineBreaks(insertionString);
    HandleNewLinesInStringForSingleLineEditor(insertionString);
  }

  // get the (collapsed) selection location
  const nsRange* firstRange = SelectionRefPtr()->GetRangeAt(0);
  if (NS_WARN_IF(!firstRange)) {
    return EditActionHandled(NS_ERROR_FAILURE);
  }
  EditorRawDOMPoint atStartOfSelection(firstRange->StartRef());
  if (NS_WARN_IF(!atStartOfSelection.IsSetAndValid())) {
    return EditActionHandled(NS_ERROR_FAILURE);
  }
  MOZ_ASSERT(!atStartOfSelection.IsContainerHTMLElement(nsGkAtoms::br));

  RefPtr<Document> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return EditActionHandled(NS_ERROR_NOT_INITIALIZED);
  }

  if (aEditSubAction == EditSubAction::eInsertTextComingFromIME) {
    EditorRawDOMPoint compositionStartPoint = GetCompositionStartPoint();
    if (!compositionStartPoint.IsSet()) {
      compositionStartPoint = FindBetterInsertionPoint(atStartOfSelection);
      NS_WARNING_ASSERTION(
          compositionStartPoint.IsSet(),
          "EditorBase::FindBetterInsertionPoint() failed, but ignored");
    }
    nsresult rv = InsertTextWithTransaction(*document, insertionString,
                                            compositionStartPoint);
    if (NS_WARN_IF(Destroyed())) {
      return EditActionHandled(NS_ERROR_EDITOR_DESTROYED);
    }
    if (NS_FAILED(rv)) {
      NS_WARNING("EditorBase::InsertTextWithTransaction() failed");
      return EditActionHandled(rv);
    }
  } else {
    MOZ_ASSERT(aEditSubAction == EditSubAction::eInsertText);

    // don't change my selection in subtransactions
    AutoTransactionsConserveSelection dontChangeMySelection(*this);

    EditorRawDOMPoint pointAfterStringInserted;
    nsresult rv = InsertTextWithTransaction(*document, insertionString,
                                            atStartOfSelection,
                                            &pointAfterStringInserted);
    if (NS_WARN_IF(Destroyed())) {
      return EditActionHandled(NS_ERROR_EDITOR_DESTROYED);
    }
    if (NS_FAILED(rv)) {
      NS_WARNING("EditorBase::InsertTextWithTransaction() failed");
      return EditActionHandled(rv);
    }

    if (pointAfterStringInserted.IsSet()) {
      // Make the caret attach to the inserted text, unless this text ends with
      // a LF, in which case make the caret attach to the next line.
      bool endsWithLF =
          !insertionString.IsEmpty() && insertionString.Last() == nsCRT::LF;
      IgnoredErrorResult ignoredError;
      SelectionRefPtr()->SetInterlinePosition(endsWithLF, ignoredError);
      NS_WARNING_ASSERTION(
          !ignoredError.Failed(),
          "Selection::SetInterlinePosition() failed, but ignored");

      MOZ_ASSERT(
          !pointAfterStringInserted.GetChild(),
          "After inserting text into a text node, pointAfterStringInserted."
          "GetChild() should be nullptr");
      ignoredError = IgnoredErrorResult();
      MOZ_KnownLive(SelectionRefPtr())
          ->CollapseInLimiter(pointAfterStringInserted, ignoredError);
      if (NS_WARN_IF(Destroyed())) {
        return EditActionHandled(NS_ERROR_EDITOR_DESTROYED);
      }
      NS_WARNING_ASSERTION(
          !ignoredError.Failed(),
          "Selection::CollapseInLimiter() failed, but ignored");
    }
  }

  // Unmask inputted character(s) if necessary.
  if (IsPasswordEditor() && IsMaskingPassword() && CanEchoPasswordNow()) {
    nsresult rv = SetUnmaskRangeAndNotify(start, insertionString.Length(),
                                          LookAndFeel::GetPasswordMaskDelay());
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                         "TextEditor::SetUnmaskRangeAndNotify() failed");
    return EditActionHandled(rv);
  }

  return EditActionHandled();
}

EditActionResult TextEditor::SetTextWithoutTransaction(
    const nsAString& aValue) {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(!AsHTMLEditor());
  MOZ_ASSERT(IsPlaintextEditor());
  MOZ_ASSERT(!IsIMEComposing());
  MOZ_ASSERT(!IsUndoRedoEnabled());
  MOZ_ASSERT(GetEditAction() != EditAction::eReplaceText);
  MOZ_ASSERT(mMaxTextLength < 0);
  MOZ_ASSERT(aValue.FindChar(static_cast<char16_t>('\r')) == kNotFound);

  UndefineCaretBidiLevel();

  // XXX If we're setting value, shouldn't we keep setting the new value here?
  CANCEL_OPERATION_AND_RETURN_EDIT_ACTION_RESULT_IF_READONLY

  MaybeDoAutoPasswordMasking();

  nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
  if (NS_FAILED(rv)) {
    NS_WARNING("EditorBase::EnsureNoPaddingBRElementForEmptyEditor() failed");
    return EditActionResult(rv);
  }

  RefPtr<Element> anonymousDivElement = GetRoot();
  nsIContent* firstChild = anonymousDivElement->GetFirstChild();

  // We can use this fast path only when:
  //  - we need to insert a text node.
  //  - we need to replace content of existing text node.
  // Additionally, for avoiding odd result, we should check whether we're in
  // usual condition.
  if (IsSingleLineEditor()) {
    // If we're a single line text editor, i.e., <input>, there is only padding
    // <br> element.  Otherwise, there should be only one text node.  But note
    // that even if there is a padding <br> element for empty editor, it's
    // already been removed by `EnsureNoPaddingBRElementForEmptyEditor()`.  So,
    // at here, there should be only one text node or no children.
    if (firstChild && (!firstChild->IsText() || firstChild->GetNextSibling())) {
      return EditActionIgnored();
    }
  } else {
    // If we're a multiline text editor, i.e., <textarea>, there is a padding
    // <br> element for empty last line followed by scrollbar/resizer elements.
    // Otherwise, a text node is followed by them.
    if (!firstChild) {
      return EditActionIgnored();
    }
    if (firstChild->IsText()) {
      if (!firstChild->GetNextSibling() ||
          !EditorUtils::IsPaddingBRElementForEmptyLastLine(
              *firstChild->GetNextSibling())) {
        return EditActionIgnored();
      }
    } else if (!EditorUtils::IsPaddingBRElementForEmptyLastLine(*firstChild)) {
      return EditActionIgnored();
    }
  }

  // XXX Password fields accept line breaks as normal characters with this code.
  //     Is this intentional?
  nsAutoString sanitizedValue(aValue);
  if (IsSingleLineEditor() && !IsPasswordEditor()) {
    HandleNewLinesInStringForSingleLineEditor(sanitizedValue);
  }

  if (!firstChild || !firstChild->IsText()) {
    if (sanitizedValue.IsEmpty()) {
      return EditActionHandled();
    }
    RefPtr<Document> document = GetDocument();
    if (NS_WARN_IF(!document)) {
      return EditActionIgnored();
    }
    RefPtr<nsTextNode> newTextNode = CreateTextNode(sanitizedValue);
    if (!newTextNode) {
      NS_WARNING("EditorBase::CreateTextNode() failed");
      return EditActionIgnored();
    }
    nsresult rv = InsertNodeWithTransaction(
        *newTextNode, EditorDOMPoint(anonymousDivElement, 0));
    if (NS_WARN_IF(Destroyed())) {
      return EditActionResult(NS_ERROR_EDITOR_DESTROYED);
    }
    if (NS_FAILED(rv)) {
      NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
      return EditActionResult(rv);
    }
    return EditActionHandled();
  }

  // TODO: If new value is empty string, we should only remove it.
  RefPtr<Text> textNode = firstChild->GetAsText();
  if (MOZ_UNLIKELY(!textNode)) {
    NS_WARNING("The first child was not a text node");
    return EditActionIgnored();
  }
  rv = SetTextNodeWithoutTransaction(sanitizedValue, *textNode);
  if (NS_FAILED(rv)) {
    NS_WARNING("EditorBase::SetTextNodeWithoutTransaction() failed");
    return EditActionResult(rv);
  }

  // If we replaced non-empty value with empty string, we need to delete the
  // text node.
  if (sanitizedValue.IsEmpty() && !textNode->Length()) {
    nsresult rv = DeleteNodeWithTransaction(*textNode);
    if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
      return EditActionResult(NS_ERROR_EDITOR_DESTROYED);
    }
    NS_WARNING_ASSERTION(
        NS_SUCCEEDED(rv),
        "EditorBase::DeleteNodeWithTransaction() failed, but ignored");
    // XXX I don't think this is necessary because the anonymous `<div>`
    //     element has now only padding `<br>` element even if there are
    //     something.
    IgnoredErrorResult ignoredError;
    SelectionRefPtr()->SetInterlinePosition(true, ignoredError);
    NS_WARNING_ASSERTION(!ignoredError.Failed(),
                         "Selection::SetInterlinePoisition(true) failed");
  }

  return EditActionHandled();
}

EditActionResult TextEditor::HandleDeleteSelection(
    nsIEditor::EDirection aDirectionAndAmount,
    nsIEditor::EStripWrappers aStripWrappers) {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(IsTextEditor());
  MOZ_ASSERT(aStripWrappers == nsIEditor::eNoStrip);

  UndefineCaretBidiLevel();

  CANCEL_OPERATION_AND_RETURN_EDIT_ACTION_RESULT_IF_READONLY

  // if there is only padding <br> element for empty editor, cancel the
  // operation.
  if (mPaddingBRElementForEmptyEditor) {
    return EditActionCanceled();
  }
  EditActionResult result =
      HandleDeleteSelectionInternal(aDirectionAndAmount, nsIEditor::eNoStrip);
  // HandleDeleteSelectionInternal() creates SelectionBatcher.  Therefore,
  // quitting from it might cause having destroyed the editor.
  if (NS_WARN_IF(Destroyed())) {
    return result.SetResult(NS_ERROR_EDITOR_DESTROYED);
  }
  NS_WARNING_ASSERTION(
      result.Succeeded(),
      "TextEditor::HandleDeleteSelectionInternal(eNoStrip) failed");
  return result;
}

EditActionResult TextEditor::HandleDeleteSelectionInternal(
    nsIEditor::EDirection aDirectionAndAmount,
    nsIEditor::EStripWrappers aStripWrappers) {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(IsTextEditor());
  MOZ_ASSERT(aStripWrappers == nsIEditor::eNoStrip);

  // If the current selection is empty (e.g the user presses backspace with
  // a collapsed selection), then we want to avoid sending the selectstart
  // event to the user, so we hide selection changes. However, we still
  // want to send a single selectionchange event to the document, so we
  // batch the selectionchange events, such that a single event fires after
  // the AutoHideSelectionChanges destructor has been run.
  SelectionBatcher selectionBatcher(SelectionRefPtr());
  AutoHideSelectionChanges hideSelection(SelectionRefPtr());
  nsAutoScriptBlocker scriptBlocker;

  if (IsPasswordEditor() && IsMaskingPassword()) {
    MaskAllCharacters();
  } else {
    EditorRawDOMPoint selectionStartPoint(
        EditorBase::GetStartPoint(*SelectionRefPtr()));
    if (NS_WARN_IF(!selectionStartPoint.IsSet())) {
      return EditActionResult(NS_ERROR_FAILURE);
    }

    if (!SelectionRefPtr()->IsCollapsed()) {
      nsresult rv = DeleteSelectionWithTransaction(aDirectionAndAmount,
                                                   nsIEditor::eNoStrip);
      NS_WARNING_ASSERTION(
          NS_SUCCEEDED(rv),
          "EditorBase::DeleteSelectionWithTransaction(eNoStrip) failed");
      return EditActionHandled(rv);
    }

    // Test for distance between caret and text that will be deleted
    AutoCaretBidiLevelManager bidiLevelManager(*this, aDirectionAndAmount,
                                               selectionStartPoint);
    if (bidiLevelManager.Failed()) {
      NS_WARNING("EditorBase::AutoCaretBidiLevelManager() failed");
      return EditActionResult(NS_ERROR_FAILURE);
    }
    bidiLevelManager.MaybeUpdateCaretBidiLevel(*this);
    if (bidiLevelManager.Canceled()) {
      return EditActionCanceled();
    }
  }

  AutoRangeArray rangesToDelete(*SelectionRefPtr());
  Result<nsIEditor::EDirection, nsresult> result =
      rangesToDelete.ExtendAnchorFocusRangeFor(*this, aDirectionAndAmount);
  if (result.isErr()) {
    NS_WARNING("AutoRangeArray::ExtendAnchorFocusRangeFor() failed");
    return EditActionResult(result.unwrapErr());
  }

  nsresult rv = DeleteRangesWithTransaction(
      result.unwrap(), nsIEditor::eNoStrip, rangesToDelete);
  NS_WARNING_ASSERTION(
      NS_SUCCEEDED(rv),
      "EditorBase::DeleteRangesWithTransaction(eNoStrip) failed");
  return EditActionHandled(rv);
}

EditActionResult TextEditor::ComputeValueFromTextNodeAndPaddingBRElement(
    nsAString& aValue) const {
  MOZ_ASSERT(IsEditActionDataAvailable());

  // If there is a padding <br> element, there's no content.  So output empty
  // string.
  if (mPaddingBRElementForEmptyEditor) {
    aValue.Truncate();
    return EditActionHandled();
  }

  // If it's neither <input type="text"> nor <textarea>, e.g., an HTML editor
  // which is in plaintext mode (e.g., plaintext email composer on Thunderbird),
  // it should be handled by the expensive path.
  if (AsHTMLEditor()) {
    return EditActionIgnored();
  }

  Element* anonymousDivElement = GetRoot();
  if (!anonymousDivElement) {
    // Don't warn this case, this is possible, e.g., 997805.html
    aValue.Truncate();
    return EditActionHandled();
  }

  nsIContent* textNodeOrPaddingBRElement = anonymousDivElement->GetFirstChild();
  if (!textNodeOrPaddingBRElement) {
    aValue.Truncate();
    return EditActionHandled();
  }

  // If it's an <input type="text"> element, the DOM tree should be:
  // <div (::-moz-text-control-editing-root)>
  //   #text
  // </div>
  //
  // If it's a <textarea> element, the DOM tree should be:
  // <div (::-moz-text-control-editing-root)>
  //   #text (if there is)
  //   <br type="_moz">
  //   <scrollbar orient="horizontal">
  //   ...
  // </div>

  Text* textNode = textNodeOrPaddingBRElement->GetAsText();
  if (!textNode) {
    // If there is no text node in the expected DOM tree, we can say that it's
    // just empty.
    aValue.Truncate();
    return EditActionHandled();
  }

  nsIContent* firstChildExceptText =
      textNode ? textNodeOrPaddingBRElement->GetNextSibling()
               : textNodeOrPaddingBRElement;
  // If the DOM tree is unexpected, fall back to the expensive path.
  bool isInput = IsSingleLineEditor();
  bool isTextarea = !isInput;
  if (NS_WARN_IF(isInput && firstChildExceptText) ||
      NS_WARN_IF(isTextarea && !firstChildExceptText) ||
      NS_WARN_IF(isTextarea &&
                 !EditorUtils::IsPaddingBRElementForEmptyLastLine(
                     *firstChildExceptText) &&
                 !firstChildExceptText->IsXULElement(nsGkAtoms::scrollbar))) {
    return EditActionIgnored();
  }

  // Otherwise, the text data is the value.
  textNode->GetData(aValue);
  return EditActionHandled();
}

nsresult TextEditor::EnsurePaddingBRElementInMultilineEditor() {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(IsPlaintextEditor());
  MOZ_ASSERT(!IsSingleLineEditor());

  Element* anonymousDivElement = GetRoot();
  if (NS_WARN_IF(!anonymousDivElement)) {
    return NS_ERROR_FAILURE;
  }

  // Assuming EditorBase::MaybeCreatePaddingBRElementForEmptyEditor() has been
  // called first.
  // XXX This assumption is wrong.  This method may be called alone.  Actually,
  //     we see this warning in mochitest log.  So, we should fix this bug
  //     later.
  if (NS_WARN_IF(!anonymousDivElement->GetLastChild())) {
    return NS_ERROR_FAILURE;
  }

  RefPtr<HTMLBRElement> brElement =
      HTMLBRElement::FromNode(anonymousDivElement->GetLastChild());
  if (!brElement) {
    AutoTransactionsConserveSelection dontChangeMySelection(*this);
    EditorDOMPoint endOfAnonymousDiv(
        EditorDOMPoint::AtEndOf(*anonymousDivElement));
    CreateElementResult createPaddingBRResult =
        InsertPaddingBRElementForEmptyLastLineWithTransaction(
            endOfAnonymousDiv);
    NS_WARNING_ASSERTION(
        createPaddingBRResult.Succeeded(),
        "EditorBase::InsertPaddingBRElementForEmptyLastLineWithTransaction() "
        "failed");
    return createPaddingBRResult.Rv();
  }

  // Check to see if the trailing BR is a former padding <br> element for empty
  // editor - this will have stuck around if we previously morphed a trailing
  // node into a padding <br> element.
  if (!brElement->IsPaddingForEmptyEditor()) {
    return NS_OK;
  }

  // Morph it back to a padding <br> element for empty last line.
  brElement->UnsetFlags(NS_PADDING_FOR_EMPTY_EDITOR);
  brElement->SetFlags(NS_PADDING_FOR_EMPTY_LAST_LINE);

  return NS_OK;
}

EditActionResult TextEditor::MaybeTruncateInsertionStringForMaxLength(
    nsAString& aInsertionString) {
  MOZ_ASSERT(IsEditActionDataAvailable());
  MOZ_ASSERT(mMaxTextLength >= 0);

  if (!IsPlaintextEditor() || IsIMEComposing()) {
    return EditActionIgnored();
  }

  // Ignore user pastes
  switch (GetEditAction()) {
    case EditAction::ePaste:
    case EditAction::ePasteAsQuotation:
    case EditAction::eDrop:
    case EditAction::eReplaceText:
      // EditActionPrinciple() is non-null iff the edit was requested by
      // javascript.
      if (!GetEditActionPrincipal()) {
        // By now we are certain that this is a user paste, before we ignore it,
        // lets check if the user explictly enabled truncating user pastes.
        if (!StaticPrefs::editor_truncate_user_pastes()) {
          return EditActionIgnored();
        }
      }
      [[fallthrough]];
    default:
      break;
  }

  int32_t currentLength = INT32_MAX;
  nsresult rv = GetTextLength(&currentLength);
  if (NS_FAILED(rv)) {
    NS_WARNING("TextEditor::GetTextLength() failed");
    return EditActionResult(rv);
  }

  uint32_t selectionStart, selectionEnd;
  nsContentUtils::GetSelectionInTextControl(SelectionRefPtr(), GetRoot(),
                                            selectionStart, selectionEnd);

  TextComposition* composition = GetComposition();
  const uint32_t kOldCompositionStringLength =
      composition ? composition->String().Length() : 0;

  const uint32_t kSelectionLength = selectionEnd - selectionStart;
  // XXX This computation must be wrong.  If we'll support non-collapsed
  //     selection even during composition for Korean IME, kSelectionLength
  //     is part of kOldCompositionStringLength.
  const uint32_t kNewLength =
      currentLength - kSelectionLength - kOldCompositionStringLength;
  if (kNewLength >= static_cast<uint32_t>(mMaxTextLength)) {
    aInsertionString.Truncate();  // Too long, we cannot accept new character.
    return EditActionHandled();
  }

  if (aInsertionString.Length() + kNewLength <=
      static_cast<uint32_t>(mMaxTextLength)) {
    return EditActionIgnored();  // Enough short string.
  }

  int32_t newInsertionStringLength = mMaxTextLength - kNewLength;
  MOZ_ASSERT(newInsertionStringLength > 0);
  char16_t maybeHighSurrogate =
      aInsertionString.CharAt(newInsertionStringLength - 1);
  char16_t maybeLowSurrogate =
      aInsertionString.CharAt(newInsertionStringLength);
  // Don't split the surrogate pair.
  if (NS_IS_SURROGATE_PAIR(maybeHighSurrogate, maybeLowSurrogate)) {
    newInsertionStringLength--;
  }
  // XXX What should we do if we're removing IVS but its preceding
  //     character won't be removed?
  aInsertionString.Truncate(newInsertionStringLength);
  return EditActionHandled();
}

bool TextEditor::CanEchoPasswordNow() const {
  if (!LookAndFeel::GetEchoPassword() ||
      (mFlags & nsIEditor::eEditorDontEchoPassword)) {
    return false;
  }

  return GetEditAction() != EditAction::eDrop &&
         GetEditAction() != EditAction::ePaste;
}

}  // namespace mozilla