File: TSFTextStoreBase.cpp

package info (click to toggle)
firefox 146.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,653,260 kB
  • sloc: cpp: 7,587,892; javascript: 6,509,455; ansic: 3,755,295; python: 1,410,813; xml: 629,201; asm: 438,677; java: 186,096; sh: 62,697; makefile: 18,086; objc: 13,087; perl: 12,811; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (1300 lines) | stat: -rw-r--r-- 45,568 bytes parent folder | download | duplicates (7)
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "TSFTextStoreBase.h"

#include "IMMHandler.h"
#include "TSFInputScope.h"
#include "TSFTextStore.h"
#include "TSFUtils.h"
#include "WinIMEHandler.h"
#include "WinMessages.h"
#include "WinUtils.h"
#include "mozilla/Assertions.h"
#include "mozilla/Logging.h"
#include "mozilla/StaticPrefs_intl.h"
#include "mozilla/TextEventDispatcher.h"
#include "mozilla/TextEvents.h"
#include "mozilla/ToString.h"
#include "nsWindow.h"

#include <comutil.h>  // for _bstr_t
#include <oleauto.h>  // for SysAllocString
#include <olectl.h>

// For collecting other people's log, tell `MOZ_LOG=IMEHandler:4,sync`
// rather than `MOZ_LOG=IMEHandler:5,sync` since using `5` may create too
// big file.
// Therefore you shouldn't use `LogLevel::Verbose` for logging usual behavior.
extern mozilla::LazyLogModule gIMELog;  // defined in TSFUtils.cpp

namespace mozilla::widget {

/**
 * TSF related code should log its behavior even on release build especially
 * in the interface methods.
 *
 * In interface methods, use LogLevel::Info.
 * In internal methods, use LogLevel::Debug for logging normal behavior.
 * For logging error, use LogLevel::Error.
 *
 * When an instance method is called, start with following text:
 *   "0x%p TSFFoo::Bar(", the 0x%p should be the "this" of the nsFoo.
 * after that, start with:
 *   "0x%p   TSFFoo::Bar("
 * In an internal method, start with following text:
 *   "0x%p   TSFFoo::Bar("
 * When a static method is called, start with following text:
 *   "TSFFoo::Bar("
 */

/******************************************************************/
/* TSFTextStoreBase                                               */
/******************************************************************/

bool TSFTextStoreBase::InitBase(nsWindow* aWidget,
                                const InputContext& aContext) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::InitBase(aWidget=0x%p, aContext=%s)", this,
           aWidget, mozilla::ToString(aContext).c_str()));

  if (NS_WARN_IF(!aWidget) || NS_WARN_IF(aWidget->Destroyed())) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::InitBase() FAILED due to being "
             "initialized with "
             "destroyed widget",
             this));
    return false;
  }

  if (mDocumentMgr) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::InitBase() FAILED due to already "
             "initialized",
             this));
    return false;
  }

  mWidget = aWidget;
  if (NS_WARN_IF(!mWidget)) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::InitBase() FAILED "
             "due to aWidget is nullptr ",
             this));
    return false;
  }
  mDispatcher = mWidget->GetTextEventDispatcher();
  if (NS_WARN_IF(!mDispatcher)) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::InitBase() FAILED "
             "due to aWidget->GetTextEventDispatcher() failure",
             this));
    return false;
  }

  mInPrivateBrowsing = aContext.mInPrivateBrowsing;
  SetInputScope(aContext.mHTMLInputType, aContext.mHTMLInputMode);

  if (aContext.mURI) {
    // We don't need the document URL if it fails, let's ignore the error.
    nsAutoCString spec;
    if (NS_SUCCEEDED(aContext.mURI->GetSpec(spec))) {
      CopyUTF8toUTF16(spec, mDocumentURL);
    }
  }

  return true;
}

STDMETHODIMP TSFTextStoreBase::QueryInterface(REFIID riid, void** ppv) {
  *ppv = nullptr;
  if ((IID_IUnknown == riid) || (IID_ITextStoreACP == riid)) {
    *ppv = static_cast<ITextStoreACP*>(this);
  }
  if (*ppv) {
    AddRef();
    return S_OK;
  }
  return E_NOINTERFACE;
}

STDMETHODIMP TSFTextStoreBase::AdviseSink(REFIID riid, IUnknown* punk,
                                          DWORD dwMask) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::AdviseSink(riid=%s, punk=0x%p, dwMask=%s), "
           "mSink=0x%p, mSinkMask=%s",
           this, AutoRiidCString(riid).get(), punk,
           AutoSinkMasksCString(dwMask).get(), mSink.get(),
           AutoSinkMasksCString(mSinkMask).get()));

  if (!punk) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::AdviseSink() FAILED due to the null punk",
         this));
    return E_UNEXPECTED;
  }

  if (IID_ITextStoreACPSink != riid) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::AdviseSink() FAILED due to "
             "unsupported interface",
             this));
    return E_INVALIDARG;  // means unsupported interface.
  }

  if (!mSink) {
    // Install sink
    punk->QueryInterface(IID_ITextStoreACPSink, getter_AddRefs(mSink));
    if (!mSink) {
      MOZ_LOG(gIMELog, LogLevel::Error,
              ("0x%p   TSFTextStoreBase::AdviseSink() FAILED due to "
               "punk not having the interface",
               this));
      return E_UNEXPECTED;
    }
  } else {
    // If sink is already installed we check to see if they are the same
    // Get IUnknown from both sides for comparison
    RefPtr<IUnknown> comparison1, comparison2;
    punk->QueryInterface(IID_IUnknown, getter_AddRefs(comparison1));
    mSink->QueryInterface(IID_IUnknown, getter_AddRefs(comparison2));
    if (comparison1 != comparison2) {
      MOZ_LOG(gIMELog, LogLevel::Error,
              ("0x%p   TSFTextStoreBase::AdviseSink() FAILED due to "
               "the sink being different from the stored sink",
               this));
      return CONNECT_E_ADVISELIMIT;
    }
  }
  // Update mask either for a new sink or an existing sink
  mSinkMask = dwMask;
  return S_OK;
}

STDMETHODIMP TSFTextStoreBase::UnadviseSink(IUnknown* punk) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::UnadviseSink(punk=0x%p), mSink=0x%p", this,
           punk, mSink.get()));

  if (!punk) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::UnadviseSink() FAILED due to the null punk",
         this));
    return E_INVALIDARG;
  }
  if (!mSink) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::UnadviseSink() FAILED due to "
             "any sink not stored",
             this));
    return CONNECT_E_NOCONNECTION;
  }
  // Get IUnknown from both sides for comparison
  RefPtr<IUnknown> comparison1, comparison2;
  punk->QueryInterface(IID_IUnknown, getter_AddRefs(comparison1));
  mSink->QueryInterface(IID_IUnknown, getter_AddRefs(comparison2));
  // Unadvise only if sinks are the same
  if (comparison1 != comparison2) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::UnadviseSink() FAILED due to "
             "the sink being different from the stored sink",
             this));
    return CONNECT_E_NOCONNECTION;
  }
  mSink = nullptr;
  mSinkMask = 0;
  return S_OK;
}

STDMETHODIMP TSFTextStoreBase::RequestLock(DWORD dwLockFlags,
                                           HRESULT* phrSession) {
  MOZ_LOG(
      gIMELog, LogLevel::Info,
      ("0x%p TSFTextStoreBase::RequestLock(dwLockFlags=%s, phrSession=0x%p), "
       "mLock=%s, mDestroyed=%s",
       this, AutoLockFlagsCString(dwLockFlags).get(), phrSession,
       AutoLockFlagsCString(mLock).get(), TSFUtils::BoolToChar(mDestroyed)));

  if (!mSink) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::RequestLock() FAILED due to "
             "any sink not stored",
             this));
    return E_FAIL;
  }
  if (mDestroyed) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::RequestLock() FAILED due to being destroyed",
         this));
    return E_FAIL;
  }
  if (!phrSession) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::RequestLock() FAILED due to "
             "null phrSession",
             this));
    return E_INVALIDARG;
  }

  if (!mLock) {
    // put on lock
    mLock = dwLockFlags & (~TS_LF_SYNC);
    MOZ_LOG(
        gIMELog, LogLevel::Info,
        ("0x%p   Locking (%s) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
         ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",
         this, AutoLockFlagsCString(mLock).get()));
    // Don't release this instance during this lock because this is called by
    // TSF but they don't grab us during this call.
    const RefPtr<TSFTextStoreBase> kungFuDeathGrip(this);
    const RefPtr<ITextStoreACPSink> sink = mSink;
    *phrSession = sink->OnLockGranted(mLock);
    MOZ_LOG(
        gIMELog, LogLevel::Info,
        ("0x%p   Unlocked (%s) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
         "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<",
         this, AutoLockFlagsCString(mLock).get()));
    DidLockGranted();
    while (mLockQueued) {
      mLock = mLockQueued;
      mLockQueued = 0;
      MOZ_LOG(gIMELog, LogLevel::Info,
              ("0x%p   Locking for the request in the queue (%s) >>>>>>>>>>>>>>"
               ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
               ">>>>>",
               this, AutoLockFlagsCString(mLock).get()));
      sink->OnLockGranted(mLock);
      MOZ_LOG(gIMELog, LogLevel::Info,
              ("0x%p   Unlocked (%s) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
               "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
               "<<<<<",
               this, AutoLockFlagsCString(mLock).get()));
      DidLockGranted();
    }

    // The document is now completely unlocked.
    mLock = 0;

    MOZ_LOG(gIMELog, LogLevel::Info,
            ("0x%p   TSFTextStoreBase::RequestLock() succeeded: *phrSession=%s",
             this, TSFUtils::HRESULTToChar(*phrSession)));
    return S_OK;
  }

  // only time when reentrant lock is allowed is when caller holds a
  // read-only lock and is requesting an async write lock
  if (IsReadLocked() && !IsReadWriteLocked() && IsReadWriteLock(dwLockFlags) &&
      !(dwLockFlags & TS_LF_SYNC)) {
    *phrSession = TS_S_ASYNC;
    mLockQueued = dwLockFlags & (~TS_LF_SYNC);

    MOZ_LOG(gIMELog, LogLevel::Info,
            ("0x%p   TSFTextStoreBase::RequestLock() stores the request in the "
             "queue, *phrSession=TS_S_ASYNC",
             this));
    return S_OK;
  }

  // no more locks allowed
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p   TSFTextStoreBase::RequestLock() didn't allow to lock, "
           "*phrSession=TS_E_SYNCHRONOUS",
           this));
  *phrSession = TS_E_SYNCHRONOUS;
  return E_FAIL;
}

void TSFTextStoreBase::DispatchEvent(WidgetGUIEvent& aEvent) {
  if (NS_WARN_IF(!mWidget) || NS_WARN_IF(mWidget->Destroyed())) {
    return;
  }
  mWidget->DispatchWindowEvent(aEvent);
}

STDMETHODIMP TSFTextStoreBase::GetStatus(TS_STATUS* pdcs) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetStatus(pdcs=0x%p)", this, pdcs));

  if (!pdcs) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::GetStatus() FAILED due to null pdcs", this));
    return E_INVALIDARG;
  }
  // We manage on-screen keyboard by own.
  pdcs->dwDynamicFlags = TS_SD_INPUTPANEMANUALDISPLAYENABLE;
  // we use a "flat" text model for TSF support so no hidden text
  pdcs->dwStaticFlags = TS_SS_NOHIDDENTEXT;
  return S_OK;
}

STDMETHODIMP TSFTextStoreBase::QueryInsert(LONG acpTestStart, LONG acpTestEnd,
                                           ULONG cch, LONG* pacpResultStart,
                                           LONG* pacpResultEnd) {
  MOZ_LOG(
      gIMELog, LogLevel::Info,
      ("0x%p TSFTextStoreBase::QueryInsert(acpTestStart=%ld, "
       "acpTestEnd=%ld, cch=%lu, pacpResultStart=0x%p, pacpResultEnd=0x%p)",
       this, acpTestStart, acpTestEnd, cch, pacpResultStart, pacpResultEnd));

  if (!pacpResultStart || !pacpResultEnd) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::QueryInsert() FAILED due to "
             "the null argument",
             this));
    return E_INVALIDARG;
  }

  if (acpTestStart < 0 || acpTestStart > acpTestEnd) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::QueryInsert() FAILED due to "
             "wrong argument",
             this));
    return E_INVALIDARG;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::GetSelection(ULONG ulIndex, ULONG ulCount,
                                            TS_SELECTION_ACP* pSelection,
                                            ULONG* pcFetched) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetSelection(ulIndex=%lu, ulCount=%lu, "
           "pSelection=0x%p, pcFetched=0x%p)",
           this, ulIndex, ulCount, pSelection, pcFetched));

  if (!IsReadLocked()) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetSelection() FAILED due to not locked",
             this));
    return TS_E_NOLOCK;
  }
  if (!ulCount || !pSelection || !pcFetched) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::GetSelection() FAILED due to null argument",
         this));
    return E_INVALIDARG;
  }

  *pcFetched = 0;

  if (ulIndex != static_cast<ULONG>(TS_DEFAULT_SELECTION) && ulIndex != 0) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetSelection() FAILED due to "
             "unsupported selection",
             this));
    return TS_E_NOSELECTION;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::SetSelection(
    ULONG ulCount, const TS_SELECTION_ACP* pSelection) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::SetSelection(ulCount=%lu, pSelection=%s })",
           this, ulCount,
           pSelection ? mozilla::ToString(pSelection).c_str() : "nullptr"));

  if (!IsReadWriteLocked()) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::SetSelection() FAILED due to "
             "not locked (read-write)",
             this));
    return TS_E_NOLOCK;
  }
  if (ulCount != 1) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::SetSelection() FAILED due to "
             "trying setting multiple selection",
             this));
    return E_INVALIDARG;
  }
  if (!pSelection) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::SetSelection() FAILED due to "
             "null argument",
             this));
    return E_INVALIDARG;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::GetText(LONG acpStart, LONG acpEnd,
                                       WCHAR* pchPlain, ULONG cchPlainReq,
                                       ULONG* pcchPlainOut,
                                       TS_RUNINFO* prgRunInfo,
                                       ULONG ulRunInfoReq, ULONG* pulRunInfoOut,
                                       LONG* pacpNext) {
  MOZ_LOG(
      gIMELog, LogLevel::Info,
      ("0x%p TSFTextStoreBase::GetText(acpStart=%ld, acpEnd=%ld, "
       "pchPlain=0x%p, cchPlainReq=%lu, pcchPlainOut=0x%p, prgRunInfo=0x%p, "
       "ulRunInfoReq=%lu, pulRunInfoOut=0x%p, pacpNext=0x%p)",
       this, acpStart, acpEnd, pchPlain, cchPlainReq, pcchPlainOut, prgRunInfo,
       ulRunInfoReq, pulRunInfoOut, pacpNext));

  if (!IsReadLocked()) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetText() FAILED due to "
             "not locked (read)",
             this));
    return TS_E_NOLOCK;
  }

  if (!pcchPlainOut || (!pchPlain && !prgRunInfo) ||
      !cchPlainReq != !pchPlain || !ulRunInfoReq != !prgRunInfo) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetText() FAILED due to "
             "invalid argument",
             this));
    return E_INVALIDARG;
  }

  if (acpStart < 0 || acpEnd < -1 || (acpEnd != -1 && acpStart > acpEnd)) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetText() FAILED due to "
             "invalid position",
             this));
    return TS_E_INVALIDPOS;
  }

  // Making sure to null-terminate string just to be on the safe side
  *pcchPlainOut = 0;
  if (pchPlain && cchPlainReq) {
    *pchPlain = 0;
  }
  if (pulRunInfoOut) {
    *pulRunInfoOut = 0;
  }
  if (pacpNext) {
    *pacpNext = acpStart;
  }
  if (prgRunInfo && ulRunInfoReq) {
    prgRunInfo->uCount = 0;
    prgRunInfo->type = TS_RT_PLAIN;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::SetText(DWORD dwFlags, LONG acpStart,
                                       LONG acpEnd, const WCHAR* pchText,
                                       ULONG cch, TS_TEXTCHANGE* pChange) {
  MOZ_LOG(
      gIMELog, LogLevel::Info,
      ("0x%p TSFTextStoreBase::SetText(dwFlags=%s, acpStart=%ld, acpEnd=%ld, "
       "pchText=0x%p \"%s\", cch=%lu, pChange=0x%p)",
       this, dwFlags == TS_ST_CORRECTION ? "TS_ST_CORRECTION" : "not-specified",
       acpStart, acpEnd, pchText,
       pchText && cch ? AutoEscapedUTF8String(pchText, cch).get() : "", cch,
       pChange));

  // Per SDK documentation, and since we don't have better
  // ways to do this, this method acts as a helper to
  // call SetSelection followed by InsertTextAtSelection
  if (!IsReadWriteLocked()) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::SetText() FAILED due to not locked (read)",
         this));
    return TS_E_NOLOCK;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::GetFormattedText(LONG acpStart, LONG acpEnd,
                                                IDataObject** ppDataObject) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetFormattedText() called "
           "but not supported (E_NOTIMPL)",
           this));

  // no support for formatted text
  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::GetEmbedded(LONG acpPos, REFGUID rguidService,
                                           REFIID riid, IUnknown** ppunk) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetEmbedded() called "
           "but not supported (E_NOTIMPL)",
           this));

  // embedded objects are not supported
  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::QueryInsertEmbedded(const GUID* pguidService,
                                                   const FORMATETC* pFormatEtc,
                                                   BOOL* pfInsertable) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::QueryInsertEmbedded() called "
           "but not supported, *pfInsertable=FALSE (S_OK)",
           this));

  // embedded objects are not supported
  *pfInsertable = FALSE;
  return S_OK;
}

STDMETHODIMP TSFTextStoreBase::InsertEmbedded(DWORD dwFlags, LONG acpStart,
                                              LONG acpEnd,
                                              IDataObject* pDataObject,
                                              TS_TEXTCHANGE* pChange) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::InsertEmbedded() called "
           "but not supported (E_NOTIMPL)",
           this));

  // embedded objects are not supported
  return E_NOTIMPL;
}

void TSFTextStoreBase::SetInputScope(const nsString& aHTMLInputType,
                                     const nsString& aHTMLInputMode) {
  mInputScopes.Clear();

  // IME may refer only first input scope, but we will append inputmode's
  // input scopes too like Chrome since IME may refer it.
  IMEHandler::AppendInputScopeFromType(aHTMLInputType, mInputScopes);
  IMEHandler::AppendInputScopeFromInputMode(aHTMLInputMode, mInputScopes);

  if (mInPrivateBrowsing) {
    mInputScopes.AppendElement(IS_PRIVATE);
  }
}

STDMETHODIMP TSFTextStoreBase::RequestAttrsTransitioningAtPosition(
    LONG acpPos, ULONG cFilterAttrs, const TS_ATTRID* paFilterAttr,
    DWORD dwFlags) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::RequestAttrsTransitioningAtPosition("
           "acpPos=%ld, cFilterAttrs=%lu, dwFlags=%s) called but not supported "
           "(S_OK)",
           this, acpPos, cFilterAttrs, AutoFindFlagsCString(dwFlags).get()));

  // no per character attributes defined
  return S_OK;
}

STDMETHODIMP TSFTextStoreBase::FindNextAttrTransition(
    LONG acpStart, LONG acpHalt, ULONG cFilterAttrs,
    const TS_ATTRID* paFilterAttrs, DWORD dwFlags, LONG* pacpNext,
    BOOL* pfFound, LONG* plFoundOffset) {
  if (!pacpNext || !pfFound || !plFoundOffset) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("  0x%p TSFTextStoreBase::FindNextAttrTransition() FAILED due to "
             "null argument",
             this));
    return E_INVALIDARG;
  }

  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p   TSFTextStoreBase::FindNextAttrTransition() called "
           "but not supported (S_OK)",
           this));

  // no per character attributes defined
  *pacpNext = *plFoundOffset = acpHalt;
  *pfFound = FALSE;
  return S_OK;
}

// To test the document URL result, define this to out put it to the stdout
// #define DEBUG_PRINT_DOCUMENT_URL

BSTR TSFTextStoreBase::GetExposingURL() const {
  const bool allowed =
      StaticPrefs::intl_tsf_expose_url_allowed() &&
      (!mInPrivateBrowsing ||
       StaticPrefs::intl_tsf_expose_url_in_private_browsing_allowed());
  if (!allowed || mDocumentURL.IsEmpty()) {
    BSTR emptyString = ::SysAllocString(L"");
    MOZ_ASSERT(
        emptyString,
        "We need to return valid BSTR pointer to notify TSF of supporting it "
        "with a pointer to empty string");
    return emptyString;
  }
  return ::SysAllocString(mDocumentURL.get());
}

void TSFTextStoreBase::PrintExposingURL(const char* aPrefix) const {
  BSTR exposingURL = GetExposingURL();
  printf("%s: DocumentURL=\"%s\"\n", aPrefix,
         NS_ConvertUTF16toUTF8(static_cast<char16ptr_t>(_bstr_t(exposingURL)))
             .get());
  ::SysFreeString(exposingURL);
}

STDMETHODIMP TSFTextStoreBase::GetEndACP(LONG* pacp) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetEndACP(pacp=0x%p)", this, pacp));

  if (!IsReadLocked()) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::GetEndACP() FAILED due to not locked (read)",
         this));
    return TS_E_NOLOCK;
  }

  if (!pacp) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetEndACP() FAILED due to null argument",
             this));
    return E_INVALIDARG;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::GetActiveView(TsViewCookie* pvcView) {
  MOZ_LOG(
      gIMELog, LogLevel::Info,
      ("0x%p TSFTextStoreBase::GetActiveView(pvcView=0x%p)", this, pvcView));

  if (!pvcView) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetActiveView() FAILED due to "
             "null argument",
             this));
    return E_INVALIDARG;
  }

  *pvcView = TSFUtils::sDefaultView;

  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p   TSFTextStoreBase::GetActiveView() succeeded: *pvcView=%ld",
           this, *pvcView));
  return S_OK;
}

STDMETHODIMP TSFTextStoreBase::GetACPFromPoint(TsViewCookie vcView,
                                               const POINT* pt, DWORD dwFlags,
                                               LONG* pacp) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetACPFromPoint(pvcView=%ld, pt=%p (x=%ld, "
           "y=%ld), dwFlags=%s, pacp=%p, mDeferNotifyingTSFUntilNextUpdate=%s, "
           "mWaitingQueryLayout=%s",
           this, vcView, pt, pt ? pt->x : 0, pt ? pt->y : 0,
           AutoACPFromPointFlagsCString(dwFlags).get(), pacp,
           TSFUtils::BoolToChar(mDeferNotifyingTSFUntilNextUpdate),
           TSFUtils::BoolToChar(mWaitingQueryLayout)));

  if (!IsReadLocked()) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetACPFromPoint() FAILED due to not "
             "locked (read)",
             this));
    return TS_E_NOLOCK;
  }

  if (vcView != TSFUtils::sDefaultView) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetACPFromPoint() FAILED due to called "
             "with invalid view",
             this));
    return E_INVALIDARG;
  }

  if (!pt) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetACPFromPoint() FAILED due to null pt",
             this));
    return E_INVALIDARG;
  }

  if (!pacp) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::GetACPFromPoint() FAILED due to null pacp",
         this));
    return E_INVALIDARG;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::GetTextExt(TsViewCookie vcView, LONG acpStart,
                                          LONG acpEnd, RECT* prc,
                                          BOOL* pfClipped) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetTextExt(vcView=%ld, "
           "acpStart=%ld, acpEnd=%ld, prc=0x%p, pfClipped=0x%p), "
           "IsHandlingCompositionInParent()=%s, "
           "IsHandlingCompositionInContent()=%s,"
           "mDeferNotifyingTSFUntilNextUpdate=%s, mWaitingQueryLayout=%s, "
           "IMEHandler::IsA11yHandlingNativeCaret()=%s",
           this, vcView, acpStart, acpEnd, prc, pfClipped,
           TSFUtils::BoolToChar(IsHandlingCompositionInParent()),
           TSFUtils::BoolToChar(IsHandlingCompositionInContent()),
           TSFUtils::BoolToChar(mDeferNotifyingTSFUntilNextUpdate),
           TSFUtils::BoolToChar(mWaitingQueryLayout),
           TSFUtils::BoolToChar(IMEHandler::IsA11yHandlingNativeCaret())));

  if (!IsReadLocked()) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetTextExt() FAILED due to not locked "
             "(read)",
             this));
    return TS_E_NOLOCK;
  }

  if (vcView != TSFUtils::sDefaultView) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetTextExt() FAILED due to called with "
             "invalid view",
             this));
    return E_INVALIDARG;
  }

  if (!prc || !pfClipped) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::GetTextExt() FAILED due to null argument",
         this));
    return E_INVALIDARG;
  }

  // According to MSDN, ITextStoreACP::GetTextExt() should return
  // TS_E_INVALIDARG when acpStart and acpEnd are same (i.e., collapsed range).
  // https://msdn.microsoft.com/en-us/library/windows/desktop/ms538435(v=vs.85).aspx
  // > TS_E_INVALIDARG: The specified start and end character positions are
  // >                  equal.
  // However, some TIPs (including Microsoft's Chinese TIPs!) call this with
  // collapsed range and if we return TS_E_INVALIDARG, they stops showing their
  // owning window or shows it but odd position.  So, we should just return
  // error only when acpStart and/or acpEnd are really odd.

  if (acpStart < 0 || acpEnd < acpStart) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::GetTextExt() FAILED due to invalid position",
         this));
    return TS_E_INVALIDPOS;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::GetScreenExt(TsViewCookie vcView, RECT* prc) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetScreenExt(vcView=%ld, prc=0x%p)", this,
           vcView, prc));

  if (vcView != TSFUtils::sDefaultView) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetScreenExt() FAILED due to called "
             "with invalid view",
             this));
    return E_INVALIDARG;
  }

  if (!prc) {
    MOZ_LOG(
        gIMELog, LogLevel::Error,
        ("0x%p   TSFTextStoreBase::GetScreenExt() FAILED due to null argument",
         this));
    return E_INVALIDARG;
  }

  if (mDestroyed) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetScreenExt() returns empty rect "
             "due to already destroyed",
             this));
    prc->left = prc->top = prc->right = prc->bottom = 0;
    return S_OK;
  }

  if (!GetScreenExtInternal(*prc)) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetScreenExt() FAILED due to "
             "GetScreenExtInternal() failure",
             this));
    return E_FAIL;
  }

  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p   TSFTextStoreBase::GetScreenExt() succeeded: "
           "*prc={ left=%ld, top=%ld, right=%ld, bottom=%ld }",
           this, prc->left, prc->top, prc->right, prc->bottom));
  return S_OK;
}

bool TSFTextStoreBase::GetScreenExtInternal(RECT& aScreenExt) {
  MOZ_LOG(gIMELog, LogLevel::Debug,
          ("0x%p   TSFTextStoreBase::GetScreenExtInternal()", this));

  MOZ_ASSERT(!mDestroyed);

  // use NS_QUERY_EDITOR_RECT to get rect in system, screen coordinates
  WidgetQueryContentEvent queryEditorRectEvent(true, eQueryEditorRect, mWidget);
  mWidget->InitEvent(queryEditorRectEvent);
  DispatchEvent(queryEditorRectEvent);
  if (queryEditorRectEvent.Failed()) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetScreenExtInternal() FAILED due to "
             "eQueryEditorRect failure",
             this));
    return false;
  }

  nsWindow* refWindow =
      static_cast<nsWindow*>(!!queryEditorRectEvent.mReply->mFocusedWidget
                                 ? queryEditorRectEvent.mReply->mFocusedWidget
                                 : static_cast<nsIWidget*>(mWidget.get()));
  // Result rect is in top level widget coordinates
  refWindow = refWindow->GetTopLevelWindow(false);
  if (!refWindow) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetScreenExtInternal() FAILED due to "
             "no top level window",
             this));
    return false;
  }

  LayoutDeviceIntRect boundRect = refWindow->GetClientBounds();
  boundRect.MoveTo(0, 0);

  // Clip frame rect to window rect
  boundRect.IntersectRect(queryEditorRectEvent.mReply->mRect, boundRect);
  if (!boundRect.IsEmpty()) {
    boundRect.MoveBy(refWindow->WidgetToScreenOffset());
    ::SetRect(&aScreenExt, boundRect.X(), boundRect.Y(), boundRect.XMost(),
              boundRect.YMost());
  } else {
    ::SetRectEmpty(&aScreenExt);
  }

  MOZ_LOG(gIMELog, LogLevel::Debug,
          ("0x%p   TSFTextStoreBase::GetScreenExtInternal() succeeded: "
           "aScreenExt={ left=%ld, top=%ld, right=%ld, bottom=%ld }",
           this, aScreenExt.left, aScreenExt.top, aScreenExt.right,
           aScreenExt.bottom));
  return true;
}

STDMETHODIMP TSFTextStoreBase::GetWnd(TsViewCookie vcView, HWND* phwnd) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::GetWnd(vcView=%ld, phwnd=0x%p), "
           "mWidget=0x%p",
           this, vcView, phwnd, mWidget.get()));

  if (vcView != TSFUtils::sDefaultView) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetWnd() FAILED due to "
             "called with invalid view",
             this));
    return E_INVALIDARG;
  }

  if (!phwnd) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::GetScreenExt() FAILED due to "
             "null argument",
             this));
    return E_INVALIDARG;
  }

  *phwnd = mWidget ? mWidget->GetWindowHandle() : nullptr;

  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p   TSFTextStoreBase::GetWnd() succeeded: *phwnd=0x%p", this,
           static_cast<void*>(*phwnd)));
  return S_OK;
}

STDMETHODIMP TSFTextStoreBase::InsertTextAtSelection(DWORD dwFlags,
                                                     const WCHAR* pchText,
                                                     ULONG cch, LONG* pacpStart,
                                                     LONG* pacpEnd,
                                                     TS_TEXTCHANGE* pChange) {
  MOZ_LOG(
      gIMELog, LogLevel::Info,
      ("0x%p TSFTextStoreBase::InsertTextAtSelection(dwFlags=%s, "
       "pchText=0x%p \"%s\", cch=%lu, pacpStart=0x%p, pacpEnd=0x%p, "
       "pChange=0x%p)",
       this,
       dwFlags == 0                  ? "0"
       : dwFlags == TF_IAS_NOQUERY   ? "TF_IAS_NOQUERY"
       : dwFlags == TF_IAS_QUERYONLY ? "TF_IAS_QUERYONLY"
                                     : "Unknown",
       pchText, pchText && cch ? AutoEscapedUTF8String(pchText, cch).get() : "",
       cch, pacpStart, pacpEnd, pChange));

  if (cch && !pchText) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::InsertTextAtSelection() FAILED due to "
             "null pchText",
             this));
    return E_INVALIDARG;
  }

  if (TS_IAS_QUERYONLY == dwFlags) {
    if (!IsReadLocked()) {
      MOZ_LOG(gIMELog, LogLevel::Error,
              ("0x%p   TSFTextStoreBase::InsertTextAtSelection() FAILED due to "
               "not locked (read)",
               this));
      return TS_E_NOLOCK;
    }

    if (!pacpStart || !pacpEnd) {
      MOZ_LOG(gIMELog, LogLevel::Error,
              ("0x%p   TSFTextStoreBase::InsertTextAtSelection() FAILED due to "
               "null argument",
               this));
      return E_INVALIDARG;
    }

    return E_NOTIMPL;
  }

  if (!IsReadWriteLocked()) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::InsertTextAtSelection() FAILED due to "
             "not locked (read-write)",
             this));
    return TS_E_NOLOCK;
  }

  if (!pChange) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::InsertTextAtSelection() FAILED due to "
             "null pChange",
             this));
    return E_INVALIDARG;
  }

  if (TS_IAS_NOQUERY != dwFlags && (!pacpStart || !pacpEnd)) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p   TSFTextStoreBase::InsertTextAtSelection() FAILED due to "
             "null argument",
             this));
    return E_INVALIDARG;
  }

  return E_NOTIMPL;
}

STDMETHODIMP TSFTextStoreBase::InsertEmbeddedAtSelection(
    DWORD dwFlags, IDataObject* pDataObject, LONG* pacpStart, LONG* pacpEnd,
    TS_TEXTCHANGE* pChange) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::InsertEmbeddedAtSelection() called "
           "but not supported (E_NOTIMPL)",
           this));

  // embedded objects are not supported
  return E_NOTIMPL;
}

HRESULT TSFTextStoreBase::HandleRequestAttrs(DWORD aFlags, ULONG aFilterCount,
                                             const TS_ATTRID* aFilterAttrs,
                                             int32_t aNumOfSupportedAttrs) {
  MOZ_ASSERT(aNumOfSupportedAttrs == TSFUtils::NUM_OF_SUPPORTED_ATTRS ||
             aNumOfSupportedAttrs ==
                 TSFUtils::NUM_OF_SUPPORTED_ATTRS_IN_EMPTY_TEXT_STORE);
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::HandleRequestAttrs(aFlags=%s, "
           "aFilterCount=%lu, aNumOfSupportedAttrs=%d)",
           this, AutoFindFlagsCString(aFlags).get(), aFilterCount,
           aNumOfSupportedAttrs));

  // This is a little weird! RequestSupportedAttrs gives us advanced notice
  // of a support query via RetrieveRequestedAttrs for a specific attribute.
  // RetrieveRequestedAttrs needs to return valid data for all attributes we
  // support, but the text service will only want the input scope object
  // returned in RetrieveRequestedAttrs if the dwFlags passed in here contains
  // TS_ATTR_FIND_WANT_VALUE.
  for (const int32_t i : IntegerRange(aNumOfSupportedAttrs)) {
    mRequestedAttrs[i] = false;
  }
  mRequestedAttrValues = !!(aFlags & TS_ATTR_FIND_WANT_VALUE);

  for (uint32_t i : IntegerRange(aFilterCount)) {
    MOZ_LOG(gIMELog, LogLevel::Info,
            ("0x%p   TSFEmptyTextStore::HandleRequestAttrs(), "
             "requested attr=%s",
             this, AutoGuidCString(aFilterAttrs[i]).get()));
    TSFUtils::AttrIndex index =
        TSFUtils::GetRequestedAttrIndex(aFilterAttrs[i]);
    if (index != TSFUtils::AttrIndex::NotSupported) {
      mRequestedAttrs[index] = true;
    }
  }
  return S_OK;
}

// To test the document URL result, define this to out put it to the stdout
// #define DEBUG_PRINT_DOCUMENT_URL

HRESULT TSFTextStoreBase::RetrieveRequestedAttrsInternal(
    ULONG ulCount, TS_ATTRVAL* paAttrVals, ULONG* pcFetched,
    int32_t aNumOfSupportedAttrs) {
  MOZ_ASSERT(aNumOfSupportedAttrs == TSFUtils::NUM_OF_SUPPORTED_ATTRS ||
             aNumOfSupportedAttrs ==
                 TSFUtils::NUM_OF_SUPPORTED_ATTRS_IN_EMPTY_TEXT_STORE);

  if (!pcFetched || !paAttrVals) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p TSFTextStoreBase::RetrieveRequestedAttrs() FAILED due to "
             "null argument",
             this));
    return E_INVALIDARG;
  }

  const ULONG expectedCount = [&]() {
    ULONG count = 0;
    for (int32_t i : IntegerRange(aNumOfSupportedAttrs)) {
      if (mRequestedAttrs[i]) {
        count++;
      }
    }
    return count;
  }();
  if (ulCount < expectedCount) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("0x%p TSFTextStoreBase::RetrieveRequestedAttrs() FAILED due to "
             "not enough count ulCount=%lu, expectedCount=%lu",
             this, ulCount, expectedCount));
    return E_INVALIDARG;
  }

  MOZ_LOG(gIMELog, LogLevel::Info,
          ("0x%p TSFTextStoreBase::RetrieveRequestedAttrs() called "
           "ulCount=%lu, mRequestedAttrValues=%s",
           this, ulCount, TSFUtils::BoolToChar(mRequestedAttrValues)));

#ifdef DEBUG_PRINT_DOCUMENT_URL
  PrintExposingURL("TSFTextStoreBase::RetrieveRequestedAttrs");
#endif  // #ifdef DEBUG_PRINT_DOCUMENT_URL

  int32_t count = 0;
  for (int32_t i = 0; i < TSFUtils::NUM_OF_SUPPORTED_ATTRS; i++) {
    if (!mRequestedAttrs[i]) {
      continue;
    }
    mRequestedAttrs[i] = false;

    TS_ATTRID attrID = TSFUtils::GetAttrID(static_cast<TSFUtils::AttrIndex>(i));

    MOZ_LOG(gIMELog, LogLevel::Info,
            ("0x%p   TSFTextStoreBase::RetrieveRequestedAttrs() for %s", this,
             AutoGuidCString(attrID).get()));

    paAttrVals[count].idAttr = attrID;
    paAttrVals[count].dwOverlapId = 0;

    if (!mRequestedAttrValues) {
      paAttrVals[count].varValue.vt = VT_EMPTY;
    } else {
      switch (i) {
        case TSFUtils::AttrIndex::InputScope: {
          paAttrVals[count].varValue.vt = VT_UNKNOWN;
          RefPtr<IUnknown> inputScope = new TSFInputScope(mInputScopes);
          paAttrVals[count].varValue.punkVal = inputScope.forget().take();
          break;
        }
        case TSFUtils::AttrIndex::DocumentURL: {
          paAttrVals[count].varValue.vt = VT_BSTR;
          paAttrVals[count].varValue.bstrVal = GetExposingURL();
          break;
        }
        case TSFUtils::AttrIndex::TextVerticalWriting: {
          const Maybe<WritingMode> writingMode = GetWritingMode();
          paAttrVals[count].varValue.vt = VT_BOOL;
          paAttrVals[count].varValue.boolVal =
              writingMode.isSome() && writingMode->IsVertical() ? VARIANT_TRUE
                                                                : VARIANT_FALSE;
          break;
        }
        case TSFUtils::AttrIndex::TextOrientation: {
          const Maybe<WritingMode> writingMode = GetWritingMode();
          paAttrVals[count].varValue.vt = VT_I4;
          paAttrVals[count].varValue.lVal =
              writingMode.isSome() && writingMode->IsVertical() ? 2700 : 0;
          break;
        }
        default:
          MOZ_CRASH("Invalid index? Or not implemented yet?");
          break;
      }
    }
    count++;
  }

  mRequestedAttrValues = false;

  if (count) {
    *pcFetched = count;
    return S_OK;
  }

  paAttrVals->dwOverlapId = 0;
  paAttrVals->varValue.vt = VT_EMPTY;
  *pcFetched = 0;
  return S_OK;
}

#undef DEBUG_PRINT_DOCUMENT_URL

// static
void TSFTextStoreBase::SetInputContext(nsWindow* aWindow,
                                       const InputContext& aContext,
                                       const InputContextAction& aAction) {
  MOZ_LOG(gIMELog, LogLevel::Info,
          ("TSFTextStoreBase::OnSetInputContext(aWidget=%p, "
           "aContext=%s, aAction.mFocusChange=%s), "
           "CurrentTextStore(0x%p)={ mWidget=0x%p, mContext=0x%p }",
           aWindow, mozilla::ToString(aContext).c_str(),
           mozilla::ToString(aAction.mFocusChange).c_str(),
           TSFUtils::GetCurrentTextStore(),
           TSFUtils::GetCurrentTextStore()
               ? TSFUtils::GetCurrentTextStore()->GetWindow()
               : nullptr,
           TSFUtils::GetCurrentTextStore()
               ? TSFUtils::GetCurrentTextStore()->GetContext()
               : nullptr));

  const bool actuallyEditable =
      aContext.mIMEState.IsEditable() && !aWindow->Destroyed();
  switch (aAction.mFocusChange) {
    case InputContextAction::WIDGET_CREATED:
      // If this is called when the widget is created, there is nothing to do.
      return;
    case InputContextAction::FOCUS_NOT_CHANGED:
    case InputContextAction::MENU_LOST_PSEUDO_FOCUS:
      // In these cases, `NOTIFY_IME_OF_FOCUS` won't be sent.  Therefore,
      // we need to reset text store for new state right now.
      break;
    default: {
      const RefPtr<TSFTextStoreBase> textStore =
          TSFUtils::GetCurrentTextStore();
      if (!textStore) {
        break;
      }
      if (NS_SUCCEEDED(
              textStore->UpdateDocumentURLAndBrowsingMode(aWindow, aContext))) {
        return;
      }
    }
  }

  const bool alreadyEditable = TSFUtils::GetCurrentTextStore() &&
                               TSFUtils::GetCurrentTextStore()->IsEditable() &&
                               TSFUtils::GetCurrentTextStore()->MaybeHasFocus();
  if (alreadyEditable == actuallyEditable) {
    if (const RefPtr<TSFTextStoreBase> textStore =
            TSFUtils::GetCurrentTextStore()) {
      textStore->UpdateDocumentURLAndBrowsingMode(aWindow, aContext);
    }
    return;
  }
  // If focus isn't actually changed but the enabled state is changed, we beed
  // to emulate the focus move.
  if (!alreadyEditable && !IMEHandler::GetFocusedWindow()) {
    MOZ_LOG(gIMELog, LogLevel::Error,
            ("  TSFTextStoreBase::SetInputContent() gets called to enable IME, "
             "but IMEHandler has not received focus notification"));
    if (const RefPtr<TSFTextStoreBase> textStore =
            TSFUtils::GetCurrentTextStore()) {
      textStore->UpdateDocumentURLAndBrowsingMode(aWindow, aContext);
    }
    return;
  }
  TSFUtils::OnFocusChange(
      actuallyEditable ? TSFUtils::GotFocus::Yes : TSFUtils::GotFocus::No,
      aWindow, aContext);
}

nsresult TSFTextStoreBase::UpdateDocumentURLAndBrowsingMode(
    nsWindow* aWindow, const InputContext& aContext) {
  MOZ_ASSERT(aWindow);
  MOZ_LOG(gIMELog, LogLevel::Debug,
          ("0x%p TSFTextStoreBase::UpdateDocumentURLAndBrowsingMode(aWindow=%p "
           "(Destroyed()=%s), aContext=%s), "
           "mIsEditable=%s",
           this, aWindow, aWindow->Destroyed() ? "true" : "false",
           mozilla::ToString(aContext).c_str(),
           mozilla::ToString(mIsEditable).c_str()));

  const bool isEditable =
      aContext.mIMEState.IsEditable() && !aWindow->Destroyed();
  // If IME enabled state is changed, we need to recreate proper
  // TSFTextStoreBase instance.
  if (isEditable != IsEditable()) {
    return NS_ERROR_FAILURE;
  }
  // If the editable state is not changed, we can just update the input
  // scopes and the document URL.
  nsAutoString oldURL(mDocumentURL);
  CopyableAutoTArray<InputScope, 5> oldInputScopes(mInputScopes);
  mInPrivateBrowsing = aContext.mInPrivateBrowsing;
  SetInputScope(aContext.mHTMLInputType, aContext.mHTMLInputMode);
  if (aContext.mURI) {
    nsAutoCString spec;
    if (NS_SUCCEEDED(aContext.mURI->GetSpec(spec))) {
      CopyUTF8toUTF16(spec, mDocumentURL);
    } else {
      mDocumentURL.Truncate();
    }
  } else {
    mDocumentURL.Truncate();
  }
  // Notify TSF of the URL and InputScope changes.
  const auto& changedThings = [&]() -> AttrIndices {
    const bool URLChanged = mDocumentURL != oldURL;
    const bool inputScopeChanged = mInputScopes != oldInputScopes;
    if (URLChanged && inputScopeChanged) {
      return URLAndInputScopeChanged;
    }
    if (URLChanged) {
      return OnlyURLChanged;
    }
    return inputScopeChanged ? OnlyURLChanged : NothingChanged;
  }();
  if (changedThings != NothingChanged) {
    NotifyTSFOfInputContextChange(changedThings);
  }
  return NS_OK;
}

void TSFTextStoreBase::NotifyTSFOfInputContextChange(AttrIndices aAttrIndices) {
  MOZ_LOG(
      gIMELog, LogLevel::Debug,
      ("0x%p TSFTextStoreBase::NotifyTSFOfInputContextChange(), mSink=0x%p, "
       "DocumentURL is changed=%s, InputScope is changed=%s",
       this, mSink.get(),
       aAttrIndices.contains(TSFUtils::AttrIndex::DocumentURL) ? "Yes" : "No",
       aAttrIndices.contains(TSFUtils::AttrIndex::InputScope) ? "Yes" : "No"));

  if (!mSink) {
    return;
  }

  AutoTArray<TS_ATTRID, 2> attrIDs;
  if (aAttrIndices.contains(TSFUtils::AttrIndex::DocumentURL)) {
    attrIDs.AppendElement(
        TSFUtils::GetAttrID(TSFUtils::AttrIndex::DocumentURL));
  }
  if (aAttrIndices.contains(TSFUtils::AttrIndex::InputScope)) {
    attrIDs.AppendElement(TSFUtils::GetAttrID(TSFUtils::AttrIndex::InputScope));
  }
  RefPtr<ITextStoreACPSink> sink(mSink);
  sink->OnAttrsChange(0, 0, attrIDs.Length(), attrIDs.Elements());
}

}  // namespace mozilla::widget