File: input_method_engine.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1125 lines) | stat: -rw-r--r-- 36,680 bytes parent folder | download | duplicates (6)
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 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/input_method/input_method_engine.h"

#include <algorithm>
#include <memory>
#include <string_view>
#include <utility>

#include "ash/constants/ash_pref_names.h"
#include "ash/constants/notifier_catalogs.h"
#include "ash/keyboard/ui/keyboard_ui_controller.h"
#include "ash/public/cpp/system/anchored_nudge_manager.h"
#include "base/check.h"
#include "base/i18n/char_iterator.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/ash/input_method/input_method_menu_item.h"
#include "chrome/browser/ui/ash/input_method/input_method_menu_manager.h"
#include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/ime/ash/component_extension_ime_manager.h"
#include "ui/base/ime/ash/extension_ime_util.h"
#include "ui/base/ime/ash/ime_bridge.h"
#include "ui/base/ime/ash/ime_keymap.h"
#include "ui/base/ime/constants.h"
#include "ui/base/ime/text_input_flags.h"
#include "ui/base/ui_base_features.h"
#include "ui/events/event_sink.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"

namespace ash {
namespace input_method {

namespace {

const char kErrorNotActive[] = "IME is not active.";
const char kErrorWrongContext[] = "Context is not active.";
const char kErrorInvalidValue[] = "Argument '%s' with value '%d' is not valid.";
const char kCandidateNotFound[] = "Candidate not found.";
const char kSuggestionNotFound[] = "Suggestion not found.";

// The default entry number of a page in CandidateWindowProperty.
const int kDefaultPageSize = 9;

bool IsUint32Value(int i) {
  return 0 <= i && i <= std::numeric_limits<uint32_t>::max();
}

int GetUtf16Size(std::u16string& text) {
  int utf16_size = 0;
  for (base::i18n::UTF16CharIterator char_iterator(text); !char_iterator.end();
       char_iterator.Advance()) {
    ++utf16_size;
  }
  return utf16_size;
}

}  // namespace

InputMethodEngine::Candidate::Candidate() = default;

InputMethodEngine::Candidate::Candidate(const Candidate& other) = default;

InputMethodEngine::Candidate::~Candidate() = default;

// When the default values are changed, please modify
// CandidateWindow::CandidateWindowProperty defined in chromeos/ime/ too.
InputMethodEngine::CandidateWindowProperty::CandidateWindowProperty()
    : page_size(kDefaultPageSize),
      is_cursor_visible(true),
      is_vertical(false),
      show_window_at_composition(false),
      is_auxiliary_text_visible(false) {}

InputMethodEngine::CandidateWindowProperty::~CandidateWindowProperty() =
    default;
InputMethodEngine::CandidateWindowProperty::CandidateWindowProperty(
    const CandidateWindowProperty& other) = default;

InputMethodEngine::InputMethodEngine()
    : current_input_type_(ui::TEXT_INPUT_TYPE_NONE),
      context_id_(0),
      next_context_id_(1),
      profile_(nullptr),
      composition_changed_(false),
      commit_text_changed_(false),
      pref_change_registrar_(nullptr),
      // This is safe because the callback does not outlive
      // screen_projection_change_monitor_, which is a member of this class.
      screen_projection_change_monitor_(
          base::BindRepeating(&InputMethodEngine::OnScreenProjectionChanged,
                              base::Unretained(this))) {}

InputMethodEngine::~InputMethodEngine() = default;

void InputMethodEngine::Initialize(
    std::unique_ptr<InputMethodEngineObserver> observer,
    const char* extension_id,
    Profile* profile) {
  DCHECK(observer) << "Observer must not be null.";

  // TODO(komatsu): It is probably better to set observer out of Initialize.
  observer_ = std::move(observer);
  extension_id_ = extension_id;
  profile_ = profile;

  if (profile_ && profile->GetPrefs()) {
    profile_observation_.Observe(profile);
    input_method_settings_snapshot_ =
        profile->GetPrefs()
            ->GetDict(::prefs::kLanguageInputMethodSpecificSettings)
            .Clone();

    pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>();
    pref_change_registrar_->Init(profile->GetPrefs());
    pref_change_registrar_->Add(
        ::prefs::kLanguageInputMethodSpecificSettings,
        base::BindRepeating(&InputMethodEngine::OnInputMethodOptionsChanged,
                            base::Unretained(this)));
    pref_change_registrar_->Add(
        ash::prefs::kLongPressDiacriticsEnabled,
        base::BindRepeating(&InputMethodEngine::DiacriticsSettingsChanged,
                            base::Unretained(this)));
  }
}

void InputMethodEngine::DiacriticsSettingsChanged() {
  const bool new_value =
      profile_->GetPrefs()->GetBoolean(ash::prefs::kLongPressDiacriticsEnabled);
  if (!new_value) {
    AnchoredNudgeManager::Get()->MaybeRecordNudgeAction(
        NudgeCatalogName::kDisableDiacritics);
  }
}

const std::string& InputMethodEngine::GetActiveComponentId() const {
  return active_component_id_;
}

bool InputMethodEngine::ClearComposition(int context_id, std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = base::StringPrintf(
        "%s request context id = %d, current context id = %d",
        kErrorWrongContext, context_id, context_id_);
    return false;
  }

  UpdateComposition(ui::CompositionText(), 0, false);
  return true;
}

bool InputMethodEngine::CommitText(int context_id,
                                   const std::u16string& text,
                                   std::string* error) {
  if (!IsActive()) {
    // TODO: Commit the text anyways.
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = base::StringPrintf(
        "%s request context id = %d, current context id = %d",
        kErrorWrongContext, context_id, context_id_);
    return false;
  }

  CommitTextToInputContext(context_id, text);
  return true;
}

void InputMethodEngine::ConfirmComposition(bool reset_engine) {
  TextInputTarget* input_context = IMEBridge::Get()->GetInputContextHandler();
  if (input_context) {
    input_context->ConfirmComposition(reset_engine);
  }
}

bool InputMethodEngine::DeleteSurroundingText(int context_id,
                                              int offset,
                                              size_t number_of_chars,
                                              std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = base::StringPrintf(
        "%s request context id = %d, current context id = %d",
        kErrorWrongContext, context_id, context_id_);
    return false;
  }

  // TODO(nona): Return false if there is ongoing composition.

  TextInputTarget* input_context = IMEBridge::Get()->GetInputContextHandler();
  if (input_context) {
    const uint32_t before =
        offset >= 0 ? 0U : static_cast<uint32_t>(-1 * offset);
    input_context->DeleteSurroundingText(before, number_of_chars - before);
  }

  return true;
}

base::expected<void, InputMethodEngine::Error>
InputMethodEngine::ReplaceSurroundingText(
    int context_id,
    int length_before_selection,
    int length_after_selection,
    const std::u16string_view replacement_text) {
  if (!IsActive()) {
    return base::unexpected(Error::kInputMethodNotActive);
  }
  if (context_id != context_id_ || context_id_ == -1) {
    return base::unexpected(Error::kIncorrectContextId);
  }

  if (TextInputTarget* input_context =
          IMEBridge::Get()->GetInputContextHandler()) {
    input_context->ReplaceSurroundingText(
        length_before_selection, length_after_selection, replacement_text);
  }

  return base::ok();
}

bool InputMethodEngine::FinishComposingText(int context_id,
                                            std::string* error) {
  if (context_id != context_id_ || context_id_ == -1) {
    *error = base::StringPrintf(
        "%s request context id = %d, current context id = %d",
        kErrorWrongContext, context_id, context_id_);
    return false;
  }
  ConfirmComposition(/* reset_engine */ false);
  return true;
}

bool InputMethodEngine::SendKeyEvents(int context_id,
                                      const std::vector<ui::KeyEvent>& events,
                                      std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  // context_id  ==  0, means sending key events to non-input field.
  // context_id_ == -1, means the focus is not in an input field.
  if ((context_id != 0 && (context_id != context_id_ || context_id_ == -1))) {
    *error = base::StringPrintf(
        "%s request context id = %d, current context id = %d",
        kErrorWrongContext, context_id, context_id_);
    return false;
  }

  for (const auto& event : events) {
    ui::KeyEvent event_copy = event;

    // Marks the simulated key event is from the Virtual Keyboard.
    ui::Event::Properties properties;
    properties[ui::kPropertyFromVK] =
        std::vector<uint8_t>(ui::kPropertyFromVKSize);
    properties[ui::kPropertyFromVK][ui::kPropertyFromVKIsMirroringIndex] =
        static_cast<uint8_t>(screen_projection_change_monitor_.is_mirroring());
    event_copy.SetProperties(properties);

    TextInputTarget* input_context = IMEBridge::Get()->GetInputContextHandler();
    if (input_context) {
      input_context->SendKeyEvent(&event_copy);
      continue;
    }

    *error = kErrorWrongContext;
    return false;
  }

  return true;
}

bool InputMethodEngine::SetComposition(int context_id,
                                       const char* text,
                                       int selection_start,
                                       int selection_end,
                                       int cursor,
                                       const std::vector<SegmentInfo>& segments,
                                       std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }

  if (context_id != context_id_ || context_id_ == -1) {
    *error = base::StringPrintf(
        "%s request context id = %d, current context id = %d",
        kErrorWrongContext, context_id, context_id_);
    return false;
  }

  if (selection_start < 0 || selection_end < 0 || cursor < 0) {
    *error = base::StringPrintf(
        "%s request selection start = %d, selection end = %d, cursor  =  %d",
        "At least 1 arg is negative, which is invalid.", selection_start,
        selection_end, cursor);
    return false;
  }

  ui::CompositionText composition_text;
  composition_text.text = base::UTF8ToUTF16(text);
  // Check the length of the text.
  int utf16_length = GetUtf16Size(composition_text.text);
  if (selection_start > utf16_length || selection_end > utf16_length) {
    *error = base::StringPrintf(
        "%s request selection start = %d, selection end = %d, cursor  =  %d",
        "At least 1 length is above the length of the text, which is invalid.",
        selection_start, selection_end, cursor);
    return false;
  }
  composition_text.selection.set_start(selection_start);
  composition_text.selection.set_end(selection_end);

  // TODO: Add support for displaying selected text in the composition string.
  for (auto segment : segments) {
    ui::ImeTextSpan ime_text_span;

    ime_text_span.underline_color = SK_ColorTRANSPARENT;
    switch (segment.style) {
      case SEGMENT_STYLE_UNDERLINE:
        ime_text_span.thickness = ui::ImeTextSpan::Thickness::kThin;
        break;
      case SEGMENT_STYLE_DOUBLE_UNDERLINE:
        ime_text_span.thickness = ui::ImeTextSpan::Thickness::kThick;
        break;
      case SEGMENT_STYLE_NO_UNDERLINE:
        ime_text_span.thickness = ui::ImeTextSpan::Thickness::kNone;
        break;
      default:
        continue;
    }

    ime_text_span.start_offset = segment.start;
    ime_text_span.end_offset = segment.end;
    composition_text.ime_text_spans.push_back(ime_text_span);
  }

  // TODO(nona): Makes focus out mode configuable, if necessary.
  UpdateComposition(composition_text, cursor, true);
  return true;
}

bool InputMethodEngine::SetCompositionRange(
    int context_id,
    int selection_before,
    int selection_after,
    const std::vector<SegmentInfo>& segments,
    std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = base::StringPrintf(
        "%s request context id = %d, current context id = %d",
        kErrorWrongContext, context_id, context_id_);
    return false;
  }

  // When there is composition text, commit it to the text field first before
  // changing the composition range.
  ConfirmComposition(/* reset_engine */ false);

  std::vector<ui::ImeTextSpan> text_spans;
  for (const auto& segment : segments) {
    ui::ImeTextSpan text_span;

    text_span.underline_color = SK_ColorTRANSPARENT;
    switch (segment.style) {
      case SEGMENT_STYLE_UNDERLINE:
        text_span.thickness = ui::ImeTextSpan::Thickness::kThin;
        break;
      case SEGMENT_STYLE_DOUBLE_UNDERLINE:
        text_span.thickness = ui::ImeTextSpan::Thickness::kThick;
        break;
      case SEGMENT_STYLE_NO_UNDERLINE:
        text_span.thickness = ui::ImeTextSpan::Thickness::kNone;
        break;
    }

    text_span.start_offset = segment.start;
    text_span.end_offset = segment.end;
    text_spans.push_back(text_span);
  }
  if (!IsUint32Value(selection_before)) {
    *error = base::StringPrintf(kErrorInvalidValue, "selection_before",
                                selection_before);
    return false;
  }
  if (!IsUint32Value(selection_after)) {
    *error = base::StringPrintf(kErrorInvalidValue, "selection_after",
                                selection_after);
    return false;
  }

  TextInputTarget* input_context = IMEBridge::Get()->GetInputContextHandler();
  if (!input_context) {
    return false;
  }

  return input_context->SetCompositionRange(
      static_cast<uint32_t>(selection_before),
      static_cast<uint32_t>(selection_after), text_spans);
}

bool InputMethodEngine::SetComposingRange(
    int context_id,
    int start,
    int end,
    const std::vector<SegmentInfo>& segments,
    std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = base::StringPrintf(
        "%s request context id = %d, current context id = %d",
        kErrorWrongContext, context_id, context_id_);
    return false;
  }

  // When there is composition text, commit it to the text field first before
  // changing the composition range.
  ConfirmComposition(/* reset_engine */ false);

  std::vector<ui::ImeTextSpan> text_spans;
  for (const auto& segment : segments) {
    ui::ImeTextSpan text_span;

    text_span.underline_color = SK_ColorTRANSPARENT;
    switch (segment.style) {
      case SEGMENT_STYLE_UNDERLINE:
        text_span.thickness = ui::ImeTextSpan::Thickness::kThin;
        break;
      case SEGMENT_STYLE_DOUBLE_UNDERLINE:
        text_span.thickness = ui::ImeTextSpan::Thickness::kThick;
        break;
      case SEGMENT_STYLE_NO_UNDERLINE:
        text_span.thickness = ui::ImeTextSpan::Thickness::kNone;
        break;
    }

    text_span.start_offset = segment.start;
    text_span.end_offset = segment.end;
    text_spans.push_back(text_span);
  }
  if (!IsUint32Value(start)) {
    *error = base::StringPrintf(kErrorInvalidValue, "start", start);
    return false;
  }
  if (!IsUint32Value(end)) {
    *error = base::StringPrintf(kErrorInvalidValue, "end", end);
    return false;
  }

  TextInputTarget* input_context = IMEBridge::Get()->GetInputContextHandler();
  if (!input_context) {
    return false;
  }

  return input_context->SetComposingRange(
      static_cast<uint32_t>(start), static_cast<uint32_t>(end), text_spans);
}

void InputMethodEngine::KeyEventHandled(const std::string& extension_id,
                                        const std::string& request_id,
                                        bool handled) {
  // When finish handling key event, take care of the unprocessed commitText
  // and setComposition calls.
  if (commit_text_changed_) {
    CommitTextToInputContext(context_id_, text_);
    text_.clear();
    commit_text_changed_ = false;
  }

  if (composition_changed_) {
    UpdateComposition(composition_, composition_.selection.start(), true);
    composition_ = ui::CompositionText();
    composition_changed_ = false;
  }

  const auto it = pending_key_events_.find(request_id);
  if (it == pending_key_events_.end()) {
    LOG(ERROR) << "Request ID not found: " << request_id;
    return;
  }

  std::move(it->second.callback)
      .Run(handled ? ui::ime::KeyEventHandledState::kHandledByIME
                   : ui::ime::KeyEventHandledState::kNotHandled);
  pending_key_events_.erase(it);
}

std::string InputMethodEngine::AddPendingKeyEvent(
    const std::string& component_id,
    TextInputMethod::KeyEventDoneCallback callback) {
  std::string request_id = base::NumberToString(next_request_id_);
  ++next_request_id_;

  pending_key_events_.emplace(
      request_id, PendingKeyEvent(component_id, std::move(callback)));

  return request_id;
}

void InputMethodEngine::CancelPendingKeyEvents() {
  for (auto& event : pending_key_events_) {
    std::move(event.second.callback)
        .Run(ui::ime::KeyEventHandledState::kNotHandled);
  }
  pending_key_events_.clear();
}

void InputMethodEngine::Focus(
    const TextInputMethod::InputContext& input_context) {
  current_input_type_ = input_context.type;

  if (!IsActive() || current_input_type_ == ui::TEXT_INPUT_TYPE_NONE) {
    return;
  }

  context_id_ = next_context_id_;
  ++next_context_id_;

  observer_->OnFocus(active_component_id_, context_id_, input_context);
}

void InputMethodEngine::Blur() {
  if (!IsActive() || current_input_type_ == ui::TEXT_INPUT_TYPE_NONE) {
    return;
  }

  current_input_type_ = ui::TEXT_INPUT_TYPE_NONE;

  int context_id = context_id_;
  context_id_ = -1;
  observer_->OnBlur(active_component_id_, context_id);
}

void InputMethodEngine::Enable(const std::string& component_id) {
  active_component_id_ = component_id;
  observer_->OnActivate(component_id);
  const TextInputMethod::InputContext& input_context =
      IMEBridge::Get()->GetCurrentInputContext();
  current_input_type_ = input_context.type;
  Focus(input_context);

  InputMethodManager::Get()->GetActiveIMEState()->EnableInputView();
  auto* keyboard_client = ChromeKeyboardControllerClient::Get();
  if (keyboard_client->is_keyboard_enabled()) {
    keyboard_client->ReloadKeyboardIfNeeded();
  }

  // Resets candidate_window_property_ whenever a new component_id (aka
  // engine_id) is enabled.
  candidate_window_property_ = {component_id,
                                InputMethodEngine::CandidateWindowProperty()};

  is_ready_for_testing_ = false;
}

bool InputMethodEngine::IsActive() const {
  return !active_component_id_.empty();
}

void InputMethodEngine::Disable() {
  std::string last_component_id{active_component_id_};
  active_component_id_.clear();
  ConfirmComposition(/* reset_engine */ true);
  observer_->OnDeactivated(last_component_id);
}

void InputMethodEngine::Reset() {
  observer_->OnReset(active_component_id_);
}

void InputMethodEngine::ProcessKeyEvent(const ui::KeyEvent& key_event,
                                        KeyEventDoneCallback callback) {
  if (key_event.IsCommandDown()) {
    std::move(callback).Run(ui::ime::KeyEventHandledState::kNotHandled);
    return;
  }

  // Should not pass key event in password field.
  if (current_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD) {
    // Bind the start time to the callback so that we can calculate the latency
    // when the callback is called.
    observer_->OnKeyEvent(
        active_component_id_, key_event,
        base::BindOnce(
            [](base::Time start, int context_id, int* context_id_ptr,
               KeyEventDoneCallback callback,
               ui::ime::KeyEventHandledState handled_state) {
              // If the input_context has changed, assume the key event is
              // invalid as a precaution.
              if (context_id == *context_id_ptr) {
                std::move(callback).Run(handled_state);
              }
              UMA_HISTOGRAM_TIMES("InputMethod.KeyEventLatency",
                                  base::Time::Now() - start);
            },
            base::Time::Now(), context_id_, &context_id_, std::move(callback)));
  }
}

void InputMethodEngine::SetSurroundingText(const std::u16string& text,
                                           const gfx::Range selection_range,
                                           uint32_t offset_pos) {
  observer_->OnSurroundingTextChanged(active_component_id_, text,
                                      selection_range,
                                      static_cast<int>(offset_pos));
}

void InputMethodEngine::SetCaretBounds(const gfx::Rect& caret_bounds) {
  observer_->OnCaretBoundsChanged(caret_bounds);
}

void InputMethodEngine::PropertyActivate(const std::string& property_name) {
  observer_->OnMenuItemActivated(active_component_id_, property_name);
}

void InputMethodEngine::CandidateClicked(uint32_t index) {
  if (index > candidate_ids_.size()) {
    return;
  }

  // Only left button click is supported at this moment.
  observer_->OnCandidateClicked(active_component_id_, candidate_ids_.at(index),
                                MOUSE_BUTTON_LEFT);
}

void InputMethodEngine::AssistiveWindowButtonClicked(
    const ui::ime::AssistiveWindowButton& button) {
  observer_->OnAssistiveWindowButtonClicked(button);
}

void InputMethodEngine::AssistiveWindowChanged(
    const ash::ime::AssistiveWindow& window) {
  observer_->OnAssistiveWindowChanged(window);
}

ui::VirtualKeyboardController* InputMethodEngine::GetVirtualKeyboardController()
    const {
  // Callers expect a nullptr when the keyboard is disabled. See
  // https://crbug.com/850020.
  if (!keyboard::KeyboardUIController::HasInstance() ||
      !keyboard::KeyboardUIController::Get()->IsEnabled()) {
    return nullptr;
  }
  return keyboard::KeyboardUIController::Get()->virtual_keyboard_controller();
}

bool InputMethodEngine::IsReadyForTesting() {
  return is_ready_for_testing_;
}

void InputMethodEngine::OnSuggestionsChanged(
    const std::vector<std::string>& suggestions) {
  observer_->OnSuggestionsChanged(suggestions);
}

bool InputMethodEngine::SetButtonHighlighted(
    int context_id,
    const ui::ime::AssistiveWindowButton& button,
    bool highlighted,
    std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = kErrorWrongContext;
    return false;
  }
  IMEAssistiveWindowHandlerInterface* aw_handler =
      IMEBridge::Get()->GetAssistiveWindowHandler();
  if (aw_handler) {
    aw_handler->SetButtonHighlighted(button, highlighted);
  }
  return true;
}

void InputMethodEngine::ClickButton(
    const ui::ime::AssistiveWindowButton& button) {
  observer_->OnAssistiveWindowButtonClicked(button);
}

bool InputMethodEngine::AcceptSuggestionCandidate(
    int context_id,
    const std::u16string& suggestion,
    size_t delete_previous_utf16_len,
    std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = kErrorWrongContext;
    return false;
  }

  if (delete_previous_utf16_len) {
    DeleteSurroundingText(context_id_,
                          -static_cast<int>(delete_previous_utf16_len),
                          delete_previous_utf16_len, error);
  }

  CommitText(context_id, suggestion, error);

  IMEAssistiveWindowHandlerInterface* aw_handler =
      IMEBridge::Get()->GetAssistiveWindowHandler();
  if (aw_handler) {
    aw_handler->AcceptSuggestion(suggestion);
  }
  return true;
}

const InputMethodEngine::CandidateWindowProperty&
InputMethodEngine::GetCandidateWindowProperty(const std::string& engine_id) {
  if (candidate_window_property_.first != engine_id) {
    candidate_window_property_ = {engine_id,
                                  InputMethodEngine::CandidateWindowProperty()};
  }
  return candidate_window_property_.second;
}

void InputMethodEngine::SetCandidateWindowProperty(
    const std::string& engine_id,
    const CandidateWindowProperty& property) {
  // Type conversion from InputMethodEngine::CandidateWindowProperty to
  // CandidateWindow::CandidateWindowProperty defined in chromeos/ime/.
  ui::CandidateWindow::CandidateWindowProperty dest_property;
  dest_property.page_size = property.page_size;
  dest_property.is_cursor_visible = property.is_cursor_visible;
  dest_property.is_vertical = property.is_vertical;
  dest_property.show_window_at_composition =
      property.show_window_at_composition;
  dest_property.cursor_position =
      candidate_window_.GetProperty().cursor_position;
  dest_property.auxiliary_text = property.auxiliary_text;
  dest_property.is_auxiliary_text_visible = property.is_auxiliary_text_visible;
  dest_property.current_candidate_index = property.current_candidate_index;
  dest_property.total_candidates = property.total_candidates;
  dest_property.is_user_selecting = candidate_window_.is_user_selecting();

  candidate_window_.SetProperty(dest_property);
  candidate_window_property_ = {engine_id, property};

  if (IsActive()) {
    IMECandidateWindowHandlerInterface* cw_handler =
        IMEBridge::Get()->GetCandidateWindowHandler();
    if (cw_handler) {
      if (window_visible_) {
        cw_handler->UpdateLookupTable(candidate_window_);
      } else {
        cw_handler->HideLookupTable();
      }
    }
  }
}

bool InputMethodEngine::SetCandidateWindowVisible(bool visible,
                                                  std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }

  window_visible_ = visible;
  IMECandidateWindowHandlerInterface* cw_handler =
      IMEBridge::Get()->GetCandidateWindowHandler();
  if (cw_handler) {
    if (window_visible_) {
      cw_handler->UpdateLookupTable(candidate_window_);
    } else {
      cw_handler->HideLookupTable();
    }
  }
  return true;
}

bool InputMethodEngine::SetCandidates(int context_id,
                                      const std::vector<Candidate>& candidates,
                                      std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = kErrorWrongContext;
    return false;
  }

  // TODO: Nested candidates
  candidate_ids_.clear();
  candidate_indexes_.clear();
  candidate_window_.mutable_candidates()->clear();
  for (const auto& candidate : candidates) {
    ui::CandidateWindow::Entry entry;
    entry.value = base::UTF8ToUTF16(candidate.value);
    entry.label = base::UTF8ToUTF16(candidate.label);
    entry.annotation = base::UTF8ToUTF16(candidate.annotation);
    entry.description_title = base::UTF8ToUTF16(candidate.usage.title);
    entry.description_body = base::UTF8ToUTF16(candidate.usage.body);

    // Store a mapping from the user defined ID to the candidate index.
    candidate_indexes_[candidate.id] = candidate_ids_.size();
    candidate_ids_.push_back(candidate.id);

    candidate_window_.mutable_candidates()->push_back(entry);
  }
  candidate_window_.set_is_user_selecting(InferIsUserSelecting(candidates));

  if (IsActive()) {
    IMECandidateWindowHandlerInterface* cw_handler =
        IMEBridge::Get()->GetCandidateWindowHandler();
    if (cw_handler) {
      if (window_visible_) {
        cw_handler->UpdateLookupTable(candidate_window_);
      } else {
        cw_handler->HideLookupTable();
      }
    }
  }
  return true;
}

bool InputMethodEngine::SetCursorPosition(int context_id,
                                          int candidate_id,
                                          std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = kErrorWrongContext;
    return false;
  }

  std::map<int, int>::const_iterator position =
      candidate_indexes_.find(candidate_id);
  if (position == candidate_indexes_.end()) {
    *error = base::StringPrintf("%s candidate id = %d", kCandidateNotFound,
                                candidate_id);
    return false;
  }

  candidate_window_.set_cursor_position(position->second);
  IMECandidateWindowHandlerInterface* cw_handler =
      IMEBridge::Get()->GetCandidateWindowHandler();
  if (cw_handler) {
    if (window_visible_) {
      cw_handler->UpdateLookupTable(candidate_window_);
    } else {
      cw_handler->HideLookupTable();
    }
  }
  return true;
}

bool InputMethodEngine::SetSuggestion(int context_id,
                                      const ui::ime::SuggestionDetails& details,
                                      std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = kErrorWrongContext;
    return false;
  }

  IMEAssistiveWindowHandlerInterface* aw_handler =
      IMEBridge::Get()->GetAssistiveWindowHandler();
  if (aw_handler) {
    aw_handler->ShowSuggestion(details);
  }
  return true;
}

bool InputMethodEngine::DismissSuggestion(int context_id, std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = kErrorWrongContext;
    return false;
  }

  IMEAssistiveWindowHandlerInterface* aw_handler =
      IMEBridge::Get()->GetAssistiveWindowHandler();
  if (aw_handler) {
    aw_handler->HideSuggestion();
  }
  return true;
}

bool InputMethodEngine::AcceptSuggestion(int context_id, std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = kErrorWrongContext;
    return false;
  }

  FinishComposingText(context_id_, error);
  if (!error->empty()) {
    return false;
  }

  IMEAssistiveWindowHandlerInterface* aw_handler =
      IMEBridge::Get()->GetAssistiveWindowHandler();
  if (aw_handler) {
    std::u16string suggestion_text = aw_handler->GetSuggestionText();
    if (suggestion_text.empty()) {
      *error = kSuggestionNotFound;
      return false;
    }
    size_t confirmed_length = aw_handler->GetConfirmedLength();
    if (confirmed_length > 0) {
      DeleteSurroundingText(context_id_, -static_cast<int>(confirmed_length),
                            confirmed_length, error);
    }
    CommitText(context_id_, suggestion_text, error);
    aw_handler->HideSuggestion();
  }
  return true;
}

bool InputMethodEngine::SetAssistiveWindowProperties(
    int context_id,
    const AssistiveWindowProperties& assistive_window,
    std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }
  if (context_id != context_id_ || context_id_ == -1) {
    *error = kErrorWrongContext;
    return false;
  }

  IMEAssistiveWindowHandlerInterface* aw_handler =
      IMEBridge::Get()->GetAssistiveWindowHandler();
  if (aw_handler) {
    aw_handler->SetAssistiveWindowProperties(assistive_window);
  }
  return true;
}

void InputMethodEngine::Announce(const std::u16string& message) {
  IMEAssistiveWindowHandlerInterface* aw_handler =
      IMEBridge::Get()->GetAssistiveWindowHandler();
  if (aw_handler) {
    aw_handler->Announce(message);
  }
}

void InputMethodEngine::OnProfileWillBeDestroyed(Profile* profile) {
  if (profile == profile_) {
    pref_change_registrar_.reset();
    DCHECK(profile_observation_.IsObservingSource(profile_));
    profile_observation_.Reset();
    profile_ = nullptr;
  }
}

bool InputMethodEngine::UpdateMenuItems(
    const std::vector<InputMethodManager::MenuItem>& items,
    std::string* error) {
  if (!IsActive()) {
    *error = kErrorNotActive;
    return false;
  }

  ui::ime::InputMethodMenuItemList menu_item_list;
  for (const auto& item : items) {
    ui::ime::InputMethodMenuItem property;
    MenuItemToProperty(item, &property);
    menu_item_list.push_back(property);
  }

  ui::ime::InputMethodMenuManager::GetInstance()
      ->SetCurrentInputMethodMenuItemList(menu_item_list);

  InputMethodManager::Get()->NotifyImeMenuItemsChanged(active_component_id_,
                                                       items);
  return true;
}

void InputMethodEngine::HideInputView() {
  auto* keyboard_client = ChromeKeyboardControllerClient::Get();
  if (keyboard_client->is_keyboard_enabled()) {
    keyboard_client->HideKeyboard(ash::HideReason::kUser);
  }
}

void InputMethodEngine::OnInputMethodOptionsChanged() {
  const base::Value::Dict& new_settings = profile_->GetPrefs()->GetDict(
      ::prefs::kLanguageInputMethodSpecificSettings);
  const base::Value::Dict& old_settings = input_method_settings_snapshot_;
  for (const auto&& [path, value] : new_settings) {
    if (const base::Value* old_value = old_settings.Find(path)) {
      if (*old_value != value) {
        observer_->OnInputMethodOptionsChanged(path);
      }
    } else {
      observer_->OnInputMethodOptionsChanged(path);
    }
  }
  input_method_settings_snapshot_ = new_settings.Clone();
}

void InputMethodEngine::UpdateComposition(
    const ui::CompositionText& composition_text,
    uint32_t cursor_pos,
    bool is_visible) {
  TextInputTarget* input_context = IMEBridge::Get()->GetInputContextHandler();
  if (input_context) {
    input_context->UpdateCompositionText(composition_text, cursor_pos,
                                         is_visible);
  }
}

void InputMethodEngine::CommitTextToInputContext(int context_id,
                                                 const std::u16string& text) {
  TextInputTarget* input_context = IMEBridge::Get()->GetInputContextHandler();
  if (!input_context) {
    return;
  }

  const bool had_composition_text = input_context->HasCompositionText();
  input_context->CommitText(
      text,
      ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);

  if (had_composition_text) {
    // Records histograms for committed characters with composition text.
    UMA_HISTOGRAM_CUSTOM_COUNTS("InputMethod.CommitLength", text.length(), 1,
                                25, 25);
  }
}

// TODO(uekawa): rename this method to a more reasonable name.
void InputMethodEngine::MenuItemToProperty(
    const InputMethodManager::MenuItem& item,
    ui::ime::InputMethodMenuItem* property) {
  property->key = item.id;

  if (item.modified & MENU_ITEM_MODIFIED_LABEL) {
    property->label = item.label;
  }
  if (item.modified & MENU_ITEM_MODIFIED_CHECKED) {
    property->is_selection_item_checked = item.checked;
  }

  // TODO(nona): Support item.children.
}

void InputMethodEngine::OnScreenProjectionChanged(bool is_projected) {
  if (observer_) {
    observer_->OnScreenProjectionChanged(is_projected);
  }
}

bool InputMethodEngine::InferIsUserSelecting(
    base::span<const Candidate> candidates) {
  if (candidates.empty()) {
    return false;
  }

  // Only infer for Japanese IME.
  if (!active_component_id_.starts_with("nacl_mozc_")) {
    return true;
  }

  const bool any_non_empty_label = std::ranges::any_of(
      candidates,
      [](const Candidate& candidate) { return !candidate.label.empty(); });
  return any_non_empty_label;
}

void InputMethodEngine::NotifyInputMethodExtensionReadyForTesting() {
  is_ready_for_testing_ = true;
}

InputMethodEngine::PendingKeyEvent::PendingKeyEvent(
    const std::string& component_id,
    TextInputMethod::KeyEventDoneCallback callback)
    : component_id(component_id), callback(std::move(callback)) {}

InputMethodEngine::PendingKeyEvent::PendingKeyEvent(PendingKeyEvent&& other) =
    default;

InputMethodEngine::PendingKeyEvent::~PendingKeyEvent() = default;

}  // namespace input_method
}  // namespace ash