summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/editing/commands/typing_command.cc
blob: f32727d51fd65c2633dcdd911240e2da983d016d (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
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
/*
 * Copyright (C) 2005, 2006, 2007, 2008 Apple Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "third_party/blink/renderer/core/editing/commands/typing_command.h"

#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/editing/commands/break_blockquote_command.h"
#include "third_party/blink/renderer/core/editing/commands/delete_selection_command.h"
#include "third_party/blink/renderer/core/editing/commands/delete_selection_options.h"
#include "third_party/blink/renderer/core/editing/commands/editing_commands_utilities.h"
#include "third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.h"
#include "third_party/blink/renderer/core/editing/commands/insert_line_break_command.h"
#include "third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.h"
#include "third_party/blink/renderer/core/editing/commands/insert_text_command.h"
#include "third_party/blink/renderer/core/editing/editing_behavior.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/plain_text_range.h"
#include "third_party/blink/renderer/core/editing/selection_modifier.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/visible_position.h"
#include "third_party/blink/renderer/core/editing/visible_selection.h"
#include "third_party/blink/renderer/core/editing/visible_units.h"
#include "third_party/blink/renderer/core/events/before_text_inserted_event.h"
#include "third_party/blink/renderer/core/events/text_event.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/html_br_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/platform/heap/heap.h"

namespace blink {

namespace {

bool IsValidDocument(const Document& document) {
  return document.GetFrame() && document.GetFrame()->GetDocument() == &document;
}

String DispatchBeforeTextInsertedEvent(const String& text,
                                       const VisibleSelection& selection,
                                       EditingState* editing_state) {
  Node* start_node = selection.Start().ComputeContainerNode();
  if (!start_node || !RootEditableElement(*start_node))
    return text;

  // Send BeforeTextInsertedEvent. The event handler will update text if
  // necessary.
  const Document& document = start_node->GetDocument();
  auto* evt = MakeGarbageCollected<BeforeTextInsertedEvent>(text);
  RootEditableElement(*start_node)->DispatchEvent(*evt);
  if (IsValidDocument(document) && selection.IsValidFor(document))
    return evt->GetText();
  // editing/inserting/webkitBeforeTextInserted-removes-frame.html
  // and
  // editing/inserting/webkitBeforeTextInserted-disconnects-selection.html
  // reaches here.
  editing_state->Abort();
  return String();
}

DispatchEventResult DispatchTextInputEvent(LocalFrame* frame,
                                           const String& text,
                                           EditingState* editing_state) {
  const Document& document = *frame->GetDocument();
  Element* target = document.FocusedElement();
  if (!target)
    return DispatchEventResult::kCanceledBeforeDispatch;

  // Send TextInputEvent. Unlike BeforeTextInsertedEvent, there is no need to
  // update text for TextInputEvent as it doesn't have the API to modify text.
  TextEvent* event = TextEvent::Create(frame->DomWindow(), text,
                                       kTextEventInputIncrementalInsertion);
  event->SetUnderlyingEvent(nullptr);
  DispatchEventResult result = target->DispatchEvent(*event);
  if (IsValidDocument(document))
    return result;
  // editing/inserting/insert-text-remove-iframe-on-textInput-event.html
  // reaches here.
  editing_state->Abort();
  return result;
}

PlainTextRange GetSelectionOffsets(const SelectionInDOMTree& selection) {
  const VisibleSelection visible_selection = CreateVisibleSelection(selection);
  const EphemeralRange range = FirstEphemeralRangeOf(visible_selection);
  if (range.IsNull())
    return PlainTextRange();
  ContainerNode* const editable =
      RootEditableElementOrTreeScopeRootNodeOf(selection.Base());
  DCHECK(editable);
  return PlainTextRange::Create(*editable, range);
}

SelectionInDOMTree CreateSelection(const wtf_size_t start,
                                   const wtf_size_t end,
                                   Element* element) {
  const EphemeralRange& start_range =
      PlainTextRange(0, static_cast<int>(start)).CreateRange(*element);
  DCHECK(start_range.IsNotNull());
  const Position& start_position = start_range.EndPosition();

  const EphemeralRange& end_range =
      PlainTextRange(0, static_cast<int>(end)).CreateRange(*element);
  DCHECK(end_range.IsNotNull());
  const Position& end_position = end_range.EndPosition();

  const SelectionInDOMTree& selection =
      SelectionInDOMTree::Builder()
          .SetBaseAndExtent(start_position, end_position)
          .Build();
  return selection;
}

bool CanAppendNewLineFeedToSelection(const VisibleSelection& selection,
                                     EditingState* editing_state) {
  Element* element = selection.RootEditableElement();
  if (!element)
    return false;

  const Document& document = element->GetDocument();
  auto* event = MakeGarbageCollected<BeforeTextInsertedEvent>(String("\n"));
  element->DispatchEvent(*event);
  // event may invalidate frame or selection
  if (IsValidDocument(document) && selection.IsValidFor(document))
    return event->GetText().length();
  // editing/inserting/webkitBeforeTextInserted-removes-frame.html
  // and
  // editing/inserting/webkitBeforeTextInserted-disconnects-selection.html
  // reaches here.
  editing_state->Abort();
  return false;
}

}  // anonymous namespace

TypingCommand::TypingCommand(Document& document,
                             CommandType command_type,
                             const String& text_to_insert,
                             Options options,
                             TextGranularity granularity,
                             TextCompositionType composition_type)
    : CompositeEditCommand(document),
      command_type_(command_type),
      text_to_insert_(text_to_insert),
      open_for_more_typing_(true),
      select_inserted_text_(options & kSelectInsertedText),
      smart_delete_(options & kSmartDelete),
      granularity_(granularity),
      composition_type_(composition_type),
      kill_ring_(options & kKillRing),
      opened_by_backward_delete_(false) {
  UpdatePreservesTypingStyle(command_type_);
}

void TypingCommand::DeleteSelection(Document& document, Options options) {
  LocalFrame* frame = document.GetFrame();
  DCHECK(frame);

  if (!frame->Selection()
           .ComputeVisibleSelectionInDOMTreeDeprecated()
           .IsRange())
    return;

  if (TypingCommand* last_typing_command =
          LastTypingCommandIfStillOpenForTyping(frame)) {
    UpdateSelectionIfDifferentFromCurrentSelection(last_typing_command, frame);

    // InputMethodController uses this function to delete composition
    // selection.  It won't be aborted.
    last_typing_command->DeleteSelection(options & kSmartDelete,
                                         ASSERT_NO_EDITING_ABORT);
    return;
  }

  MakeGarbageCollected<TypingCommand>(document, kDeleteSelection, "", options)
      ->Apply();
}

void TypingCommand::DeleteSelectionIfRange(
    const SelectionForUndoStep& selection,
    EditingState* editing_state) {
  if (!selection.IsRange())
    return;
  // Although the 'selection' to delete is indeed a Range, it may have been
  // built from a Caret selection; in that case we don't want to expand so that
  // the table structure is deleted as well.
  bool expand_for_special = EndingSelection().IsRange();
  ApplyCommandToComposite(
      MakeGarbageCollected<DeleteSelectionCommand>(
          selection, DeleteSelectionOptions::Builder()
                         .SetSmartDelete(smart_delete_)
                         .SetMergeBlocksAfterDelete(true)
                         .SetExpandForSpecialElements(expand_for_special)
                         .SetSanitizeMarkup(true)
                         .Build()),
      editing_state);
}

void TypingCommand::DeleteKeyPressed(Document& document,
                                     Options options,
                                     TextGranularity granularity) {
  if (granularity == TextGranularity::kCharacter) {
    LocalFrame* frame = document.GetFrame();
    if (TypingCommand* last_typing_command =
            LastTypingCommandIfStillOpenForTyping(frame)) {
      // If the last typing command is not Delete, open a new typing command.
      // We need to group continuous delete commands alone in a single typing
      // command.
      if (last_typing_command->CommandTypeOfOpenCommand() == kDeleteKey) {
        UpdateSelectionIfDifferentFromCurrentSelection(last_typing_command,
                                                       frame);
        EditingState editing_state;
        last_typing_command->DeleteKeyPressed(granularity, options & kKillRing,
                                              &editing_state);
        return;
      }
    }
  }

  MakeGarbageCollected<TypingCommand>(document, kDeleteKey, "", options,
                                      granularity)
      ->Apply();
}

void TypingCommand::ForwardDeleteKeyPressed(Document& document,
                                            EditingState* editing_state,
                                            Options options,
                                            TextGranularity granularity) {
  // FIXME: Forward delete in TextEdit appears to open and close a new typing
  // command.
  if (granularity == TextGranularity::kCharacter) {
    LocalFrame* frame = document.GetFrame();
    if (TypingCommand* last_typing_command =
            LastTypingCommandIfStillOpenForTyping(frame)) {
      UpdateSelectionIfDifferentFromCurrentSelection(last_typing_command,
                                                     frame);
      last_typing_command->ForwardDeleteKeyPressed(
          granularity, options & kKillRing, editing_state);
      return;
    }
  }

  MakeGarbageCollected<TypingCommand>(document, kForwardDeleteKey, "", options,
                                      granularity)
      ->Apply();
}

String TypingCommand::TextDataForInputEvent() const {
  if (commands_.IsEmpty() || IsIncrementalInsertion())
    return text_to_insert_;
  return commands_.back()->TextDataForInputEvent();
}

void TypingCommand::UpdateSelectionIfDifferentFromCurrentSelection(
    TypingCommand* typing_command,
    LocalFrame* frame) {
  DCHECK(frame);
  const SelectionInDOMTree& current_selection =
      frame->Selection().GetSelectionInDOMTree();
  if (current_selection == typing_command->EndingSelection().AsSelection())
    return;

  typing_command->SetStartingSelection(
      SelectionForUndoStep::From(current_selection));
  typing_command->SetEndingSelection(
      SelectionForUndoStep::From(current_selection));
}

void TypingCommand::InsertText(Document& document,
                               const String& text,
                               Options options,
                               TextCompositionType composition,
                               const bool is_incremental_insertion) {
  LocalFrame* frame = document.GetFrame();
  DCHECK(frame);
  EditingState editing_state;
  InsertText(document, text, frame->Selection().GetSelectionInDOMTree(),
             options, &editing_state, composition, is_incremental_insertion);
}

void TypingCommand::AdjustSelectionAfterIncrementalInsertion(
    LocalFrame* frame,
    const wtf_size_t selection_start,
    const wtf_size_t text_length,
    EditingState* editing_state) {
  if (!IsIncrementalInsertion())
    return;

  // TODO(editing-dev): The use of UpdateStyleAndLayout
  // needs to be audited. see http://crbug.com/590369 for more details.
  frame->GetDocument()->UpdateStyleAndLayout(DocumentUpdateReason::kEditing);

  Element* element = frame->Selection()
                         .ComputeVisibleSelectionInDOMTreeDeprecated()
                         .RootEditableElement();

  // TODO(editing-dev): The text insertion should probably always leave the
  // selection in an editable region, but we know of at least one case where it
  // doesn't (see test case in crbug.com/767599). Return early in this case to
  // avoid a crash.
  if (!element) {
    editing_state->Abort();
    return;
  }

  const wtf_size_t new_end = selection_start + text_length;
  const SelectionInDOMTree& selection =
      CreateSelection(new_end, new_end, element);
  SetEndingSelection(SelectionForUndoStep::From(selection));
}

// FIXME: We shouldn't need to take selectionForInsertion. It should be
// identical to FrameSelection's current selection.
void TypingCommand::InsertText(
    Document& document,
    const String& text,
    const SelectionInDOMTree& passed_selection_for_insertion,
    Options options,
    EditingState* editing_state,
    TextCompositionType composition_type,
    const bool is_incremental_insertion,
    InputEvent::InputType input_type) {
  DCHECK(!document.NeedsLayoutTreeUpdate());
  LocalFrame* frame = document.GetFrame();
  DCHECK(frame);

  const VisibleSelection& current_selection =
      frame->Selection().ComputeVisibleSelectionInDOMTree();
  const VisibleSelection& selection_for_insertion =
      CreateVisibleSelection(passed_selection_for_insertion);

  String new_text = text;
  if (composition_type != kTextCompositionUpdate) {
    new_text = DispatchBeforeTextInsertedEvent(text, selection_for_insertion,
                                               editing_state);
    if (editing_state->IsAborted())
      return;
  }

  if (composition_type == kTextCompositionConfirm) {
    if (DispatchTextInputEvent(frame, new_text, editing_state) !=
        DispatchEventResult::kNotCanceled)
      return;
    // event handler might destroy document.
    if (editing_state->IsAborted())
      return;
    // editing/inserting/insert-text-nodes-disconnect-on-textinput-event.html
    // hits true for ABORT_EDITING_COMMAND_IF macro.
    ABORT_EDITING_COMMAND_IF(!selection_for_insertion.IsValidFor(document));
  }

  // Do nothing if no need to delete and insert.
  if (selection_for_insertion.IsCaret() && new_text.IsEmpty())
    return;

  // TODO(editing-dev): The use of UpdateStyleAndLayout
  // needs to be audited. see http://crbug.com/590369 for more details.
  document.UpdateStyleAndLayout(DocumentUpdateReason::kEditing);

  const PlainTextRange selection_offsets =
      GetSelectionOffsets(selection_for_insertion.AsSelection());
  if (selection_offsets.IsNull())
    return;
  const wtf_size_t selection_start = selection_offsets.Start();

  // Set the starting and ending selection appropriately if we are using a
  // selection that is different from the current selection.  In the future, we
  // should change EditCommand to deal with custom selections in a general way
  // that can be used by all of the commands.
  if (TypingCommand* last_typing_command =
          LastTypingCommandIfStillOpenForTyping(frame)) {
    if (last_typing_command->EndingVisibleSelection() !=
        selection_for_insertion) {
      const SelectionForUndoStep& selection_for_insertion_as_undo_step =
          SelectionForUndoStep::From(selection_for_insertion.AsSelection());
      last_typing_command->SetStartingSelection(
          selection_for_insertion_as_undo_step);
      last_typing_command->SetEndingSelection(
          selection_for_insertion_as_undo_step);
    }

    last_typing_command->SetCompositionType(composition_type);
    last_typing_command->is_incremental_insertion_ = is_incremental_insertion;
    last_typing_command->selection_start_ = selection_start;
    last_typing_command->input_type_ = input_type;

    EventQueueScope event_queue_scope;
    last_typing_command->InsertTextInternal(
        new_text, options & kSelectInsertedText, editing_state);
    return;
  }

  TypingCommand* command = MakeGarbageCollected<TypingCommand>(
      document, kInsertText, new_text, options, TextGranularity::kCharacter,
      composition_type);
  bool change_selection = selection_for_insertion != current_selection;
  if (change_selection) {
    const SelectionForUndoStep& selection_for_insertion_as_undo_step =
        SelectionForUndoStep::From(selection_for_insertion.AsSelection());
    command->SetStartingSelection(selection_for_insertion_as_undo_step);
    command->SetEndingSelection(selection_for_insertion_as_undo_step);
  }
  command->is_incremental_insertion_ = is_incremental_insertion;
  command->selection_start_ = selection_start;
  command->input_type_ = input_type;
  ABORT_EDITING_COMMAND_IF(!command->Apply());

  if (change_selection) {
    ABORT_EDITING_COMMAND_IF(!current_selection.IsValidFor(document));
    const SelectionInDOMTree& current_selection_as_dom =
        current_selection.AsSelection();
    command->SetEndingSelection(
        SelectionForUndoStep::From(current_selection_as_dom));
    frame->Selection().SetSelection(
        current_selection_as_dom,
        SetSelectionOptions::Builder()
            .SetIsDirectional(frame->Selection().IsDirectional())
            .Build());
  }
}

bool TypingCommand::InsertLineBreak(Document& document) {
  if (TypingCommand* last_typing_command =
          LastTypingCommandIfStillOpenForTyping(document.GetFrame())) {
    EditingState editing_state;
    EventQueueScope event_queue_scope;
    last_typing_command->InsertLineBreak(&editing_state);
    return !editing_state.IsAborted();
  }

  return MakeGarbageCollected<TypingCommand>(document, kInsertLineBreak, "", 0)
      ->Apply();
}

bool TypingCommand::InsertParagraphSeparatorInQuotedContent(
    Document& document) {
  if (TypingCommand* last_typing_command =
          LastTypingCommandIfStillOpenForTyping(document.GetFrame())) {
    EditingState editing_state;
    EventQueueScope event_queue_scope;
    last_typing_command->InsertParagraphSeparatorInQuotedContent(
        &editing_state);
    return !editing_state.IsAborted();
  }

  return MakeGarbageCollected<TypingCommand>(
             document, kInsertParagraphSeparatorInQuotedContent)
      ->Apply();
}

bool TypingCommand::InsertParagraphSeparator(Document& document) {
  if (TypingCommand* last_typing_command =
          LastTypingCommandIfStillOpenForTyping(document.GetFrame())) {
    EditingState editing_state;
    EventQueueScope event_queue_scope;
    last_typing_command->InsertParagraphSeparator(&editing_state);
    return !editing_state.IsAborted();
  }

  return MakeGarbageCollected<TypingCommand>(document,
                                             kInsertParagraphSeparator, "", 0)
      ->Apply();
}

TypingCommand* TypingCommand::LastTypingCommandIfStillOpenForTyping(
    LocalFrame* frame) {
  DCHECK(frame);

  CompositeEditCommand* last_edit_command =
      frame->GetEditor().LastEditCommand();
  if (!last_edit_command || !last_edit_command->IsTypingCommand() ||
      !static_cast<TypingCommand*>(last_edit_command)->IsOpenForMoreTyping())
    return nullptr;

  return static_cast<TypingCommand*>(last_edit_command);
}

void TypingCommand::CloseTyping(LocalFrame* frame) {
  if (TypingCommand* last_typing_command =
          LastTypingCommandIfStillOpenForTyping(frame))
    last_typing_command->CloseTyping();
}

void TypingCommand::DoApply(EditingState* editing_state) {
  if (EndingSelection().IsNone() ||
      !EndingSelection().IsValidFor(GetDocument()))
    return;

  if (command_type_ == kDeleteKey) {
    if (commands_.IsEmpty())
      opened_by_backward_delete_ = true;
  }

  switch (command_type_) {
    case kDeleteSelection:
      DeleteSelection(smart_delete_, editing_state);
      return;
    case kDeleteKey:
      DeleteKeyPressed(granularity_, kill_ring_, editing_state);
      return;
    case kForwardDeleteKey:
      ForwardDeleteKeyPressed(granularity_, kill_ring_, editing_state);
      return;
    case kInsertLineBreak:
      InsertLineBreak(editing_state);
      return;
    case kInsertParagraphSeparator:
      InsertParagraphSeparator(editing_state);
      return;
    case kInsertParagraphSeparatorInQuotedContent:
      InsertParagraphSeparatorInQuotedContent(editing_state);
      return;
    case kInsertText:
      InsertTextInternal(text_to_insert_, select_inserted_text_, editing_state);
      return;
  }

  NOTREACHED();
}

InputEvent::InputType TypingCommand::GetInputType() const {
  using InputType = InputEvent::InputType;

  if (composition_type_ != kTextCompositionNone)
    return InputType::kInsertCompositionText;

  if (input_type_ != InputType::kNone)
    return input_type_;

  switch (command_type_) {
    // TODO(editing-dev): |DeleteSelection| is used by IME but we don't have
    // direction info.
    case kDeleteSelection:
      return InputType::kDeleteContentBackward;
    case kDeleteKey:
      return DeletionInputTypeFromTextGranularity(DeleteDirection::kBackward,
                                                  granularity_);
    case kForwardDeleteKey:
      return DeletionInputTypeFromTextGranularity(DeleteDirection::kForward,
                                                  granularity_);
    case kInsertText:
      return InputType::kInsertText;
    case kInsertLineBreak:
      return InputType::kInsertLineBreak;
    case kInsertParagraphSeparator:
    case kInsertParagraphSeparatorInQuotedContent:
      return InputType::kInsertParagraph;
    default:
      return InputType::kNone;
  }
}

void TypingCommand::TypingAddedToOpenCommand(
    CommandType command_type_for_added_typing) {
  LocalFrame* frame = GetDocument().GetFrame();
  if (!frame)
    return;

  UpdatePreservesTypingStyle(command_type_for_added_typing);
  UpdateCommandTypeOfOpenCommand(command_type_for_added_typing);

  AppliedEditing();
}

void TypingCommand::InsertTextInternal(const String& text,
                                       bool select_inserted_text,
                                       EditingState* editing_state) {
  text_to_insert_ = text;

  if (text.IsEmpty()) {
    InsertTextRunWithoutNewlines(text, editing_state);
    return;
  }
  wtf_size_t selection_start = selection_start_;
  unsigned offset = 0;
  wtf_size_t newline;
  while ((newline = text.find('\n', offset)) != kNotFound) {
    if (newline > offset) {
      const wtf_size_t insertion_length = newline - offset;
      InsertTextRunWithoutNewlines(text.Substring(offset, insertion_length),
                                   editing_state);
      if (editing_state->IsAborted())
        return;

      AdjustSelectionAfterIncrementalInsertion(GetDocument().GetFrame(),
                                               selection_start,
                                               insertion_length, editing_state);
      selection_start += insertion_length;
    }

    InsertParagraphSeparator(editing_state);
    if (editing_state->IsAborted())
      return;

    offset = newline + 1;
    ++selection_start;
  }

  if (text.length() > offset) {
    const wtf_size_t insertion_length = text.length() - offset;
    InsertTextRunWithoutNewlines(text.Substring(offset, insertion_length),
                                 editing_state);
    if (editing_state->IsAborted())
      return;

    AdjustSelectionAfterIncrementalInsertion(GetDocument().GetFrame(),
                                             selection_start, insertion_length,
                                             editing_state);
  }

  if (!select_inserted_text)
    return;

  // If the caller wants the newly-inserted text to be selected, we select from
  // the plain text offset corresponding to the beginning of the range (possibly
  // collapsed) being replaced by the text insert, to wherever the selection was
  // left after the final run of text was inserted.
  ContainerNode* const editable =
      RootEditableElementOrTreeScopeRootNodeOf(EndingSelection().Base());

  const EphemeralRange new_selection_start_collapsed_range =
      PlainTextRange(selection_start_, selection_start_).CreateRange(*editable);
  const Position current_selection_end = EndingSelection().End();

  const SelectionInDOMTree& new_selection =
      SelectionInDOMTree::Builder()
          .SetBaseAndExtent(new_selection_start_collapsed_range.StartPosition(),
                            current_selection_end)
          .Build();

  SetEndingSelection(SelectionForUndoStep::From(new_selection));
}

void TypingCommand::InsertTextRunWithoutNewlines(const String& text,
                                                 EditingState* editing_state) {
  CompositeEditCommand* command;
  if (IsIncrementalInsertion()) {
    command = MakeGarbageCollected<InsertIncrementalTextCommand>(
        GetDocument(), text,
        composition_type_ == kTextCompositionNone
            ? InsertIncrementalTextCommand::
                  kRebalanceLeadingAndTrailingWhitespaces
            : InsertIncrementalTextCommand::kRebalanceAllWhitespaces);
  } else {
    command = MakeGarbageCollected<InsertTextCommand>(
        GetDocument(), text,
        composition_type_ == kTextCompositionNone
            ? InsertTextCommand::kRebalanceLeadingAndTrailingWhitespaces
            : InsertTextCommand::kRebalanceAllWhitespaces);
  }

  command->SetStartingSelection(EndingSelection());
  command->SetEndingSelection(EndingSelection());
  ApplyCommandToComposite(command, editing_state);
  if (editing_state->IsAborted())
    return;

  TypingAddedToOpenCommand(kInsertText);
}

void TypingCommand::InsertLineBreak(EditingState* editing_state) {
  if (!CanAppendNewLineFeedToSelection(EndingVisibleSelection(), editing_state))
    return;

  ApplyCommandToComposite(
      MakeGarbageCollected<InsertLineBreakCommand>(GetDocument()),
      editing_state);
  if (editing_state->IsAborted())
    return;
  TypingAddedToOpenCommand(kInsertLineBreak);
}

void TypingCommand::InsertParagraphSeparator(EditingState* editing_state) {
  if (!CanAppendNewLineFeedToSelection(EndingVisibleSelection(), editing_state))
    return;

  ApplyCommandToComposite(
      MakeGarbageCollected<InsertParagraphSeparatorCommand>(GetDocument()),
      editing_state);
  if (editing_state->IsAborted())
    return;
  TypingAddedToOpenCommand(kInsertParagraphSeparator);
}

void TypingCommand::InsertParagraphSeparatorInQuotedContent(
    EditingState* editing_state) {
  // If the selection starts inside a table, just insert the paragraph separator
  // normally Breaking the blockquote would also break apart the table, which is
  // unecessary when inserting a newline
  if (EnclosingNodeOfType(EndingSelection().Start(), &IsTableStructureNode)) {
    InsertParagraphSeparator(editing_state);
    return;
  }

  ApplyCommandToComposite(
      MakeGarbageCollected<BreakBlockquoteCommand>(GetDocument()),
      editing_state);
  if (editing_state->IsAborted())
    return;
  TypingAddedToOpenCommand(kInsertParagraphSeparatorInQuotedContent);
}

bool TypingCommand::MakeEditableRootEmpty(EditingState* editing_state) {
  DCHECK(!GetDocument().NeedsLayoutTreeUpdate());
  Element* root = RootEditableElementOf(EndingSelection().Base());
  if (!root || !root->HasChildren())
    return false;

  if (root->firstChild() == root->lastChild()) {
    if (IsA<HTMLBRElement>(root->firstChild())) {
      // If there is a single child and it could be a placeholder, leave it
      // alone.
      if (root->GetLayoutObject() &&
          root->GetLayoutObject()->IsLayoutBlockFlow())
        return false;
    }
  }

  RemoveAllChildrenIfPossible(root, editing_state);
  if (editing_state->IsAborted() || root->firstChild())
    return false;

  AddBlockPlaceholderIfNeeded(root, editing_state);
  if (editing_state->IsAborted())
    return false;
  const SelectionInDOMTree& selection =
      SelectionInDOMTree::Builder()
          .Collapse(Position::FirstPositionInNode(*root))
          .Build();
  SetEndingSelection(SelectionForUndoStep::From(selection));

  return true;
}

// If there are multiple Unicode code points to be deleted, adjust the
// range to match platform conventions.
static VisibleSelection AdjustSelectionForBackwardDelete(
    const VisibleSelection& selection) {
  if (selection.End().ComputeContainerNode() !=
      selection.Start().ComputeContainerNode())
    return selection;
  if (selection.End().ComputeOffsetInContainerNode() -
          selection.Start().ComputeOffsetInContainerNode() <=
      1)
    return selection;
  return VisibleSelection::CreateWithoutValidationDeprecated(
      selection.End(),
      PreviousPositionOf(selection.End(), PositionMoveType::kBackwardDeletion),
      selection.Affinity());
}

void TypingCommand::DeleteKeyPressed(TextGranularity granularity,
                                     bool kill_ring,
                                     EditingState* editing_state) {
  LocalFrame* frame = GetDocument().GetFrame();
  if (!frame)
    return;

  if (EndingSelection().IsRange()) {
    DeleteKeyPressedInternal(EndingSelection(), EndingSelection(), kill_ring,
                             editing_state);
    return;
  }

  if (!EndingSelection().IsCaret()) {
    NOTREACHED();
    return;
  }

  // After breaking out of an empty mail blockquote, we still want continue
  // with the deletion so actual content will get deleted, and not just the
  // quote style.
  const bool break_out_result =
      BreakOutOfEmptyMailBlockquotedParagraph(editing_state);
  if (editing_state->IsAborted())
    return;
  if (break_out_result)
    TypingAddedToOpenCommand(kDeleteKey);

  smart_delete_ = false;
  GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kEditing);

  SelectionModifier selection_modifier(*frame, EndingSelection().AsSelection());
  selection_modifier.SetSelectionIsDirectional(SelectionIsDirectional());
  selection_modifier.Modify(SelectionModifyAlteration::kExtend,
                            SelectionModifyDirection::kBackward, granularity);
  if (kill_ring && selection_modifier.Selection().IsCaret() &&
      granularity != TextGranularity::kCharacter) {
    selection_modifier.Modify(SelectionModifyAlteration::kExtend,
                              SelectionModifyDirection::kBackward,
                              TextGranularity::kCharacter);
  }

  const VisiblePosition& visible_start(EndingVisibleSelection().VisibleStart());
  const VisiblePosition& previous_position =
      PreviousPositionOf(visible_start, kCannotCrossEditingBoundary);
  const Node* enclosing_table_cell =
      EnclosingNodeOfType(visible_start.DeepEquivalent(), &IsTableCell);
  const Node* enclosing_table_cell_for_previous_position =
      EnclosingNodeOfType(previous_position.DeepEquivalent(), &IsTableCell);
  if (previous_position.IsNull() ||
      enclosing_table_cell != enclosing_table_cell_for_previous_position) {
    // When the caret is at the start of the editable area, or cell, in an
    // empty list item, break out of the list item.
    const bool break_out_of_empty_list_item_result =
        BreakOutOfEmptyListItem(editing_state);
    if (editing_state->IsAborted())
      return;
    if (break_out_of_empty_list_item_result) {
      TypingAddedToOpenCommand(kDeleteKey);
      return;
    }
  }
  if (previous_position.IsNull()) {
    // When there are no visible positions in the editing root, delete its
    // entire contents.
    if (NextPositionOf(visible_start, kCannotCrossEditingBoundary).IsNull() &&
        MakeEditableRootEmpty(editing_state)) {
      TypingAddedToOpenCommand(kDeleteKey);
      return;
    }
    if (editing_state->IsAborted())
      return;
  }

  // If we have a caret selection at the beginning of a cell, we have
  // nothing to do.
  if (enclosing_table_cell && visible_start.DeepEquivalent() ==
                                  VisiblePosition::FirstPositionInNode(
                                      *const_cast<Node*>(enclosing_table_cell))
                                      .DeepEquivalent())
    return;

  // If the caret is at the start of a paragraph after a table, move content
  // into the last table cell (this is done to follows macOS' behavior).
  if (frame->GetEditor().Behavior().ShouldMergeContentWithTablesOnBackspace() &&
      IsStartOfParagraph(visible_start) &&
      TableElementJustBefore(
          PreviousPositionOf(visible_start, kCannotCrossEditingBoundary))) {
    // Unless the caret is just before a table.  We don't want to move a
    // table into the last table cell.
    if (TableElementJustAfter(visible_start))
      return;
    // Extend the selection backward into the last cell, then deletion will
    // handle the move.
    selection_modifier.Modify(SelectionModifyAlteration::kExtend,
                              SelectionModifyDirection::kBackward, granularity);
    // If the caret is just after a table, select the table and don't delete
    // anything.
  } else if (Element* table = TableElementJustBefore(visible_start)) {
    const SelectionInDOMTree& selection =
        SelectionInDOMTree::Builder()
            .Collapse(Position::BeforeNode(*table))
            .Extend(EndingSelection().Start())
            .Build();
    SetEndingSelection(SelectionForUndoStep::From(selection));
    TypingAddedToOpenCommand(kDeleteKey);
    return;
  }

  const VisibleSelection& selection_to_delete =
      granularity == TextGranularity::kCharacter
          ? AdjustSelectionForBackwardDelete(selection_modifier.Selection())
          : selection_modifier.Selection();

  if (!StartingSelection().IsRange() ||
      selection_to_delete.Base() != StartingSelection().Start()) {
    DeleteKeyPressedInternal(
        SelectionForUndoStep::From(selection_to_delete.AsSelection()),
        SelectionForUndoStep::From(selection_to_delete.AsSelection()),
        kill_ring, editing_state);
    return;
  }
  // Note: |StartingSelection().End()| can be disconnected.
  // See editing/deleting/delete_list_item.html on MacOS.
  const SelectionForUndoStep selection_after_undo =
      SelectionForUndoStep::Builder()
          .SetBaseAndExtentAsBackwardSelection(
              StartingSelection().End(),
              CreateVisiblePosition(selection_to_delete.Extent())
                  .DeepEquivalent())
          .Build();
  DeleteKeyPressedInternal(
      SelectionForUndoStep::From(selection_to_delete.AsSelection()),
      selection_after_undo, kill_ring, editing_state);
}

void TypingCommand::DeleteKeyPressedInternal(
    const SelectionForUndoStep& selection_to_delete,
    const SelectionForUndoStep& selection_after_undo,
    bool kill_ring,
    EditingState* editing_state) {
  DCHECK(!selection_to_delete.IsNone());
  if (selection_to_delete.IsNone())
    return;

  if (selection_to_delete.IsCaret())
    return;

  LocalFrame* frame = GetDocument().GetFrame();
  DCHECK(frame);

  if (kill_ring) {
    frame->GetEditor().AddToKillRing(CreateVisibleSelection(selection_to_delete)
                                         .ToNormalizedEphemeralRange());
  }
  // On Mac, make undo select everything that has been deleted, unless an undo
  // will undo more than just this deletion.
  // FIXME: This behaves like TextEdit except for the case where you open with
  // text insertion and then delete more text than you insert.  In that case all
  // of the text that was around originally should be selected.
  if (frame->GetEditor().Behavior().ShouldUndoOfDeleteSelectText() &&
      opened_by_backward_delete_)
    SetStartingSelection(selection_after_undo);
  DeleteSelectionIfRange(selection_to_delete, editing_state);
  if (editing_state->IsAborted())
    return;
  SetSmartDelete(false);
  TypingAddedToOpenCommand(kDeleteKey);
}

static Position ComputeExtentForForwardDeleteUndo(
    const VisibleSelection& selection,
    const Position& extent) {
  if (extent.ComputeContainerNode() != selection.End().ComputeContainerNode())
    return selection.Extent();
  const int extra_characters =
      selection.Start().ComputeContainerNode() ==
              selection.End().ComputeContainerNode()
          ? selection.End().ComputeOffsetInContainerNode() -
                selection.Start().ComputeOffsetInContainerNode()
          : selection.End().ComputeOffsetInContainerNode();
  return Position::CreateWithoutValidation(
      *extent.ComputeContainerNode(),
      extent.ComputeOffsetInContainerNode() + extra_characters);
}

void TypingCommand::ForwardDeleteKeyPressed(TextGranularity granularity,
                                            bool kill_ring,
                                            EditingState* editing_state) {
  LocalFrame* frame = GetDocument().GetFrame();
  if (!frame)
    return;

  if (EndingSelection().IsRange()) {
    ForwardDeleteKeyPressedInternal(EndingSelection(), EndingSelection(),
                                    kill_ring, editing_state);
    return;
  }

  if (!EndingSelection().IsCaret()) {
    NOTREACHED();
    return;
  }

  smart_delete_ = false;
  GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kEditing);

  // Handle delete at beginning-of-block case.
  // Do nothing in the case that the caret is at the start of a
  // root editable element or at the start of a document.
  SelectionModifier selection_modifier(*frame, EndingSelection().AsSelection());
  selection_modifier.SetSelectionIsDirectional(SelectionIsDirectional());
  selection_modifier.Modify(SelectionModifyAlteration::kExtend,
                            SelectionModifyDirection::kForward, granularity);
  if (kill_ring && selection_modifier.Selection().IsCaret() &&
      granularity != TextGranularity::kCharacter) {
    selection_modifier.Modify(SelectionModifyAlteration::kExtend,
                              SelectionModifyDirection::kForward,
                              TextGranularity::kCharacter);
  }

  Position downstream_end = MostForwardCaretPosition(EndingSelection().End());
  VisiblePosition visible_end = EndingVisibleSelection().VisibleEnd();
  Node* enclosing_table_cell =
      EnclosingNodeOfType(visible_end.DeepEquivalent(), &IsTableCell);
  if (enclosing_table_cell &&
      visible_end.DeepEquivalent() ==
          VisiblePosition::LastPositionInNode(*enclosing_table_cell)
              .DeepEquivalent())
    return;
  if (visible_end.DeepEquivalent() ==
      EndOfParagraph(visible_end).DeepEquivalent()) {
    downstream_end = MostForwardCaretPosition(
        NextPositionOf(visible_end, kCannotCrossEditingBoundary)
            .DeepEquivalent());
  }
  // When deleting tables: Select the table first, then perform the deletion
  if (IsDisplayInsideTable(downstream_end.ComputeContainerNode()) &&
      downstream_end.ComputeOffsetInContainerNode() <=
          CaretMinOffset(downstream_end.ComputeContainerNode())) {
    const SelectionInDOMTree& selection =
        SelectionInDOMTree::Builder()
            .SetBaseAndExtentDeprecated(
                EndingSelection().End(),
                Position::AfterNode(*downstream_end.ComputeContainerNode()))
            .Build();
    SetEndingSelection(SelectionForUndoStep::From(selection));
    TypingAddedToOpenCommand(kForwardDeleteKey);
    return;
  }

  // deleting to end of paragraph when at end of paragraph needs to merge
  // the next paragraph (if any)
  if (granularity == TextGranularity::kParagraphBoundary &&
      selection_modifier.Selection().IsCaret() &&
      IsEndOfParagraph(selection_modifier.Selection().VisibleEnd())) {
    selection_modifier.Modify(SelectionModifyAlteration::kExtend,
                              SelectionModifyDirection::kForward,
                              TextGranularity::kCharacter);
  }

  const VisibleSelection& selection_to_delete = selection_modifier.Selection();
  if (!StartingSelection().IsRange() ||
      MostBackwardCaretPosition(selection_to_delete.Base()) !=
          StartingSelection().Start()) {
    ForwardDeleteKeyPressedInternal(
        SelectionForUndoStep::From(selection_to_delete.AsSelection()),
        SelectionForUndoStep::From(selection_to_delete.AsSelection()),
        kill_ring, editing_state);
    return;
  }
  // Note: |StartingSelection().Start()| can be disconnected.
  const SelectionForUndoStep selection_after_undo =
      SelectionForUndoStep::Builder()
          .SetBaseAndExtentAsForwardSelection(
              StartingSelection().Start(),
              ComputeExtentForForwardDeleteUndo(selection_to_delete,
                                                StartingSelection().End()))
          .Build();
  ForwardDeleteKeyPressedInternal(
      SelectionForUndoStep::From(selection_to_delete.AsSelection()),
      selection_after_undo, kill_ring, editing_state);
}

void TypingCommand::ForwardDeleteKeyPressedInternal(
    const SelectionForUndoStep& selection_to_delete,
    const SelectionForUndoStep& selection_after_undo,
    bool kill_ring,
    EditingState* editing_state) {
  DCHECK(!selection_to_delete.IsNone());
  if (selection_to_delete.IsNone())
    return;

  if (selection_to_delete.IsCaret())
    return;

  LocalFrame* frame = GetDocument().GetFrame();
  DCHECK(frame);

  if (kill_ring) {
    frame->GetEditor().AddToKillRing(CreateVisibleSelection(selection_to_delete)
                                         .ToNormalizedEphemeralRange());
  }
  // Make undo select what was deleted on Mac alone
  if (frame->GetEditor().Behavior().ShouldUndoOfDeleteSelectText())
    SetStartingSelection(selection_after_undo);
  DeleteSelectionIfRange(selection_to_delete, editing_state);
  if (editing_state->IsAborted())
    return;
  SetSmartDelete(false);
  TypingAddedToOpenCommand(kForwardDeleteKey);
}

void TypingCommand::DeleteSelection(bool smart_delete,
                                    EditingState* editing_state) {
  if (!CompositeEditCommand::DeleteSelection(
          editing_state, smart_delete ? DeleteSelectionOptions::SmartDelete()
                                      : DeleteSelectionOptions::NormalDelete()))
    return;
  TypingAddedToOpenCommand(kDeleteSelection);
}

void TypingCommand::UpdatePreservesTypingStyle(CommandType command_type) {
  switch (command_type) {
    case kDeleteSelection:
    case kDeleteKey:
    case kForwardDeleteKey:
    case kInsertParagraphSeparator:
    case kInsertLineBreak:
      preserves_typing_style_ = true;
      return;
    case kInsertParagraphSeparatorInQuotedContent:
    case kInsertText:
      preserves_typing_style_ = false;
      return;
  }
  NOTREACHED();
  preserves_typing_style_ = false;
}

bool TypingCommand::IsTypingCommand() const {
  return true;
}

}  // namespace blink