summaryrefslogtreecommitdiffstats
path: root/views/controls/textfield/textfield_views_model.cc
blob: 50d966262edae8d4efa250858fc6eaa7436c41c1 (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
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/controls/textfield/textfield_views_model.h"

#include <algorithm>

#include "base/i18n/break_iterator.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "base/utf_string_conversions.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/range/range.h"
#include "ui/gfx/font.h"
#include "views/controls/textfield/textfield.h"
#include "views/views_delegate.h"

namespace views {

namespace internal {

// An edit object holds enough information/state to undo/redo the
// change. Two edits are merged when possible, for example, when
// you type new characters in sequence.  |Commit()| can be used to
// mark an edit as an independent edit and it shouldn't be merged.
// (For example, when you did undo/redo, or a text is appended via
// API)
class Edit {
 public:
  enum Type {
    INSERT_EDIT,
    DELETE_EDIT,
    REPLACE_EDIT
  };

  virtual ~Edit() {
  }

  // Revert the change made by this edit in |model|.
  void Undo(TextfieldViewsModel* model) {
    size_t old_cursor = delete_backward_ ? old_text_end() : old_text_start_;
    model->ModifyText(new_text_start_, new_text_end(),
                      old_text_, old_text_start_,
                      old_cursor);
  }

  // Apply the change of this edit to the |model|.
  void Redo(TextfieldViewsModel* model) {
    model->ModifyText(old_text_start_, old_text_end(),
                      new_text_, new_text_start_,
                      new_text_end());
  }

  // Try to merge the edit into this edit. Returns true if merge was
  // successful, or false otherwise. Merged edit will be deleted after
  // redo and should not be reused.
  bool Merge(Edit* edit) {
    return mergeable_ && edit->mergeable() && DoMerge(edit);
  }

  // Commits the edit and marks as un-mergeable.
  void Commit() { mergeable_ = false; }

 private:
  friend class InsertEdit;
  friend class ReplaceEdit;
  friend class DeleteEdit;

  Edit(Type type,
       bool mergeable,
       string16 old_text,
       size_t old_text_start,
       bool delete_backward,
       string16 new_text,
       size_t new_text_start)
      : type_(type),
        mergeable_(mergeable),
        old_text_(old_text),
        old_text_start_(old_text_start),
        delete_backward_(delete_backward),
        new_text_(new_text),
        new_text_start_(new_text_start) {
  }

  // A template method pattern that provides specific merge
  // implementation for each type of edit.
  virtual bool DoMerge(Edit* edit) = 0;

  Type type() { return type_; }

  // Can this edit be merged?
  bool mergeable() { return mergeable_; }

  // Returns the end index of the |old_text_|.
  size_t old_text_end() { return old_text_start_ + old_text_.length(); }

  // Returns the end index of the |new_text_|.
  size_t new_text_end() { return new_text_start_ + new_text_.length(); }

  Type type_;

  // True if the edit can be marged.
  bool mergeable_;
  // Deleted text by this edit.
  string16 old_text_;
  // The index of |old_text_|.
  size_t old_text_start_;
  // True if the deletion is made backward.
  bool delete_backward_;
  // Added text.
  string16 new_text_;
  // The index of |new_text_|
  size_t new_text_start_;

  DISALLOW_COPY_AND_ASSIGN(Edit);
};

class InsertEdit : public Edit {
 public:
  InsertEdit(bool mergeable, const string16& new_text, size_t at)
      : Edit(INSERT_EDIT, mergeable, string16(), at, false, new_text, at) {
  }

  // Edit implementation.
  virtual bool DoMerge(Edit* edit) OVERRIDE {
    if (edit->type() != INSERT_EDIT || new_text_end() != edit->new_text_start_)
      return false;
    // If continuous edit, merge it.
    // TODO(oshima): gtk splits edits between whitespace. Find out what
    // we want to here and implement if necessary.
    new_text_ += edit->new_text_;
    return true;
  }
};

class ReplaceEdit : public Edit {
 public:
  ReplaceEdit(bool mergeable,
              const string16& old_text,
              size_t old_text_start,
              bool backward,
              const string16& new_text,
              size_t new_text_start)
      : Edit(REPLACE_EDIT, mergeable,
             old_text,
             old_text_start,
             backward,
             new_text,
             new_text_start) {
  }

  // Edit implementation.
  virtual bool DoMerge(Edit* edit) OVERRIDE {
    if (edit->type() == DELETE_EDIT ||
        new_text_end() != edit->old_text_start_ ||
        edit->old_text_start_ != edit->new_text_start_)
      return false;
    old_text_ += edit->old_text_;
    new_text_ += edit->new_text_;
    return true;
  }
};

class DeleteEdit : public Edit {
 public:
  DeleteEdit(bool mergeable,
             const string16& text,
             size_t text_start,
             bool backward)
      : Edit(DELETE_EDIT, mergeable,
             text,
             text_start,
             backward,
             string16(),
             text_start) {
  }

  // Edit implementation.
  virtual bool DoMerge(Edit* edit) OVERRIDE {
    if (edit->type() != DELETE_EDIT)
      return false;

    if (delete_backward_) {
      // backspace can be merged only with backspace at the
      // same position.
      if (!edit->delete_backward_ || old_text_start_ != edit->old_text_end())
        return false;
      old_text_start_ = edit->old_text_start_;
      old_text_ = edit->old_text_ + old_text_;
    } else {
      // delete can be merged only with delete at the same
      // position.
      if (edit->delete_backward_ || old_text_start_ != edit->old_text_start_)
        return false;
      old_text_ += edit->old_text_;
    }
    return true;
  }
};

}  // namespace internal

using internal::Edit;
using internal::DeleteEdit;
using internal::InsertEdit;
using internal::ReplaceEdit;

/////////////////////////////////////////////////////////////////
// TextfieldViewsModel: public

TextfieldViewsModel::Delegate::~Delegate() {
}

TextfieldViewsModel::TextfieldViewsModel(Delegate* delegate)
    : delegate_(delegate),
      cursor_pos_(0),
      selection_start_(0),
      composition_start_(0),
      composition_end_(0),
      is_password_(false),
      current_edit_(edit_history_.end()) {
}

TextfieldViewsModel::~TextfieldViewsModel() {
  ClearEditHistory();
}

void TextfieldViewsModel::GetFragments(TextFragments* fragments) const {
  DCHECK(fragments);
  fragments->clear();
  if (HasCompositionText()) {
    if (composition_start_)
      fragments->push_back(TextFragment(0, composition_start_, false, false));

    size_t selection_start = std::min(selection_start_, cursor_pos_);
    size_t selection_end = std::max(selection_start_, cursor_pos_);
    size_t last_end = composition_start_;
    for (ui::CompositionUnderlines::const_iterator i =
         composition_underlines_.begin();
         i != composition_underlines_.end(); ++i) {
      size_t fragment_start =
          std::min(i->start_offset, i->end_offset) + composition_start_;
      size_t fragment_end =
          std::max(i->start_offset, i->end_offset) + composition_start_;

      fragment_start = std::max(last_end, fragment_start);
      fragment_end = std::min(fragment_end, composition_end_);

      if (fragment_start >= fragment_end)
        break;

      // If there is no selection, then just add a text fragment with underline.
      if (selection_start == selection_end) {
        if (last_end < fragment_start) {
          fragments->push_back(
              TextFragment(last_end, fragment_start, false, false));
        }
        fragments->push_back(
            TextFragment(fragment_start, fragment_end, false, true));
        last_end = fragment_end;
        continue;
      }

      size_t end = std::min(fragment_start, selection_start);
      if (last_end < end)
        fragments->push_back(TextFragment(last_end, end, false, false));

      last_end = fragment_end;

      if (selection_start < fragment_start) {
        end = std::min(selection_end, fragment_start);
        fragments->push_back(TextFragment(selection_start, end, true, false));
        selection_start = end;
      } else if (selection_start > fragment_start) {
        end = std::min(selection_start, fragment_end);
        fragments->push_back(TextFragment(fragment_start, end, false, true));
        fragment_start = end;
        if (fragment_start == fragment_end)
          continue;
      }

      if (fragment_start < selection_end) {
        DCHECK_EQ(selection_start, fragment_start);
        end = std::min(fragment_end, selection_end);
        fragments->push_back(TextFragment(fragment_start, end, true, true));
        fragment_start = end;
        selection_start = end;
        if (fragment_start == fragment_end)
          continue;
      }

      DCHECK_LT(fragment_start, fragment_end);
      fragments->push_back(
          TextFragment(fragment_start, fragment_end, false, true));
    }

    if (last_end < composition_end_) {
      if (selection_start < selection_end) {
        DCHECK_LE(last_end, selection_start);
        if (last_end < selection_start) {
          fragments->push_back(
              TextFragment(last_end, selection_start, false, false));
        }
        fragments->push_back(
            TextFragment(selection_start, selection_end, true, false));
        if (selection_end < composition_end_) {
          fragments->push_back(
              TextFragment(selection_end, composition_end_, false, false));
        }
      } else {
        fragments->push_back(
            TextFragment(last_end, composition_end_, false, false));
      }
    }

    size_t len = text_.length();
    if (composition_end_ < len)
      fragments->push_back(TextFragment(composition_end_, len, false, false));
  } else if (HasSelection()) {
    size_t start = std::min(selection_start_, cursor_pos_);
    size_t end = std::max(selection_start_, cursor_pos_);
    if (start)
      fragments->push_back(TextFragment(0, start, false, false));
    fragments->push_back(TextFragment(start, end, true, false));
    size_t len = text_.length();
    if (end != len)
      fragments->push_back(TextFragment(end, len, false, false));
  } else {
    fragments->push_back(TextFragment(0, text_.length(), false, false));
  }
}

bool TextfieldViewsModel::SetText(const string16& text) {
  bool changed = false;
  if (HasCompositionText()) {
    ConfirmCompositionText();
    changed = true;
  }
  if (text_ != text) {
    if (changed) // no need to remember composition.
      Undo();
    SelectAll();
    InsertTextInternal(text, false);
    cursor_pos_ = 0;
  }
  ClearSelection();
  return changed;
}

void TextfieldViewsModel::Append(const string16& text) {
  if (HasCompositionText())
    ConfirmCompositionText();
  size_t save = cursor_pos_;
  MoveCursorToEnd(false);
  InsertText(text);
  cursor_pos_ = save;
  ClearSelection();
}

bool TextfieldViewsModel::Delete() {
  if (HasCompositionText()) {
    // No undo/redo for composition text.
    ClearCompositionText();
    return true;
  }
  if (HasSelection()) {
    DeleteSelection();
    return true;
  }
  if (text_.length() > cursor_pos_) {
    ExecuteAndRecordDelete(cursor_pos_, cursor_pos_ + 1, true);
    return true;
  }
  return false;
}

bool TextfieldViewsModel::Backspace() {
  if (HasCompositionText()) {
    // No undo/redo for composition text.
    ClearCompositionText();
    return true;
  }
  if (HasSelection()) {
    DeleteSelection();
    return true;
  }
  if (cursor_pos_ > 0) {
    ExecuteAndRecordDelete(cursor_pos_, cursor_pos_ - 1, true);
    return true;
  }
  return false;
}

void TextfieldViewsModel::MoveCursorLeft(bool select) {
  if (HasCompositionText())
    ConfirmCompositionText();
  // TODO(oshima): support BIDI
  if (select) {
    if (cursor_pos_ > 0)
      cursor_pos_--;
  } else {
    if (HasSelection())
      cursor_pos_ = std::min(cursor_pos_, selection_start_);
    else if (cursor_pos_ > 0)
      cursor_pos_--;
    ClearSelection();
  }
}

void TextfieldViewsModel::MoveCursorRight(bool select) {
  if (HasCompositionText())
    ConfirmCompositionText();
  // TODO(oshima): support BIDI
  if (select) {
    cursor_pos_ = std::min(text_.length(),  cursor_pos_ + 1);
  } else {
    if  (HasSelection())
      cursor_pos_ = std::max(cursor_pos_, selection_start_);
    else
      cursor_pos_ = std::min(text_.length(),  cursor_pos_ + 1);
    ClearSelection();
  }
}

void TextfieldViewsModel::MoveCursorToPreviousWord(bool select) {
  if (HasCompositionText())
    ConfirmCompositionText();
  // Notes: We always iterate words from the begining.
  // This is probably fast enough for our usage, but we may
  // want to modify WordIterator so that it can start from the
  // middle of string and advance backwards.
  base::i18n::BreakIterator iter(&text_, base::i18n::BreakIterator::BREAK_WORD);
  bool success = iter.Init();
  DCHECK(success);
  if (!success)
    return;
  int last = 0;
  while (iter.Advance()) {
    if (iter.IsWord()) {
      size_t begin = iter.pos() - iter.GetString().length();
      if (begin == cursor_pos_) {
        // The cursor is at the beginning of a word.
        // Move to previous word.
        break;
      } else if(iter.pos() >= cursor_pos_) {
        // The cursor is in the middle or at the end of a word.
        // Move to the top of current word.
        last = begin;
        break;
      } else {
        last = iter.pos() - iter.GetString().length();
      }
    }
  }

  cursor_pos_ = last;
  if (!select)
    ClearSelection();
}

void TextfieldViewsModel::MoveCursorToNextWord(bool select) {
  if (HasCompositionText())
    ConfirmCompositionText();
  base::i18n::BreakIterator iter(&text_, base::i18n::BreakIterator::BREAK_WORD);
  bool success = iter.Init();
  DCHECK(success);
  if (!success)
    return;
  size_t pos = 0;
  while (iter.Advance()) {
    pos = iter.pos();
    if (iter.IsWord() && pos > cursor_pos_) {
      break;
    }
  }
  cursor_pos_ = pos;
  if (!select)
    ClearSelection();
}

void TextfieldViewsModel::MoveCursorToHome(bool select) {
  MoveCursorTo(0, select);
}

void TextfieldViewsModel::MoveCursorToEnd(bool select) {
  MoveCursorTo(text_.length(), select);
}

bool TextfieldViewsModel::MoveCursorTo(size_t pos, bool select) {
  if (HasCompositionText())
    ConfirmCompositionText();
  bool changed = cursor_pos_ != pos || select != HasSelection();
  cursor_pos_ = pos;
  if (!select)
    ClearSelection();
  return changed;
}

gfx::Rect TextfieldViewsModel::GetCursorBounds(const gfx::Font& font) const {
  string16 text = GetVisibleText();
  int x = font.GetStringWidth(text.substr(0U, cursor_pos_));
  int h = font.GetHeight();
  DCHECK(x >= 0);
  if (text.length() == cursor_pos_) {
    return gfx::Rect(x, 0, 0, h);
  } else {
    int x_end = font.GetStringWidth(text.substr(0U, cursor_pos_ + 1U));
    return gfx::Rect(x, 0, x_end - x, h);
  }
}

string16 TextfieldViewsModel::GetSelectedText() const {
  return text_.substr(
      std::min(cursor_pos_, selection_start_),
      std::abs(static_cast<long>(cursor_pos_ - selection_start_)));
}

void TextfieldViewsModel::GetSelectedRange(ui::Range* range) const {
  *range = ui::Range(selection_start_, cursor_pos_);
}

void TextfieldViewsModel::SelectRange(const ui::Range& range) {
  if (HasCompositionText())
    ConfirmCompositionText();
  selection_start_ = GetSafePosition(range.start());
  cursor_pos_ = GetSafePosition(range.end());
}

void TextfieldViewsModel::SelectAll() {
  if (HasCompositionText())
    ConfirmCompositionText();
  // SelectAll selects towards the end.
  cursor_pos_ = text_.length();
  selection_start_ = 0;
}

void TextfieldViewsModel::SelectWord() {
  if (HasCompositionText())
    ConfirmCompositionText();
  // First we setup selection_start_ and cursor_pos_. There are so many cases
  // because we try to emulate what select-word looks like in a gtk textfield.
  // See associated testcase for different cases.
  if (cursor_pos_ > 0 && cursor_pos_ < text_.length()) {
    if (isalnum(text_[cursor_pos_])) {
      selection_start_ = cursor_pos_;
      cursor_pos_++;
    } else
      selection_start_ = cursor_pos_ - 1;
  } else if (cursor_pos_ == 0) {
    selection_start_ = cursor_pos_;
    if (text_.length() > 0)
      cursor_pos_++;
  } else {
    selection_start_ = cursor_pos_ - 1;
  }

  // Now we move selection_start_ to beginning of selection. Selection boundary
  // is defined as the position where we have alpha-num character on one side
  // and non-alpha-num char on the other side.
  for (; selection_start_ > 0; selection_start_--) {
    if (IsPositionAtWordSelectionBoundary(selection_start_))
      break;
  }

  // Now we move cursor_pos_ to end of selection. Selection boundary
  // is defined as the position where we have alpha-num character on one side
  // and non-alpha-num char on the other side.
  for (; cursor_pos_ < text_.length(); cursor_pos_++) {
    if (IsPositionAtWordSelectionBoundary(cursor_pos_))
      break;
  }
}

void TextfieldViewsModel::ClearSelection() {
  if (HasCompositionText())
    ConfirmCompositionText();
  selection_start_ = cursor_pos_;
}

bool TextfieldViewsModel::CanUndo() {
  return edit_history_.size() && current_edit_ != edit_history_.end();
}

bool TextfieldViewsModel::CanRedo() {
  if (!edit_history_.size())
    return false;
  // There is no redo iff the current edit is the last element
  // in the history.
  EditHistory::iterator iter = current_edit_;
  return iter == edit_history_.end() || // at the top.
      ++iter != edit_history_.end();
}

bool TextfieldViewsModel::Undo() {
  if (!CanUndo())
    return false;
  DCHECK(!HasCompositionText());
  if (HasCompositionText())  // safe guard for release build.
    ClearCompositionText();

  string16 old = text_;
  (*current_edit_)->Commit();
  (*current_edit_)->Undo(this);

  if (current_edit_ == edit_history_.begin())
    current_edit_ = edit_history_.end();
  else
    current_edit_--;
  return old != text_;
}

bool TextfieldViewsModel::Redo() {
  if (!CanRedo())
    return false;
  DCHECK(!HasCompositionText());
  if (HasCompositionText()) // safe guard for release build.
    ClearCompositionText();

  if (current_edit_ == edit_history_.end())
    current_edit_ = edit_history_.begin();
  else
    current_edit_ ++;
  string16 old = text_;
  (*current_edit_)->Redo(this);
  return old != text_;
}

bool TextfieldViewsModel::Cut() {
  if (!HasCompositionText() && HasSelection()) {
    ui::ScopedClipboardWriter(views::ViewsDelegate::views_delegate
        ->GetClipboard()).WriteText(GetSelectedText());
    DeleteSelection();
    return true;
  }
  return false;
}

void TextfieldViewsModel::Copy() {
  if (!HasCompositionText() && HasSelection()) {
    ui::ScopedClipboardWriter(views::ViewsDelegate::views_delegate
        ->GetClipboard()).WriteText(GetSelectedText());
  }
}

bool TextfieldViewsModel::Paste() {
  string16 result;
  views::ViewsDelegate::views_delegate->GetClipboard()
      ->ReadText(ui::Clipboard::BUFFER_STANDARD, &result);
  if (!result.empty()) {
    InsertTextInternal(result, false);
    return true;
  }
  return false;
}

bool TextfieldViewsModel::HasSelection() const {
  return selection_start_ != cursor_pos_;
}

void TextfieldViewsModel::DeleteSelection() {
  DCHECK(!HasCompositionText());
  DCHECK(HasSelection());
  ExecuteAndRecordDelete(selection_start_, cursor_pos_, false);
}

void TextfieldViewsModel::DeleteSelectionAndInsertTextAt(
    const string16& text, size_t position) {
  if (HasCompositionText())
    ClearCompositionText();
  ExecuteAndRecordReplaceAt(text, position, false);
}

string16 TextfieldViewsModel::GetTextFromRange(const ui::Range& range) const {
  if (range.IsValid() && range.GetMin() < text_.length())
    return text_.substr(range.GetMin(), range.length());
  return string16();
}

void TextfieldViewsModel::GetTextRange(ui::Range* range) const {
  *range = ui::Range(0, text_.length());
}

void TextfieldViewsModel::SetCompositionText(
    const ui::CompositionText& composition) {
  if (HasCompositionText())
    ClearCompositionText();
  else if (HasSelection())
    DeleteSelection();

  if (composition.text.empty())
    return;

  size_t length = composition.text.length();
  text_.insert(cursor_pos_, composition.text);
  composition_start_ = cursor_pos_;
  composition_end_ = composition_start_ + length;
  composition_underlines_ = composition.underlines;

  if (composition.selection.IsValid()) {
    selection_start_ =
        std::min(composition_start_ + composition.selection.start(),
                 composition_end_);
    cursor_pos_ =
        std::min(composition_start_ + composition.selection.end(),
                 composition_end_);
  } else {
    cursor_pos_ = composition_end_;
    ClearSelection();
  }
}

void TextfieldViewsModel::ConfirmCompositionText() {
  DCHECK(HasCompositionText());
  string16 new_text =
      text_.substr(composition_start_, composition_end_ - composition_start_);
  // TODO(oshima): current behavior on ChromeOS is a bit weird and not
  // sure exactly how this should work. Find out and fix if necessary.
  AddOrMergeEditHistory(new InsertEdit(false, new_text, composition_start_));
  cursor_pos_ = composition_end_;
  composition_start_ = composition_end_ = string16::npos;
  composition_underlines_.clear();
  ClearSelection();
  if (delegate_)
    delegate_->OnCompositionTextConfirmedOrCleared();
}

void TextfieldViewsModel::ClearCompositionText() {
  DCHECK(HasCompositionText());
  text_.erase(composition_start_, composition_end_ - composition_start_);
  cursor_pos_ = composition_start_;
  composition_start_ = composition_end_ = string16::npos;
  composition_underlines_.clear();
  ClearSelection();
  if (delegate_)
    delegate_->OnCompositionTextConfirmedOrCleared();
}

void TextfieldViewsModel::GetCompositionTextRange(ui::Range* range) const {
  if (HasCompositionText())
    *range = ui::Range(composition_start_, composition_end_);
  else
    *range = ui::Range::InvalidRange();
}

bool TextfieldViewsModel::HasCompositionText() const {
  return composition_start_ != composition_end_;
}

/////////////////////////////////////////////////////////////////
// TextfieldViewsModel: private

string16 TextfieldViewsModel::GetVisibleText(size_t begin, size_t end) const {
  DCHECK(end >= begin);
  if (is_password_)
    return string16(end - begin, '*');
  return text_.substr(begin, end - begin);
}

bool TextfieldViewsModel::IsPositionAtWordSelectionBoundary(size_t pos) {
  return (isalnum(text_[pos - 1]) && !isalnum(text_[pos])) ||
      (!isalnum(text_[pos - 1]) && isalnum(text_[pos]));
}

size_t TextfieldViewsModel::GetSafePosition(size_t position) const {
  if (position > text_.length()) {
    return text_.length();
  }
  return position;
}

void TextfieldViewsModel::InsertTextInternal(const string16& text,
                                             bool mergeable) {
  if (HasCompositionText()) {
    ClearCompositionText();
    ExecuteAndRecordInsert(text, mergeable);
  } else if (HasSelection()) {
    ExecuteAndRecordReplace(text, mergeable);
  } else {
    ExecuteAndRecordInsert(text, mergeable);
  }
}

void TextfieldViewsModel::ReplaceTextInternal(const string16& text,
                                              bool mergeable) {
  if (HasCompositionText())
    ClearCompositionText();
  else if (!HasSelection())
    SelectRange(ui::Range(cursor_pos_ + text.length(), cursor_pos_));
  // Edit history is recorded in InsertText.
  InsertTextInternal(text, mergeable);
}

void TextfieldViewsModel::ClearEditHistory() {
  STLDeleteContainerPointers(edit_history_.begin(),
                             edit_history_.end());
  edit_history_.clear();
  current_edit_ = edit_history_.end();
}

void TextfieldViewsModel::ClearRedoHistory() {
  if (edit_history_.begin() == edit_history_.end())
    return;
  if (current_edit_ == edit_history_.end()) {
    ClearEditHistory();
    return;
  }
  EditHistory::iterator delete_start = current_edit_;
  delete_start++;
  STLDeleteContainerPointers(delete_start,
                             edit_history_.end());
  edit_history_.erase(delete_start, edit_history_.end());
}

void TextfieldViewsModel::ExecuteAndRecordDelete(size_t from,
                                                 size_t to,
                                                 bool mergeable) {
  size_t old_text_start = std::min(from, to);
  const string16 text = text_.substr(old_text_start,
                                     std::abs(static_cast<long>(from - to)));
  Edit* edit = new DeleteEdit(mergeable,
                              text,
                              old_text_start,
                              (from > to));
  bool delete_edit = AddOrMergeEditHistory(edit);
  edit->Redo(this);
  if (delete_edit)
    delete edit;
}

void TextfieldViewsModel::ExecuteAndRecordReplace(const string16& text,
                                                  bool mergeable) {
  size_t at = std::min(cursor_pos_, selection_start_);
  ExecuteAndRecordReplaceAt(text, at, mergeable);
}

void TextfieldViewsModel::ExecuteAndRecordReplaceAt(const string16& text,
                                                    size_t at,
                                                    bool mergeable) {
  size_t text_start = std::min(cursor_pos_, selection_start_);
  Edit* edit = new ReplaceEdit(mergeable,
                               GetSelectedText(),
                               text_start,
                               selection_start_ > cursor_pos_,
                               text,
                               at);
  bool delete_edit = AddOrMergeEditHistory(edit);
  edit->Redo(this);
  if (delete_edit)
    delete edit;
}

void TextfieldViewsModel::ExecuteAndRecordInsert(const string16& text,
                                                 bool mergeable) {
  Edit* edit = new InsertEdit(mergeable, text, cursor_pos_);
  bool delete_edit = AddOrMergeEditHistory(edit);
  edit->Redo(this);
  if (delete_edit)
    delete edit;
}

bool TextfieldViewsModel::AddOrMergeEditHistory(Edit* edit) {
  ClearRedoHistory();

  if (current_edit_ != edit_history_.end() && (*current_edit_)->Merge(edit)) {
    // If a current edit exists and has been merged with a new edit,
    // don't add to the history, and return true to delete |edit| after
    // redo.
    return true;
  }
  edit_history_.push_back(edit);
  if (current_edit_ == edit_history_.end()) {
    // If there is no redoable edit, this is the 1st edit because
    // RedoHistory has been already deleted.
    DCHECK_EQ(1u, edit_history_.size());
    current_edit_ = edit_history_.begin();
  } else {
    current_edit_++;
  }
  return false;
}

void TextfieldViewsModel::ModifyText(size_t delete_from,
                                     size_t delete_to,
                                     const string16& new_text,
                                     size_t new_text_insert_at,
                                     size_t new_cursor_pos) {
  DCHECK_LE(delete_from, delete_to);
  if (delete_from != delete_to)
    text_.erase(delete_from, delete_to - delete_from);
  if (!new_text.empty())
    text_.insert(new_text_insert_at, new_text);
  cursor_pos_ = new_cursor_pos;
  ClearSelection();
  // TODO(oshima): mac selects the text that is just undone (but gtk doesn't).
  // This looks fine feature and we may want to do the same.
}

}  // namespace views