File: input_method_manager_impl.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 (1558 lines) | stat: -rw-r--r-- 56,146 bytes parent folder | download | duplicates (5)
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
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

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

#include <stdint.h>

#include <algorithm>
#include <memory>
#include <set>
#include <sstream>
#include <utility>

#include "ash/constants/ash_features.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/hash/hash.h"
#include "base/i18n/string_compare.h"
#include "base/location.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "chrome/browser/ash/input_method/assistive_window_controller.h"
#include "chrome/browser/ash/input_method/candidate_window_controller.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part_ash.h"
#include "chrome/browser/lifetime/termination_notification.h"
#include "chrome/browser/ui/ash/input_method/assistive_delegate.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/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "chromeos/ash/components/language_preferences/language_preferences.h"
#include "components/prefs/pref_service.h"
#include "components/user_manager/user_manager.h"
#include "third_party/icu/source/common/unicode/uloc.h"
#include "third_party/icu/source/i18n/unicode/coll.h"
#include "ui/base/ime/ash/component_extension_ime_manager.h"
#include "ui/base/ime/ash/component_extension_ime_manager_delegate.h"
#include "ui/base/ime/ash/extension_ime_util.h"
#include "ui/base/ime/ash/ime_bridge.h"
#include "ui/base/ime/ash/ime_keyboard.h"
#include "ui/base/ime/ash/ime_keyboard_impl.h"
#include "ui/base/ime/ash/input_method_delegate.h"
#include "ui/base/ui_base_features.h"

namespace ash {
namespace input_method {

namespace {

const char* const kNonPositionalLayouts[] = {
    "de(neo)",    "gb(dvorak)", "tr(f)",       "us(colemak)",
    "us(dvorak)", "us(dvp)",    "us(workman)", "us(workman-intl)",
};

const size_t kNonPositionalLayoutsLength = std::size(kNonPositionalLayouts);

enum InputMethodCategory {
  INPUT_METHOD_CATEGORY_UNKNOWN = 0,
  INPUT_METHOD_CATEGORY_XKB,   // XKB input methods
  INPUT_METHOD_CATEGORY_ZH,    // Chinese input methods
  INPUT_METHOD_CATEGORY_JA,    // Japanese input methods
  INPUT_METHOD_CATEGORY_KO,    // Korean input methods
  INPUT_METHOD_CATEGORY_M17N,  // Multilingualization input methods
  INPUT_METHOD_CATEGORY_T13N,  // Transliteration input methods
  INPUT_METHOD_CATEGORY_ARC,   // ARC input methods
  INPUT_METHOD_CATEGORY_MAX
};

const ImeKeyset kKeysets[] = {ImeKeyset::kEmoji, ImeKeyset::kHandwriting,
                              ImeKeyset::kVoice};

InputMethodCategory GetInputMethodCategory(const std::string& input_method_id) {
  const std::string component_id =
      extension_ime_util::GetComponentIDByInputMethodID(input_method_id);
  InputMethodCategory category = INPUT_METHOD_CATEGORY_UNKNOWN;
  if (base::StartsWith(component_id, "xkb:", base::CompareCase::SENSITIVE)) {
    category = INPUT_METHOD_CATEGORY_XKB;
  } else if (base::StartsWith(component_id, "zh-",
                              base::CompareCase::SENSITIVE)) {
    category = INPUT_METHOD_CATEGORY_ZH;
  } else if (base::StartsWith(component_id, "nacl_mozc_",
                              base::CompareCase::SENSITIVE)) {
    category = INPUT_METHOD_CATEGORY_JA;
  } else if (base::StartsWith(component_id, "hangul_",
                              base::CompareCase::SENSITIVE) ||
             component_id == "ko-t-i0-und") {
    category = INPUT_METHOD_CATEGORY_KO;
  } else if (base::StartsWith(component_id, "vkd_",
                              base::CompareCase::SENSITIVE)) {
    category = INPUT_METHOD_CATEGORY_M17N;
  } else if (component_id.find("-t-i0-") != std::string::npos) {
    category = INPUT_METHOD_CATEGORY_T13N;
  } else if (extension_ime_util::IsArcIME(input_method_id)) {
    category = INPUT_METHOD_CATEGORY_ARC;
  }

  return category;
}

std::string KeysetToString(ImeKeyset keyset) {
  switch (keyset) {
    case ImeKeyset::kNone:
      return "";
    case ImeKeyset::kEmoji:
      return "emoji";
    case ImeKeyset::kHandwriting:
      return "hwt";
    case ImeKeyset::kVoice:
      return "voice";
  }
}

bool IsShuttingDown() {
  return !g_browser_process || g_browser_process->IsShuttingDown();
}

}  // namespace

// ------------------------ InputMethodManagerImpl::StateImpl

InputMethodManagerImpl::StateImpl::StateImpl(
    InputMethodManagerImpl* manager,
    Profile* profile,
    const InputMethodDescriptor* initial_input_method)
    : profile_(profile), manager_(manager) {
  if (initial_input_method) {
    enabled_input_method_ids_.push_back(initial_input_method->id());
    current_input_method_ = *initial_input_method;
  }
}

InputMethodManagerImpl::StateImpl::~StateImpl() = default;

bool InputMethodManagerImpl::StateImpl::IsActive() const {
  return manager_->state_.get() == this;
}

scoped_refptr<InputMethodManager::State>
InputMethodManagerImpl::StateImpl::Clone() const {
  scoped_refptr<StateImpl> new_state(new StateImpl(manager_, profile_));

  new_state->last_used_input_method_id_ = last_used_input_method_id_;
  new_state->current_input_method_ = current_input_method_;

  new_state->enabled_input_method_ids_ = enabled_input_method_ids_;
  new_state->allowed_keyboard_layout_input_method_ids_ =
      allowed_keyboard_layout_input_method_ids_;

  new_state->pending_input_method_id_ = pending_input_method_id_;

  new_state->enabled_extension_imes_ = enabled_extension_imes_;
  new_state->available_input_methods_ = available_input_methods_;
  new_state->menu_activated_ = menu_activated_;
  new_state->input_view_url_ = input_view_url_;
  new_state->input_view_url_overridden_ = input_view_url_overridden_;
  new_state->ui_style_ = ui_style_;

  return scoped_refptr<InputMethodManager::State>(new_state.get());
}

InputMethodDescriptors
InputMethodManagerImpl::StateImpl::GetEnabledInputMethods() const {
  InputMethodDescriptors result;
  // Build the enabled input method descriptors from the enabled input
  // methods cache |enabled_input_method_ids_|.
  for (const auto& input_method_id : enabled_input_method_ids_) {
    const InputMethodDescriptor* descriptor =
        manager_->util_.GetInputMethodDescriptorFromId(input_method_id);
    if (descriptor) {
      result.push_back(*descriptor);
    } else {
      const auto ix = available_input_methods_.find(input_method_id);
      if (ix != available_input_methods_.end()) {
        result.push_back(ix->second);
      } else {
        DVLOG(1) << "Descriptor is not found for: " << input_method_id;
      }
    }
  }
  if (result.empty()) {
    // Initially |enabled_input_method_ids_| is empty. browser_tests might take
    // this path.
    result.push_back(InputMethodUtil::GetFallbackInputMethodDescriptor());
  }

  return result;
}

InputMethodDescriptors InputMethodManagerImpl::StateImpl::
    GetEnabledInputMethodsSortedByLocalizedDisplayNames() const {
  InputMethodDescriptors result = GetEnabledInputMethods();

  UErrorCode error_code = U_ZERO_ERROR;
  std::unique_ptr<icu::Collator> collator(
      icu::Collator::createInstance(error_code));  // use current ICU locale
  DCHECK(U_SUCCESS(error_code));
  const InputMethodUtil& util = manager_->util_;

  std::sort(
      result.begin(), result.end(),
      [&collator, &util](const InputMethodDescriptor& a,
                         const InputMethodDescriptor& b) {
        std::u16string a16 = base::UTF8ToUTF16(util.GetLocalizedDisplayName(a));
        std::u16string b16 = base::UTF8ToUTF16(util.GetLocalizedDisplayName(b));
        return base::i18n::CompareString16WithCollator(*collator, a16, b16) < 0;
      });

  return result;
}

const std::vector<std::string>&
InputMethodManagerImpl::StateImpl::GetEnabledInputMethodIds() const {
  return enabled_input_method_ids_;
}

size_t InputMethodManagerImpl::StateImpl::GetNumEnabledInputMethods() const {
  return enabled_input_method_ids_.size();
}

const InputMethodDescriptor*
InputMethodManagerImpl::StateImpl::GetInputMethodFromId(
    const std::string& input_method_id) const {
  const InputMethodDescriptor* ime =
      manager_->util_.GetInputMethodDescriptorFromId(input_method_id);
  if (!ime) {
    const auto ix = available_input_methods_.find(input_method_id);
    if (ix != available_input_methods_.end()) {
      ime = &ix->second;
    }
  }
  return ime;
}

void InputMethodManagerImpl::StateImpl::EnableLoginLayouts(
    const std::string& language_code,
    const std::vector<std::string>& initial_layouts) {
  if (IsShuttingDown()) {
    return;
  }

  // First, hardware keyboard layout should be shown.
  std::vector<std::string> candidates =
      manager_->util_.GetHardwareLoginInputMethodIds();

  // Second, locale based input method should be shown.
  // Add input methods associated with the language.
  std::vector<std::string> layouts_from_locale;
  manager_->util_.GetInputMethodIdsFromLanguageCode(
      language_code, kKeyboardLayoutsOnly, &layouts_from_locale);
  candidates.insert(candidates.end(), layouts_from_locale.begin(),
                    layouts_from_locale.end());

  std::vector<std::string> layouts;
  // First, add the initial input method ID, if it's requested, to
  // layouts, so it appears first on the list of enabled input
  // methods at the input language status menu.
  for (const auto& initial_layout : initial_layouts) {
    if (manager_->util_.IsValidInputMethodId(initial_layout)) {
      if (manager_->IsLoginKeyboard(initial_layout)) {
        if (IsInputMethodAllowed(initial_layout)) {
          layouts.push_back(initial_layout);
        } else {
          DVLOG(1) << "EnableLoginLayouts: ignoring layout disallowd by policy:"
                   << initial_layout;
        }
      } else {
        DVLOG(1)
            << "EnableLoginLayouts: ignoring non-login initial keyboard layout:"
            << initial_layout;
      }
    } else if (!initial_layout.empty()) {
      DVLOG(1) << "EnableLoginLayouts: ignoring non-keyboard or invalid ID: "
               << initial_layout;
    }
  }

  // Add candidates to layouts, while skipping duplicates.
  for (const auto& candidate : candidates) {
    // Not efficient, but should be fine, as the two vectors are very
    // short (2-5 items).
    if (!base::Contains(layouts, candidate) &&
        manager_->IsLoginKeyboard(candidate) &&
        IsInputMethodAllowed(candidate)) {
      layouts.push_back(candidate);
    }
  }

  // Empty |initial_layouts| work too.
  FinalizeInputMethodsEnabling(layouts, initial_layouts);
}

void InputMethodManagerImpl::StateImpl::EnableOobeInputMethods(
    const std::string& language_code,
    const std::vector<std::string>& initial_input_methods) {
  if (IsShuttingDown()) {
    return;
  }

  // First, hardware input methods should be shown.
  std::vector<std::string> candidates =
      manager_->util_.GetHardwareInputMethodIds();

  // Second, locale based input method should be shown.
  // Add input methods associated with the language.
  std::vector<std::string> input_methods_from_locale;
  manager_->util_.GetInputMethodIdsFromLanguageCode(
      language_code, kAllInputMethods, &input_methods_from_locale);
  candidates.insert(candidates.end(), input_methods_from_locale.begin(),
                    input_methods_from_locale.end());

  std::vector<std::string> resulting_input_methods;
  // First, add the initial input method ID, if it's requested, to
  // resulting_input_methods, so it appears first on the list of enabled input
  // methods at the input language status menu.
  for (const auto& initial_input_method : initial_input_methods) {
    if (manager_->util_.IsValidInputMethodId(initial_input_method) &&
        manager_->util_.IsOobeAllowlisted(initial_input_method) &&
        IsInputMethodAllowed(initial_input_method)) {
      resulting_input_methods.push_back(initial_input_method);
    }
  }

  // Add candidates to resulting_input_methods, while skipping duplicates.
  for (const auto& candidate : candidates) {
    // Not efficient, but should be fine, as the two vectors are very
    // short (2-5 items).
    if (!base::Contains(resulting_input_methods, candidate) &&
        manager_->util_.IsOobeAllowlisted(candidate) &&
        IsInputMethodAllowed(candidate)) {
      resulting_input_methods.push_back(candidate);
    }
  }

  // Empty |initial_input_methods| work too.
  FinalizeInputMethodsEnabling(resulting_input_methods, initial_input_methods);
}

void InputMethodManagerImpl::StateImpl::FinalizeInputMethodsEnabling(
    std::vector<std::string>& input_methods_to_enable,
    const std::vector<std::string>& initial_input_methods) {
  manager_->GetMigratedInputMethodIDs(&input_methods_to_enable);
  enabled_input_method_ids_.swap(input_methods_to_enable);

  if (IsActive()) {
    // Initialize candidate window controller and widgets such as
    // candidate window, infolist and mode indicator.  Note, mode
    // indicator is used by only keyboard layout input methods.
    if (enabled_input_method_ids_.size() > 1) {
      manager_->MaybeInitializeCandidateWindowController();
    }

    ChangeInputMethod(initial_input_methods.empty()
                          ? std::string()
                          : extension_ime_util::GetInputMethodIDByEngineID(
                                initial_input_methods[0]),
                      false);
  }
}

void InputMethodManagerImpl::StateImpl::DisableNonLockScreenLayouts() {
  std::set<std::string> added_ids;

  const std::vector<std::string>& hardware_keyboard_ids =
      manager_->util_.GetHardwareLoginInputMethodIds();

  std::vector<std::string> new_enabled_input_method_ids;
  for (const auto& input_method_id : enabled_input_method_ids_) {
    // Skip if it's not a keyboard layout. Drop input methods including
    // extension ones. We need to keep all IMEs to support inputting on inline
    // reply on a notification if notifications on lock screen is enabled.
    if (!manager_->IsLoginKeyboard(input_method_id) ||
        added_ids.count(input_method_id)) {
      continue;
    }
    new_enabled_input_method_ids.push_back(input_method_id);
    added_ids.insert(input_method_id);
  }

  // We'll add the hardware keyboard if it's not included in
  // |enabled_input_method_ids_| so that the user can always use the hardware
  // keyboard on the screen locker.
  for (const auto& hardware_keyboard_id : hardware_keyboard_ids) {
    if (added_ids.count(hardware_keyboard_id)) {
      continue;
    }
    new_enabled_input_method_ids.push_back(hardware_keyboard_id);
    added_ids.insert(hardware_keyboard_id);
  }

  enabled_input_method_ids_.swap(new_enabled_input_method_ids);

  // Re-check current_input_method_.
  ChangeInputMethod(current_input_method_.id(), false);
}

// Adds new input method to given list.
bool InputMethodManagerImpl::StateImpl::EnableInputMethodImpl(
    const std::string& input_method_id,
    std::vector<std::string>* new_enabled_input_method_ids) const {
  if (!IsInputMethodAllowed(input_method_id)) {
    DVLOG(1) << "EnableInputMethod: " << input_method_id << " is not allowed.";
    return false;
  }

  DCHECK(new_enabled_input_method_ids);
  if (!manager_->util_.IsValidInputMethodId(input_method_id)) {
    DVLOG(1) << "EnableInputMethod: Invalid ID: " << input_method_id;
    return false;
  }

  if (!base::Contains(*new_enabled_input_method_ids, input_method_id)) {
    new_enabled_input_method_ids->push_back(input_method_id);
  }

  return true;
}

bool InputMethodManagerImpl::StateImpl::EnableInputMethod(
    const std::string& input_method_id) {
  if (!EnableInputMethodImpl(input_method_id, &enabled_input_method_ids_)) {
    return false;
  }

  manager_->ReconfigureIMFramework(this);
  return true;
}

bool InputMethodManagerImpl::StateImpl::ReplaceEnabledInputMethods(
    const std::vector<std::string>& new_enabled_input_method_ids) {
  if (IsShuttingDown()) {
    return false;
  }

  // Filter unknown or obsolete IDs.
  std::vector<std::string> new_enabled_input_method_ids_filtered;

  for (const auto& new_enabled_input_method_id : new_enabled_input_method_ids) {
    EnableInputMethodImpl(new_enabled_input_method_id,
                          &new_enabled_input_method_ids_filtered);
  }

  if (new_enabled_input_method_ids_filtered.empty()) {
    DVLOG(1) << "ReplaceEnabledInputMethods: No valid input method ID";
    return false;
  }

  // Copy extension IDs to |new_enabled_input_method_ids_filtered|. We have to
  // keep relative order of the extension input method IDs.
  for (const auto& input_method_id : enabled_input_method_ids_) {
    if (extension_ime_util::IsExtensionIME(input_method_id)) {
      new_enabled_input_method_ids_filtered.push_back(input_method_id);
    }
  }
  enabled_input_method_ids_.swap(new_enabled_input_method_ids_filtered);
  manager_->GetMigratedInputMethodIDs(&enabled_input_method_ids_);

  manager_->ReconfigureIMFramework(this);

  // If |current_input_method_| is no longer in |enabled_input_method_ids_|,
  // ChangeInputMethod() picks the first one in |enabled_input_method_ids_|.
  ChangeInputMethod(current_input_method_.id(), false);

  // Record histogram for enabled input method count; "active" in the metric
  // name is a legacy misnomer; "active" should refer to just the single current
  // aka. activated input method that's one of the enabled input methods whose
  // total count is being tracked by this metric.
  UMA_HISTOGRAM_COUNTS_1M("InputMethod.ActiveCount",
                          enabled_input_method_ids_.size());

  return true;
}

bool InputMethodManagerImpl::StateImpl::SetAllowedInputMethods(
    const std::vector<std::string>& new_allowed_input_method_ids) {
  allowed_keyboard_layout_input_method_ids_.clear();
  for (auto input_method_id : new_allowed_input_method_ids) {
    std::string migrated_id =
        manager_->util_.GetMigratedInputMethod(input_method_id);
    if (manager_->util_.IsValidInputMethodId(migrated_id)) {
      allowed_keyboard_layout_input_method_ids_.push_back(migrated_id);
      // Kiosk users are not able to go to the settings and manually enable
      // allowed input methods, thus it has to be done automatically for
      // non-empty list.
      DCHECK(user_manager::UserManager::Get());
      if (user_manager::UserManager::Get()->IsLoggedInAsAnyKioskApp()) {
        EnableInputMethod(migrated_id);
      }
    }
  }

  if (allowed_keyboard_layout_input_method_ids_.empty()) {
    // None of the passed input methods were valid, so allow everything.
    return false;
  }
  return true;
}

const std::vector<std::string>&
InputMethodManagerImpl::StateImpl::GetAllowedInputMethodIds() const {
  return allowed_keyboard_layout_input_method_ids_;
}

bool InputMethodManagerImpl::StateImpl::IsInputMethodAllowed(
    const std::string& input_method_id) const {
  // Every input method is allowed if SetAllowedKeyboardLayoutInputMethods has
  // not been called.
  if (allowed_keyboard_layout_input_method_ids_.empty()) {
    return true;
  }

  return base::Contains(allowed_keyboard_layout_input_method_ids_,
                        input_method_id) ||
         base::Contains(
             allowed_keyboard_layout_input_method_ids_,
             manager_->util_.GetMigratedInputMethod(input_method_id));
}

std::string
InputMethodManagerImpl::StateImpl::GetAllowedFallBackKeyboardLayout() const {
  for (const std::string& hardware_id :
       manager_->util_.GetHardwareInputMethodIds()) {
    if (IsInputMethodAllowed(hardware_id)) {
      return hardware_id;
    }
  }
  return allowed_keyboard_layout_input_method_ids_[0];
}

void InputMethodManagerImpl::StateImpl::ChangeInputMethod(
    const std::string& input_method_id,
    bool show_message) {
  if (IsShuttingDown()) {
    return;
  }

  bool notify_menu = false;

  // Always lookup input method, even if it is the same as
  // |current_input_method_| because If it is no longer in
  // |enabled_input_method_ids_|, pick the first one in
  // |enabled_input_method_ids_|.
  const InputMethodDescriptor* descriptor = LookupInputMethod(input_method_id);
  if (!descriptor) {
    descriptor = LookupInputMethod(
        manager_->util_.GetMigratedInputMethod(input_method_id));
    if (!descriptor) {
      LOG(ERROR) << "Can't find InputMethodDescriptor for \"" << input_method_id
                 << "\"";
      return;
    }
  }

  // For 3rd party IME, when the user just logged in, SetEnabledExtensionImes
  // happens after activating the 3rd party IME.
  // So here to record the 3rd party IME to be activated, and activate it
  // when SetEnabledExtensionImes happens later.
  if (!InputMethodIsEnabled(input_method_id) &&
      extension_ime_util::IsExtensionIME(input_method_id)) {
    pending_input_method_id_ = input_method_id;
  }

  if (descriptor->id() != current_input_method_.id()) {
    last_used_input_method_id_ = current_input_method_.id();
    current_input_method_ = *descriptor;
    notify_menu = true;
  }

  // Always change input method even if it is the same.
  // TODO(komatsu): Revisit if this is necessary.
  if (IsActive()) {
    manager_->ChangeInputMethodInternalFromActiveState(show_message,
                                                       notify_menu);
  }

  manager_->RecordInputMethodUsage(current_input_method_.id());
}

void InputMethodManagerImpl::StateImpl::ChangeInputMethodToJpKeyboard() {
  ChangeInputMethod(
      extension_ime_util::GetInputMethodIDByEngineID("xkb:jp::jpn"), true);
}

void InputMethodManagerImpl::StateImpl::ChangeInputMethodToJpIme() {
  ChangeInputMethod(
      extension_ime_util::GetInputMethodIDByEngineID("nacl_mozc_jp"), true);
}

void InputMethodManagerImpl::StateImpl::ToggleInputMethodForJpIme() {
  std::string jp_ime_id =
      extension_ime_util::GetInputMethodIDByEngineID("nacl_mozc_jp");
  ChangeInputMethod(
      GetCurrentInputMethod().id() == jp_ime_id
          ? extension_ime_util::GetInputMethodIDByEngineID("xkb:jp::jpn")
          : jp_ime_id,
      true);
}

void InputMethodManagerImpl::StateImpl::AddInputMethodExtension(
    const std::string& extension_id,
    const InputMethodDescriptors& descriptors,
    TextInputMethod* engine) {
  if (IsShuttingDown()) {
    return;
  }

  DCHECK(engine);

  manager_->engine_map_[profile_][extension_id] = engine;
  VLOG(1) << "Add an engine for \"" << extension_id << "\"";

  bool contain = false;
  for (const auto& descriptor : descriptors) {
    const std::string& id = descriptor.id();
    available_input_methods_[id] = descriptor;
    if (base::Contains(enabled_extension_imes_, id)) {
      if (!base::Contains(enabled_input_method_ids_, id)) {
        enabled_input_method_ids_.push_back(id);
      } else {
        DVLOG(1) << "AddInputMethodExtension: already added: " << id << ", "
                 << descriptor.name();
      }
      contain = true;
    }
  }

  if (IsActive()) {
    if (extension_id == extension_ime_util::GetExtensionIDFromInputMethodID(
                            current_input_method_.id())) {
      IMEBridge::Get()->SetCurrentEngineHandler(engine);
      engine->Enable(extension_ime_util::GetComponentIDByInputMethodID(
          current_input_method_.id()));
    }

    // Ensure that the input method daemon is running.
    if (contain) {
      manager_->MaybeInitializeCandidateWindowController();
    }
  }

  manager_->NotifyImeMenuListChanged();
  manager_->NotifyInputMethodExtensionAdded(extension_id);
}

void InputMethodManagerImpl::StateImpl::RemoveInputMethodExtension(
    const std::string& extension_id) {
  // Remove the enabled input methods with |extension_id|.
  std::vector<std::string> new_enabled_input_method_ids;
  for (const auto& enabled_input_method_id : enabled_input_method_ids_) {
    if (extension_id != extension_ime_util::GetExtensionIDFromInputMethodID(
                            enabled_input_method_id)) {
      new_enabled_input_method_ids.push_back(enabled_input_method_id);
    }
  }
  enabled_input_method_ids_.swap(new_enabled_input_method_ids);

  // Remove the input methods registered by `extension_id`.
  std::map<std::string, InputMethodDescriptor> new_available_input_methods;
  for (const auto& entry : available_input_methods_) {
    if (extension_id !=
        extension_ime_util::GetExtensionIDFromInputMethodID(entry.first)) {
      new_available_input_methods[entry.first] = entry.second;
    }
  }
  available_input_methods_.swap(new_available_input_methods);

  if (IsActive()) {
    if (IMEBridge::Get()->GetCurrentEngineHandler() ==
        manager_->engine_map_[profile_][extension_id]) {
      IMEBridge::Get()->SetCurrentEngineHandler(nullptr);
    }
    manager_->engine_map_[profile_].erase(extension_id);
  }

  // If |current_input_method_| is no longer in |enabled_input_method_ids_|,
  // switch to the first one in |enabled_input_method_ids_|.
  ChangeInputMethod(current_input_method_.id(), false);
  manager_->NotifyInputMethodExtensionRemoved(extension_id);
}

void InputMethodManagerImpl::StateImpl::GetInputMethodExtensions(
    InputMethodDescriptors* result) {
  // Build the extension input method descriptors from the input methods cache
  // `available_input_methods_`.
  for (const auto& entry : available_input_methods_) {
    if (extension_ime_util::IsExtensionIME(entry.first) ||
        extension_ime_util::IsArcIME(entry.first)) {
      result->push_back(entry.second);
    }
  }
}

void InputMethodManagerImpl::StateImpl::SetEnabledExtensionImes(
    base::span<const std::string> ids) {
  enabled_extension_imes_.clear();
  enabled_extension_imes_.insert(enabled_extension_imes_.end(), ids.begin(),
                                 ids.end());
  bool enabled_imes_changed = false;
  bool switch_to_pending = false;

  for (const auto& entry : available_input_methods_) {
    if (extension_ime_util::IsComponentExtensionIME(entry.first)) {
      continue;  // Do not filter component extension.
    }

    if (pending_input_method_id_ == entry.first) {
      switch_to_pending = true;
    }

    const auto currently_enabled_iter =
        std::ranges::find(enabled_input_method_ids_, entry.first);

    bool currently_enabled =
        currently_enabled_iter != enabled_input_method_ids_.end();
    bool enabled = base::Contains(enabled_extension_imes_, entry.first);

    if (currently_enabled && !enabled) {
      enabled_input_method_ids_.erase(currently_enabled_iter);
    }

    if (!currently_enabled && enabled) {
      enabled_input_method_ids_.push_back(entry.first);
    }

    if (currently_enabled == !enabled) {
      enabled_imes_changed = true;
    }
  }

  if (IsActive() && enabled_imes_changed) {
    manager_->MaybeInitializeCandidateWindowController();

    if (switch_to_pending) {
      ChangeInputMethod(pending_input_method_id_, false);
      pending_input_method_id_.clear();
    } else {
      // If |current_input_method_| is no longer in |enabled_input_method_ids_|,
      // switch to the first one in |enabled_input_method_ids_|.
      ChangeInputMethod(current_input_method_.id(), false);
    }
  }
}

void InputMethodManagerImpl::StateImpl::SetInputMethodLoginDefaultFromVPD(
    const std::string& locale,
    const std::string& oem_layout) {
  std::string input_method_id;
  if (!oem_layout.empty()) {
    // If the OEM layout information is provided, use it.
    input_method_id = oem_layout;
  } else {
    // Otherwise, determine the hardware keyboard from the locale.
    std::vector<std::string> input_method_ids;
    if (manager_->util_.GetInputMethodIdsFromLanguageCode(
            locale, kAllInputMethods, &input_method_ids)) {
      // The output list |input_method_ids| is sorted by popularity, hence
      // input_method_ids[0] now contains the most popular keyboard layout
      // for the given locale.
      DCHECK_GE(input_method_ids.size(), 1U);
      input_method_id = input_method_ids[0];
    }
  }

  if (input_method_id.empty()) {
    return;
  }

  std::vector<std::string> input_method_ids = base::SplitString(
      input_method_id, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  manager_->GetMigratedInputMethodIDs(&input_method_ids);

  PrefService* prefs = g_browser_process->local_state();
  prefs->SetString(prefs::kHardwareKeyboardLayout,
                   base::JoinString(input_method_ids, ","));

  // This asks the file thread to save the prefs (i.e. doesn't block).
  // The latest values of Local State reside in memory so we can safely
  // get the value of kHardwareKeyboardLayout even if the data is not
  // yet saved to disk.
  prefs->CommitPendingWrite();

  manager_->util_.UpdateHardwareLayoutCache();

  // This function is called only during system setup in OOBE.
  EnableOobeInputMethods(locale, input_method_ids);
  LoadNecessaryComponentExtensions();
}

void InputMethodManagerImpl::StateImpl::SetInputMethodLoginDefault(
    bool is_in_oobe_context) {
  // Set up keyboards. For example, when |locale| is "en-US", enable US qwerty
  // and US dvorak keyboard layouts.
  if (g_browser_process && g_browser_process->local_state()) {
    const std::string locale = g_browser_process->GetApplicationLocale();
    std::vector<std::string> input_method_ids_to_be_enabled;
    if (!GetAllowedInputMethodIds().empty()) {
      // Prefer policy-set input methods.
      input_method_ids_to_be_enabled = GetAllowedInputMethodIds();
    } else {
      // If the preferred keyboard for the login screen has been saved, use it.
      PrefService* prefs = g_browser_process->local_state();
      std::string initial_input_method_id =
          prefs->GetString(language_prefs::kPreferredKeyboardLayout);
      if (initial_input_method_id.empty()) {
        // If kPreferredKeyboardLayout is not specified, use the hardware
        // layout.
        input_method_ids_to_be_enabled =
            manager_->util_.GetHardwareLoginInputMethodIds();
      } else {
        input_method_ids_to_be_enabled.push_back(initial_input_method_id);
      }
    }
    if (is_in_oobe_context) {
      EnableOobeInputMethods(locale, input_method_ids_to_be_enabled);
    } else {
      EnableLoginLayouts(locale, input_method_ids_to_be_enabled);
    }
    LoadNecessaryComponentExtensions();
  }
}

void InputMethodManagerImpl::StateImpl::SwitchToNextInputMethod() {
  if (enabled_input_method_ids_.size() <= 1 ||
      current_input_method_.id().empty()) {
    return;
  }

  const std::string& current_input_method_id = current_input_method_.id();
  InputMethodDescriptors sorted_enabled_input_methods =
      GetEnabledInputMethodsSortedByLocalizedDisplayNames();

  auto iter =
      std::ranges::find(sorted_enabled_input_methods, current_input_method_id,
                        &InputMethodDescriptor::id);

  if (iter != sorted_enabled_input_methods.end()) {
    ++iter;
  }
  if (iter == sorted_enabled_input_methods.end()) {
    iter = sorted_enabled_input_methods.begin();
  }

  ChangeInputMethod(iter->id(), true);
}

void InputMethodManagerImpl::StateImpl::SwitchToLastUsedInputMethod() {
  if (enabled_input_method_ids_.size() <= 1 ||
      current_input_method_.id().empty()) {
    return;
  }

  if (last_used_input_method_id_.empty() ||
      last_used_input_method_id_ == current_input_method_.id()) {
    SwitchToNextInputMethod();
    return;
  }

  const auto iter =
      std::ranges::find(enabled_input_method_ids_, last_used_input_method_id_);
  if (iter == enabled_input_method_ids_.end()) {
    // last_used_input_method_id_ is not supported.
    SwitchToNextInputMethod();
    return;
  }
  ChangeInputMethod(*iter, true);
}

InputMethodDescriptor InputMethodManagerImpl::StateImpl::GetCurrentInputMethod()
    const {
  if (current_input_method_.id().empty()) {
    return InputMethodUtil::GetFallbackInputMethodDescriptor();
  }

  return current_input_method_;
}

bool InputMethodManagerImpl::StateImpl::InputMethodIsEnabled(
    const std::string& input_method_id) const {
  return base::Contains(enabled_input_method_ids_, input_method_id);
}

void InputMethodManagerImpl::StateImpl::EnableInputView() {
  if (!input_view_url_overridden_) {
    input_view_url_ = current_input_method_.input_view_url();
  }
}

void InputMethodManagerImpl::StateImpl::DisableInputView() {
  input_view_url_ = GURL();
}

const GURL& InputMethodManagerImpl::StateImpl::GetInputViewUrl() const {
  return input_view_url_;
}

InputMethodManager::UIStyle InputMethodManagerImpl::StateImpl::GetUIStyle()
    const {
  return ui_style_;
}

void InputMethodManagerImpl::StateImpl::SetUIStyle(
    InputMethodManager::UIStyle ui_style) {
  ui_style_ = ui_style;
}

void InputMethodManagerImpl::StateImpl::OverrideInputViewUrl(const GURL& url) {
  input_view_url_ = url;
  input_view_url_overridden_ = true;
}

void InputMethodManagerImpl::StateImpl::ResetInputViewUrl() {
  input_view_url_ = current_input_method_.input_view_url();
  input_view_url_overridden_ = false;
}

void InputMethodManagerImpl::StateImpl::LoadNecessaryComponentExtensions() {
  // Load component extensions but also update |enabled_input_method_ids_| as
  // some component extension IMEs may have been removed from the Chrome OS
  // image. If specified component extension IME no longer exists, falling back
  // to an existing IME.
  TRACE_EVENT0(
      "ime",
      "InputMethodManagerImpl::StateImpl::LoadNecessaryComponentExtensions");
  std::vector<std::string> unfiltered_input_method_ids;
  unfiltered_input_method_ids.swap(enabled_input_method_ids_);
  std::set<std::string> ext_loaded;
  for (const auto& unfiltered_input_method_id : unfiltered_input_method_ids) {
    if (!extension_ime_util::IsComponentExtensionIME(
            unfiltered_input_method_id)) {
      // Legacy IMEs or xkb layouts are alwayes enabled.
      enabled_input_method_ids_.push_back(unfiltered_input_method_id);
    } else if (manager_->component_extension_ime_manager_->IsAllowlisted(
                   unfiltered_input_method_id)) {
      if (manager_->enable_extension_loading_) {
        manager_->component_extension_ime_manager_->LoadComponentExtensionIME(
            profile_, unfiltered_input_method_id, &ext_loaded);
      }

      enabled_input_method_ids_.push_back(unfiltered_input_method_id);
    }
  }
}

const InputMethodDescriptor*
InputMethodManagerImpl::StateImpl::LookupInputMethod(
    const std::string& input_method_id) {
  std::string input_method_id_to_switch = input_method_id;

  // Sanity check
  if (!InputMethodIsEnabled(input_method_id)) {
    InputMethodDescriptors input_methods(GetEnabledInputMethods());
    DCHECK(!input_methods.empty());
    input_method_id_to_switch = input_methods.at(0).id();
    if (!input_method_id.empty()) {
      DVLOG(1) << "Can't change the current input method to " << input_method_id
               << " since the engine is not enabled. " << "Switch to "
               << input_method_id_to_switch << " instead.";
    }
  }

  const InputMethodDescriptor* descriptor = nullptr;
  if (extension_ime_util::IsExtensionIME(input_method_id_to_switch) ||
      extension_ime_util::IsArcIME(input_method_id_to_switch)) {
    DCHECK(available_input_methods_.find(input_method_id_to_switch) !=
           available_input_methods_.end());
    descriptor = &(available_input_methods_[input_method_id_to_switch]);
  } else {
    descriptor = manager_->util_.GetInputMethodDescriptorFromId(
        input_method_id_to_switch);
    if (!descriptor) {
      LOG(ERROR) << "Unknown input method id: " << input_method_id_to_switch;
    }
  }
  DCHECK(descriptor);
  return descriptor;
}

Profile* InputMethodManagerImpl::StateImpl::GetProfile() const {
  return profile_;
}

void InputMethodManagerImpl::StateImpl::SetMenuActivated(bool activated) {
  menu_activated_ = activated;
}

bool InputMethodManagerImpl::StateImpl::IsMenuActivated() const {
  return menu_activated_;
}

// ------------------------ InputMethodManagerImpl
bool InputMethodManagerImpl::IsLoginKeyboard(const std::string& layout) const {
  return util_.IsLoginKeyboard(layout);
}

std::string InputMethodManagerImpl::GetMigratedInputMethodID(
    const std::string& input_method_id) {
  return util_.GetMigratedInputMethod(input_method_id);
}

bool InputMethodManagerImpl::GetMigratedInputMethodIDs(
    std::vector<std::string>* input_method_ids) {
  return util_.GetMigratedInputMethodIDs(input_method_ids);
}

// Starts or stops the system input method framework as needed.
void InputMethodManagerImpl::ReconfigureIMFramework(
    InputMethodManagerImpl::StateImpl* state) {
  DCHECK(state);
  state->LoadNecessaryComponentExtensions();

  // Initialize candidate window controller and widgets such as
  // candidate window, infolist and mode indicator.  Note, mode
  // indicator is used by only keyboard layout input methods.
  if (state_.get() == state) {
    MaybeInitializeCandidateWindowController();
    MaybeInitializeAssistiveWindowController();
  }
}

void InputMethodManagerImpl::SetState(
    scoped_refptr<InputMethodManager::State> state) {
  DCHECK(state.get());
  auto* new_impl_state =
      static_cast<InputMethodManagerImpl::StateImpl*>(state.get());

  state_ = new_impl_state;

  if (state_.get() && state_->GetNumEnabledInputMethods()) {
    // Initialize candidate window controller and widgets such as
    // candidate window, infolist and mode indicator.  Note, mode
    // indicator is used by only keyboard layout input methods.
    MaybeInitializeCandidateWindowController();
    MaybeInitializeAssistiveWindowController();

    // Always call ChangeInputMethodInternalFromActiveState even when the input
    // method id remain unchanged, because onActivate event needs to be sent to
    // IME extension to update the current screen type correctly.
    ChangeInputMethodInternalFromActiveState(false /* show_message */,
                                             true /* notify_menu */);
  }
}

scoped_refptr<InputMethodManager::State>
InputMethodManagerImpl::GetActiveIMEState() {
  return scoped_refptr<InputMethodManager::State>(state_.get());
}

InputMethodManagerImpl::InputMethodManagerImpl(
    std::unique_ptr<InputMethodDelegate> delegate,
    std::unique_ptr<ComponentExtensionIMEManagerDelegate>
        component_extension_ime_manager_delegate,
    bool enable_extension_loading,
    std::unique_ptr<ImeKeyboard> ime_keyboard)
    : delegate_(std::move(delegate)),
      util_(delegate_.get()),
      keyboard_(std::move(ime_keyboard)),
      enable_extension_loading_(enable_extension_loading),
      features_enabled_state_(InputMethodManager::FEATURE_ALL) {
  if (::features::IsImprovedKeyboardShortcutsEnabled()) {
    // Create a set of layouts that do not use positional shortcuts.
    non_positional_layouts_.reserve(kNonPositionalLayoutsLength);
    for (size_t i = 0; i < kNonPositionalLayoutsLength; i++) {
      non_positional_layouts_.emplace(kNonPositionalLayouts[i]);
    }
  }

  // Initializes the system IME list.
  component_extension_ime_manager_ =
      std::make_unique<ComponentExtensionIMEManager>(
          std::move(component_extension_ime_manager_delegate));
  const InputMethodDescriptors& descriptors =
      component_extension_ime_manager_->GetAllIMEAsInputMethodDescriptor();
  util_.ResetInputMethods(descriptors);

  // We should not use ALL_BROWSERS_CLOSING here since logout might be cancelled
  // by JavaScript after ALL_BROWSERS_CLOSING is sent (crosbug.com/11055).
  on_app_terminating_subscription_ =
      browser_shutdown::AddAppTerminatingCallback(base::BindOnce(
          &InputMethodManagerImpl::OnAppTerminating, base::Unretained(this)));
}

InputMethodManagerImpl::~InputMethodManagerImpl() {
  if (candidate_window_controller_.get()) {
    candidate_window_controller_->RemoveObserver(this);
  }
}

void InputMethodManagerImpl::RecordInputMethodUsage(
    const std::string& input_method_id) {
  UMA_HISTOGRAM_ENUMERATION("InputMethod.Category",
                            GetInputMethodCategory(input_method_id),
                            INPUT_METHOD_CATEGORY_MAX);
  base::UmaHistogramSparse(
      "InputMethod.ID2",
      static_cast<int32_t>(base::PersistentHash(input_method_id)));
}

void InputMethodManagerImpl::AddObserver(
    InputMethodManager::Observer* observer) {
  observers_.AddObserver(observer);
  observer->OnExtraInputEnabledStateChange(
      // TODO(shuchen): Remove this parameter - ex features::kEHVInputOnImeMenu
      true, features_enabled_state_ & InputMethodManager::FEATURE_EMOJI,
      features_enabled_state_ & InputMethodManager::FEATURE_HANDWRITING,
      features_enabled_state_ & InputMethodManager::FEATURE_VOICE);
}

void InputMethodManagerImpl::AddCandidateWindowObserver(
    InputMethodManager::CandidateWindowObserver* observer) {
  candidate_window_observers_.AddObserver(observer);
}

void InputMethodManagerImpl::AddImeMenuObserver(
    InputMethodManager::ImeMenuObserver* observer) {
  ime_menu_observers_.AddObserver(observer);
}

void InputMethodManagerImpl::RemoveObserver(
    InputMethodManager::Observer* observer) {
  observers_.RemoveObserver(observer);
}

void InputMethodManagerImpl::RemoveCandidateWindowObserver(
    InputMethodManager::CandidateWindowObserver* observer) {
  candidate_window_observers_.RemoveObserver(observer);
}

void InputMethodManagerImpl::RemoveImeMenuObserver(
    InputMethodManager::ImeMenuObserver* observer) {
  ime_menu_observers_.RemoveObserver(observer);
}

void InputMethodManagerImpl::ChangeInputMethodInternalFromActiveState(
    bool show_message,
    bool notify_menu) {
  // No need to switch input method when terminating.
  if (IsShuttingDown()) {
    VLOG(1) << "No need to switch input method when terminating.";
    return;
  }

  if (candidate_window_controller_.get()) {
    candidate_window_controller_->Hide();
  }

  if (notify_menu) {
    // Clear property list.  Property list would be updated by
    // extension IMEs via TextInputMethod::(Set|Update)MenuItems.
    // If the current input method is a keyboard layout, empty
    // properties are sufficient.
    const ui::ime::InputMethodMenuItemList empty_menu_item_list;
    ui::ime::InputMethodMenuManager* input_method_menu_manager =
        ui::ime::InputMethodMenuManager::GetInstance();
    input_method_menu_manager->SetCurrentInputMethodMenuItemList(
        empty_menu_item_list);
  }

  // Disable the current engine handler.
  TextInputMethod* engine = IMEBridge::Get()->GetCurrentEngineHandler();
  if (engine) {
    engine->Disable();
  }

  // Configure the next engine handler.
  // This must be after |current_input_method_| has been set to new input
  // method, because engine's Enable() method needs to access it.
  const std::string& extension_id =
      extension_ime_util::GetExtensionIDFromInputMethodID(
          state_->GetCurrentInputMethod().id());
  const std::string& component_id =
      extension_ime_util::GetComponentIDByInputMethodID(
          state_->GetCurrentInputMethod().id());
  if (!engine_map_.count(state_->GetProfile()) ||
      !engine_map_[state_->GetProfile()].count(extension_id)) {
    LOG_IF(ERROR, base::SysInfo::IsRunningOnChromeOS())
        << "IMEEngine for \"" << extension_id << "\" is not registered";
  }
  engine = engine_map_[state_->GetProfile()][extension_id];

  IMEBridge::Get()->SetCurrentEngineHandler(engine);

  if (engine) {
    engine->Enable(component_id);
  } else {
    // If no engine to enable, cancel the virtual keyboard url override so that
    // it can use the fallback system virtual keyboard UI.
    state_->DisableInputView();
    ReloadKeyboard();
  }

  // Change the keyboard layout to a preferred layout for the input method.
  keyboard_->SetCurrentKeyboardLayoutByName(
      state_->GetCurrentInputMethod().keyboard_layout(),
      base::BindOnce(&InputMethodManagerImpl::NotifyInputMethodChanged,
                     base::Unretained(this), show_message));

  // Update the current input method in IME menu.
  NotifyImeMenuListChanged();
}

void InputMethodManagerImpl::NotifyInputMethodChanged(bool show_message,
                                                      bool success) {
  if (!success) {
    LOG(ERROR) << "Failed to change keyboard layout to "
               << state_->GetCurrentInputMethod().keyboard_layout();
  }

  // Update input method indicators (e.g. "US", "DV") in Chrome windows.
  for (auto& observer : observers_) {
    observer.InputMethodChanged(this, state_->GetProfile(), show_message);
  }
}

void InputMethodManagerImpl::ActivateInputMethodMenuItem(
    const std::string& key) {
  DCHECK(!key.empty());

  if (ui::ime::InputMethodMenuManager::GetInstance()
          ->HasInputMethodMenuItemForKey(key)) {
    TextInputMethod* engine = IMEBridge::Get()->GetCurrentEngineHandler();
    if (engine) {
      engine->PropertyActivate(key);
    }
    return;
  }

  DVLOG(1) << "ActivateInputMethodMenuItem: unknown key: " << key;
}

void InputMethodManagerImpl::ConnectInputEngineManager(
    mojo::PendingReceiver<ime::mojom::InputEngineManager> receiver) {
  DCHECK(state_);
  ImeServiceConnectorMap::iterator iter =
      ime_service_connectors_.find(state_->GetProfile());
  if (iter == ime_service_connectors_.end()) {
    auto connector_ =
        std::make_unique<ImeServiceConnector>(state_->GetProfile());
    iter =
        ime_service_connectors_
            .insert(std::make_pair(state_->GetProfile(), std::move(connector_)))
            .first;
  }
  iter->second->SetupImeService(std::move(receiver));
}

void InputMethodManagerImpl::BindInputMethodUserDataService(
    mojo::PendingReceiver<ime::mojom::InputMethodUserDataService> receiver) {
  DCHECK(state_);
  ImeServiceConnectorMap::iterator iter =
      ime_service_connectors_.find(state_->GetProfile());
  if (iter == ime_service_connectors_.end()) {
    auto connector_ =
        std::make_unique<ImeServiceConnector>(state_->GetProfile());
    iter =
        ime_service_connectors_
            .insert(std::make_pair(state_->GetProfile(), std::move(connector_)))
            .first;
  }
  iter->second->BindInputMethodUserDataService(std::move(receiver));
}

bool InputMethodManagerImpl::IsISOLevel5ShiftUsedByCurrentInputMethod() const {
  return keyboard_->IsISOLevel5ShiftAvailable();
}

bool InputMethodManagerImpl::IsAltGrUsedByCurrentInputMethod() const {
  return keyboard_->IsAltGrAvailable();
}

bool InputMethodManagerImpl::ArePositionalShortcutsUsedByCurrentInputMethod()
    const {
  if (!state_ || !::features::IsImprovedKeyboardShortcutsEnabled()) {
    return false;
  }

  return !non_positional_layouts_.contains(
      state_.get()->GetCurrentInputMethod().keyboard_layout());
}

ImeKeyboard* InputMethodManagerImpl::GetImeKeyboard() {
  return keyboard_.get();
}

InputMethodUtil* InputMethodManagerImpl::GetInputMethodUtil() {
  return &util_;
}

ComponentExtensionIMEManager*
InputMethodManagerImpl::GetComponentExtensionIMEManager() {
  return component_extension_ime_manager_.get();
}

scoped_refptr<InputMethodManager::State> InputMethodManagerImpl::CreateNewState(
    Profile* profile) {
  // Enabled and current (active) IM should be set to owner/user's default.
  PrefService* prefs = g_browser_process->local_state();
  PrefService* user_prefs = profile ? profile->GetPrefs() : nullptr;
  std::string initial_input_method_id;
  if (user_prefs) {
    initial_input_method_id =
        user_prefs->GetString(prefs::kLanguageCurrentInputMethod);
  }
  if (initial_input_method_id.empty()) {
    initial_input_method_id =
        prefs->GetString(language_prefs::kPreferredKeyboardLayout);
  }

  const InputMethodDescriptor* descriptor =
      GetInputMethodUtil()->GetInputMethodDescriptorFromId(
          initial_input_method_id.empty()
              ? GetInputMethodUtil()->GetFallbackInputMethodDescriptor().id()
              : initial_input_method_id);

  auto* new_state = new StateImpl(this, profile, descriptor);
  return scoped_refptr<InputMethodManager::State>(new_state);
}

void InputMethodManagerImpl::SetCandidateWindowControllerForTesting(
    CandidateWindowController* candidate_window_controller) {
  candidate_window_controller_.reset(candidate_window_controller);
  candidate_window_controller_->AddObserver(this);
}

void InputMethodManagerImpl::OnAppTerminating() {
  if (candidate_window_controller_.get()) {
    candidate_window_controller_.reset();
  }

  if (assistive_window_controller_.get()) {
    assistive_window_controller_.reset();
    IMEBridge::Get()->SetAssistiveWindowHandler(nullptr);
  }
}

void InputMethodManagerImpl::CandidateClicked(int index) {
  TextInputMethod* engine = IMEBridge::Get()->GetCurrentEngineHandler();
  if (engine) {
    engine->CandidateClicked(index);
  }
}

void InputMethodManagerImpl::CandidateWindowOpened() {
  for (auto& observer : candidate_window_observers_) {
    observer.CandidateWindowOpened(this);
  }
}

void InputMethodManagerImpl::CandidateWindowClosed() {
  for (auto& observer : candidate_window_observers_) {
    observer.CandidateWindowClosed(this);
  }
}

void InputMethodManagerImpl::AssistiveWindowButtonClicked(
    const ui::ime::AssistiveWindowButton& button) const {
  TextInputMethod* engine = IMEBridge::Get()->GetCurrentEngineHandler();
  if (engine) {
    engine->AssistiveWindowButtonClicked(button);
  }
}

void InputMethodManagerImpl::AssistiveWindowChanged(
    const ash::ime::AssistiveWindow& window) const {
  TextInputMethod* engine = IMEBridge::Get()->GetCurrentEngineHandler();
  if (engine) {
    engine->AssistiveWindowChanged(window);
  }
}

void InputMethodManagerImpl::ImeMenuActivationChanged(bool is_active) {
  // Saves the state that whether the expanded IME menu has been activated by
  // users. This method is only called when the preference is changing.
  state_->SetMenuActivated(is_active);
  MaybeNotifyImeMenuActivationChanged();
}

void InputMethodManagerImpl::NotifyInputMethodExtensionAdded(
    const std::string& extension_id) {
  for (auto& observer : observers_) {
    observer.OnInputMethodExtensionAdded(extension_id);
  }
}

void InputMethodManagerImpl::NotifyInputMethodExtensionRemoved(
    const std::string& extension_id) {
  for (auto& observer : observers_) {
    observer.OnInputMethodExtensionRemoved(extension_id);
  }
}

void InputMethodManagerImpl::NotifyImeMenuListChanged() {
  for (auto& observer : ime_menu_observers_) {
    observer.ImeMenuListChanged();
  }
}

void InputMethodManagerImpl::MaybeInitializeCandidateWindowController() {
  if (candidate_window_controller_.get()) {
    return;
  }

  candidate_window_controller_.reset(
      CandidateWindowController::CreateCandidateWindowController());
  candidate_window_controller_->AddObserver(this);
}

void InputMethodManagerImpl::MaybeInitializeAssistiveWindowController() {
  if (assistive_window_controller_.get()) {
    return;
  }

  assistive_window_controller_ =
      std::make_unique<AssistiveWindowController>(this, state_->GetProfile());
  IMEBridge::Get()->SetAssistiveWindowHandler(
      assistive_window_controller_.get());
}

void InputMethodManagerImpl::NotifyImeMenuItemsChanged(
    const std::string& engine_id,
    const std::vector<InputMethodManager::MenuItem>& items) {
  for (auto& observer : ime_menu_observers_) {
    observer.ImeMenuItemsChanged(engine_id, items);
  }
}

void InputMethodManagerImpl::MaybeNotifyImeMenuActivationChanged() {
  if (is_ime_menu_activated_ == state_->IsMenuActivated()) {
    return;
  }

  is_ime_menu_activated_ = state_->IsMenuActivated();
  for (auto& observer : ime_menu_observers_) {
    observer.ImeMenuActivationChanged(is_ime_menu_activated_);
  }
}

void InputMethodManagerImpl::OverrideKeyboardKeyset(ImeKeyset keyset) {
  GURL url = state_->GetInputViewUrl();

  // If fails to find ref or tag "id" in the ref, it means the current IME is
  // not system IME, and we don't support show emoji, handwriting or voice
  // input for such IME extension.
  if (!url.has_ref()) {
    return;
  }
  std::string overridden_ref = url.ref();

  auto id_start = overridden_ref.find("id=");
  if (id_start == std::string::npos) {
    return;
  }

  if (keyset == ImeKeyset::kNone) {
    // Resets the url as the input method default url and notify the hash
    // changed to VK.
    state_->ResetInputViewUrl();
    ReloadKeyboard();
    return;
  }

  // For IME component extension, the input view url is overridden as:
  // chrome-extension://${extension_id}/inputview.html#id=us.compact.qwerty
  // &language=en-US&passwordLayout=us.compact.qwerty&name=keyboard_us
  // For emoji, handwriting and voice input, we append the keyset to the end of
  // id like: id=${keyset}.emoji/hwt/voice.
  auto id_end = overridden_ref.find("&", id_start + 1);
  std::string id_string = overridden_ref.substr(id_start, id_end - id_start);
  // Remove existing keyset string.
  for (const ImeKeyset keyset_to_find : kKeysets) {
    std::string keyset_string = KeysetToString(keyset_to_find);
    auto keyset_start = id_string.find("." + keyset_string);
    if (keyset_start != std::string::npos) {
      id_string.replace(keyset_start, keyset_string.length() + 1, "");
    }
  }
  id_string += "." + KeysetToString(keyset);
  overridden_ref.replace(id_start, id_end - id_start, id_string);

  // Always add a timestamp tag to make sure the hash tags are changed, so that
  // the frontend will reload.
  auto ts_start = overridden_ref.find("&ts=");
  std::string ts_tag =
      base::StringPrintf("&ts=%" PRId64, base::Time::NowFromSystemTime()
                                             .ToDeltaSinceWindowsEpoch()
                                             .InMicroseconds());
  if (ts_start == std::string::npos) {
    overridden_ref += ts_tag;
  } else {
    auto ts_end = overridden_ref.find("&", ts_start + 1);
    if (ts_end == std::string::npos) {
      overridden_ref.replace(ts_start, overridden_ref.length() - ts_start,
                             ts_tag);
    } else {
      overridden_ref.replace(ts_start, ts_end - ts_start, ts_tag);
    }
  }

  GURL::Replacements replacements;
  replacements.SetRefStr(overridden_ref);
  state_->OverrideInputViewUrl(url.ReplaceComponents(replacements));
  ReloadKeyboard();
}

void InputMethodManagerImpl::SetImeMenuFeatureEnabled(ImeMenuFeature feature,
                                                      bool enabled) {
  const uint32_t original_state = features_enabled_state_;
  if (enabled) {
    features_enabled_state_ |= feature;
  } else {
    features_enabled_state_ &= ~feature;
  }
  if (original_state != features_enabled_state_) {
    NotifyObserversImeExtraInputStateChange();
  }
}

bool InputMethodManagerImpl::GetImeMenuFeatureEnabled(
    ImeMenuFeature feature) const {
  return features_enabled_state_ & feature;
}

void InputMethodManagerImpl::NotifyObserversImeExtraInputStateChange() {
  for (auto& observer : observers_) {
    const bool is_emoji_enabled =
        (features_enabled_state_ & InputMethodManager::FEATURE_EMOJI);
    const bool is_handwriting_enabled =
        (features_enabled_state_ & InputMethodManager::FEATURE_HANDWRITING);
    const bool is_voice_enabled =
        (features_enabled_state_ & InputMethodManager::FEATURE_VOICE);
    observer.OnExtraInputEnabledStateChange(
        true, is_emoji_enabled, is_handwriting_enabled, is_voice_enabled);
  }
}

void InputMethodManagerImpl::ReloadKeyboard() {
  auto* keyboard_client = ChromeKeyboardControllerClient::Get();
  if (keyboard_client->is_keyboard_enabled()) {
    keyboard_client->ReloadKeyboardIfNeeded();
  }
}

}  // namespace input_method
}  // namespace ash