forked from EasyIME/libIME
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextService.cpp
1161 lines (1023 loc) · 35.6 KB
/
TextService.cpp
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
//
// Copyright (C) 2013 Hong Jen Yee (PCMan) <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
// Boston, MA 02110-1301, USA.
//
#include "TextService.h"
#include "EditSession.h"
#include "CandidateWindow.h"
#include "LangBarButton.h"
#include "DisplayAttributeInfoEnum.h"
#include "ImeModule.h"
#include <assert.h>
#include <string>
#include <algorithm>
using namespace std;
namespace Ime {
TextService::TextService(ImeModule* module):
module_(module),
threadMgr_(NULL),
clientId_(TF_CLIENTID_NULL),
activateFlags_(0),
isKeyboardOpened_(false),
threadMgrEventSinkCookie_(TF_INVALID_COOKIE),
textEditSinkCookie_(TF_INVALID_COOKIE),
compositionSinkCookie_(TF_INVALID_COOKIE),
keyboardOpenEventSinkCookie_(TF_INVALID_COOKIE),
globalCompartmentEventSinkCookie_(TF_INVALID_COOKIE),
langBarSinkCookie_(TF_INVALID_COOKIE),
activateLanguageProfileNotifySinkCookie_(TF_INVALID_COOKIE),
composition_(NULL),
refCount_(1) {
addCompartmentMonitor(GUID_COMPARTMENT_KEYBOARD_OPENCLOSE, false);
}
TextService::~TextService(void) {
// This should only happen in rare cases
if(!compartmentMonitors_.empty()) {
vector<CompartmentMonitor>::iterator it;
for(it = compartmentMonitors_.begin(); it != compartmentMonitors_.end(); ++it) {
ComQIPtr<ITfSource> source;
if(it->isGlobal)
source = globalCompartment(it->guid);
else
source = threadCompartment(it->guid);
if (source) {
source->UnadviseSink(it->cookie);
}
}
}
if(langBarMgr_) {
langBarMgr_->UnadviseEventSink(langBarSinkCookie_);
}
langBarMgr_ = NULL;
}
// public methods
ImeModule* TextService::imeModule() const {
return module_;
}
ITfThreadMgr* TextService::threadMgr() const {
return threadMgr_;
}
TfClientId TextService::clientId() const {
return clientId_;
}
// language bar
DWORD TextService::langBarStatus() const {
if(langBarMgr_) {
DWORD status;
if(langBarMgr_->GetShowFloatingStatus(&status) == S_OK) {
return status;
}
}
return 0;
}
void TextService::addButton(LangBarButton* button) {
if(button) {
langBarButtons_.emplace_back(button);
if(isActivated()) {
ComPtr<ITfLangBarItemMgr> langBarItemMgr;
if(threadMgr_->QueryInterface(IID_ITfLangBarItemMgr, (void**)&langBarItemMgr) == S_OK) {
langBarItemMgr->AddItem(button);
}
}
}
}
void TextService::removeButton(LangBarButton* button) {
if(button) {
auto it = find(langBarButtons_.begin(), langBarButtons_.end(), button);
if(it != langBarButtons_.end()) {
if(isActivated()) {
ComPtr<ITfLangBarItemMgr> langBarItemMgr;
if(threadMgr_->QueryInterface(IID_ITfLangBarItemMgr, (void**)&langBarItemMgr) == S_OK) {
langBarItemMgr->RemoveItem(button);
}
}
langBarButtons_.erase(it);
}
}
}
// preserved key
void TextService::addPreservedKey(UINT keyCode, UINT modifiers, const GUID& guid) {
PreservedKey preservedKey;
preservedKey.guid = guid;
preservedKey.uVKey = keyCode;
preservedKey.uModifiers = modifiers;
preservedKeys_.push_back(preservedKey);
if(threadMgr_) { // our text service is activated
ITfKeystrokeMgr *keystrokeMgr;
if (threadMgr_->QueryInterface(IID_ITfKeystrokeMgr, (void **)&keystrokeMgr) == S_OK) {
keystrokeMgr->PreserveKey(clientId_, guid, &preservedKey, NULL, 0);
keystrokeMgr->Release();
}
}
}
void TextService::removePreservedKey(const GUID& guid) {
vector<PreservedKey>::iterator it;
for(it = preservedKeys_.begin(); it != preservedKeys_.end(); ++it) {
PreservedKey& preservedKey = *it;
if(::IsEqualIID(preservedKey.guid, guid)) {
if(threadMgr_) { // our text service is activated
ITfKeystrokeMgr *keystrokeMgr;
if (threadMgr_->QueryInterface(IID_ITfKeystrokeMgr, (void **)&keystrokeMgr) == S_OK) {
keystrokeMgr->UnpreserveKey(preservedKey.guid, &preservedKey);
keystrokeMgr->Release();
}
}
preservedKeys_.erase(it);
break;
}
}
}
// text composition
bool TextService::isComposing() {
return (composition_ != NULL);
}
// is keyboard disabled for the context (NULL means current context)
bool TextService::isKeyboardDisabled(ITfContext* context) {
return (contextCompartmentValue(GUID_COMPARTMENT_KEYBOARD_DISABLED, context)
|| contextCompartmentValue(GUID_COMPARTMENT_EMPTYCONTEXT, context));
}
// is keyboard opened for the whole thread
bool TextService::isKeyboardOpened() {
return isKeyboardOpened_;
}
void TextService::setKeyboardOpen(bool open) {
if(open != isKeyboardOpened_) {
setThreadCompartmentValue(GUID_COMPARTMENT_KEYBOARD_OPENCLOSE, (DWORD)open);
}
}
// check if current insertion point is in the range of composition.
// if not in range, insertion is now allowed
bool TextService::isInsertionAllowed(EditSession* session) {
TfEditCookie cookie = session->editCookie();
TF_SELECTION selection;
ULONG selectionNum;
if(isComposing()) {
if(session->context()->GetSelection(cookie, TF_DEFAULT_SELECTION, 1, &selection, &selectionNum) == S_OK) {
ITfRange* compositionRange;
if(composition_->GetRange(&compositionRange) == S_OK) {
bool allowed = false;
// check if current selection is covered by composition range
LONG compareResult1;
LONG compareResult2;
if(selection.range->CompareStart(cookie, compositionRange, TF_ANCHOR_START, &compareResult1) == S_OK
&& selection.range->CompareStart(cookie, compositionRange, TF_ANCHOR_END, &compareResult2) == S_OK) {
if(compareResult1 == -1 && compareResult2 == +1)
allowed = true;
}
compositionRange->Release();
}
if(selection.range)
selection.range->Release();
}
}
return false;
}
void TextService::startComposition(ITfContext* context) {
assert(context);
HRESULT sessionResult;
StartCompositionEditSession* session = new StartCompositionEditSession(this, context);
context->RequestEditSession(clientId_, session, TF_ES_SYNC|TF_ES_READWRITE, &sessionResult);
session->Release();
}
void TextService::endComposition(ITfContext* context) {
assert(context);
HRESULT sessionResult;
EndCompositionEditSession* session = new EndCompositionEditSession(this, context);
context->RequestEditSession(clientId_, session, TF_ES_SYNC|TF_ES_READWRITE, &sessionResult);
session->Release();
}
std::wstring TextService::compositionString(EditSession* session) {
if (composition_) {
ComPtr<ITfRange> compositionRange;
if (composition_->GetRange(&compositionRange) == S_OK) {
TfEditCookie editCookie = session->editCookie();
// FIXME: the TSF API is really stupid here and it provides no way to know the size of the range.
// we cannot even get the actual position of start and end to calculate by ourselves.
// So, just use a huge buffer and assume that it's enough. :-(
// this should be quite enough for most of the IME on the earth as most composition strings
// only contain dozens of characters.
wchar_t buf[4096];
ULONG len = 0;
if (compositionRange->GetText(editCookie, 0, buf, 4096, &len) == S_OK) {
buf[len] = '\0';
return std::wstring(buf);
}
}
}
return std::wstring();
}
void TextService::setCompositionString(EditSession* session, const wchar_t* str, int len) {
ITfContext* context = session->context();
if(context) {
TfEditCookie editCookie = session->editCookie();
TF_SELECTION selection;
ULONG selectionNum;
// get current selection/insertion point
if(context->GetSelection(editCookie, TF_DEFAULT_SELECTION, 1, &selection, &selectionNum) == S_OK) {
ComPtr<ITfRange> compositionRange;
if(composition_->GetRange(&compositionRange) == S_OK) {
bool selPosInComposition = true;
// if current insertion point is not covered by composition, we cannot insert text here.
if(selPosInComposition) {
// replace context of composion area with the new string.
compositionRange->SetText(editCookie, TF_ST_CORRECTION, str, len);
// move the insertion point to end of the composition string
selection.range->Collapse(editCookie, TF_ANCHOR_END);
context->SetSelection(editCookie, 1, &selection);
}
// set display attribute to the composition range
ComPtr<ITfProperty> dispAttrProp;
if(context->GetProperty(GUID_PROP_ATTRIBUTE, &dispAttrProp) == S_OK) {
VARIANT val;
val.vt = VT_I4;
val.lVal = module_->inputAttrib()->atom();
dispAttrProp->SetValue(editCookie, compositionRange, &val);
}
}
selection.range->Release();
}
}
}
// set cursor position in the composition area
// 0 means the start pos of composition string
void TextService::setCompositionCursor(EditSession* session, int pos) {
TF_SELECTION selection;
ULONG selectionNum;
// get current selection
if(session->context()->GetSelection(session->editCookie(), TF_DEFAULT_SELECTION, 1, &selection, &selectionNum) == S_OK) {
// get composition range
ITfRange* compositionRange;
if(composition_->GetRange(&compositionRange) == S_OK) {
// make the start of selectionRange the same as that of compositionRange
selection.range->ShiftStartToRange(session->editCookie(), compositionRange, TF_ANCHOR_START);
selection.range->Collapse(session->editCookie(), TF_ANCHOR_START);
LONG moved;
// move the start anchor to right
selection.range->ShiftStart(session->editCookie(), (LONG)pos, &moved, NULL);
selection.range->Collapse(session->editCookie(), TF_ANCHOR_START);
// set the new selection to the context
session->context()->SetSelection(session->editCookie(), 1, &selection);
compositionRange->Release();
}
selection.range->Release();
}
}
// compartment handling
ComPtr<ITfCompartment> TextService::globalCompartment(const GUID& key) {
if(threadMgr_) {
ComQIPtr<ITfCompartmentMgr> compartmentMgr;
if(threadMgr_->GetGlobalCompartment(&compartmentMgr) == S_OK) {
ComPtr<ITfCompartment> compartment;
compartmentMgr->GetCompartment(key, &compartment);
return compartment;
}
}
return NULL;
}
ComPtr<ITfCompartment> TextService::threadCompartment(const GUID& key) {
if(threadMgr_) {
ComQIPtr<ITfCompartmentMgr> compartmentMgr = threadMgr_;
if(compartmentMgr) {
ComPtr<ITfCompartment> compartment;
compartmentMgr->GetCompartment(key, &compartment);
return compartment;
}
}
return NULL;
}
ComPtr<ITfCompartment> TextService::contextCompartment(const GUID& key, ITfContext* context) {
ITfContext* curContext = NULL;
if(!context) {
curContext = currentContext();
context = curContext;
}
if(context) {
ComQIPtr<ITfCompartmentMgr> compartmentMgr = context;
if(compartmentMgr) {
ComPtr<ITfCompartment> compartment;
compartmentMgr->GetCompartment(key, &compartment);
return compartment;
}
}
if(curContext)
curContext->Release();
return NULL;
}
DWORD TextService::globalCompartmentValue(const GUID& key) {
ComPtr<ITfCompartment> compartment = globalCompartment(key);
if(compartment) {
VARIANT var;
if(compartment->GetValue(&var) == S_OK && var.vt == VT_I4) {
return (DWORD)var.lVal;
}
}
return 0;
}
DWORD TextService::threadCompartmentValue(const GUID& key) {
ComPtr<ITfCompartment> compartment = threadCompartment(key);
if(compartment) {
VARIANT var;
::VariantInit(&var);
HRESULT r = compartment->GetValue(&var);
if(r == S_OK) {
if(var.vt == VT_I4)
return (DWORD)var.lVal;
}
}
return 0;
}
DWORD TextService::contextCompartmentValue(const GUID& key, ITfContext* context) {
ComPtr<ITfCompartment> compartment = contextCompartment(key, context);
if(compartment) {
VARIANT var;
if(compartment->GetValue(&var) == S_OK && var.vt == VT_I4) {
return (DWORD)var.lVal;
}
}
return 0;
}
void TextService::setGlobalCompartmentValue(const GUID& key, DWORD value) {
if(threadMgr_) {
ComPtr<ITfCompartment> compartment = globalCompartment(key);
if(compartment) {
VARIANT var;
::VariantInit(&var);
var.vt = VT_I4;
var.lVal = value;
compartment->SetValue(clientId_, &var);
}
}
else {
// if we don't have a thread manager (this is possible when we try to set
// a global compartment value while the text service is not activated)
ComPtr<ITfThreadMgr> threadMgr;
if(::CoCreateInstance(CLSID_TF_ThreadMgr, NULL, CLSCTX_INPROC_SERVER, IID_ITfThreadMgr, (void**)&threadMgr) == S_OK) {
if(threadMgr) {
ComPtr<ITfCompartmentMgr> compartmentMgr;
if(threadMgr->GetGlobalCompartment(&compartmentMgr) == S_OK) {
ComPtr<ITfCompartment> compartment;
if(compartmentMgr->GetCompartment(key, &compartment) == S_OK && compartment) {
TfClientId id;
if(threadMgr->Activate(&id) == S_OK) {
VARIANT var;
::VariantInit(&var);
var.vt = VT_I4;
var.lVal = value;
compartment->SetValue(id, &var);
threadMgr->Deactivate();
}
}
}
}
}
}
}
void TextService::setThreadCompartmentValue(const GUID& key, DWORD value) {
ComPtr<ITfCompartment> compartment = threadCompartment(key);
if(compartment) {
VARIANT var;
::VariantInit(&var);
var.vt = VT_I4;
var.lVal = value;
compartment->SetValue(clientId_, &var);
}
}
void TextService::setContextCompartmentValue(const GUID& key, DWORD value, ITfContext* context) {
ComPtr<ITfCompartment> compartment = contextCompartment(key, context);
if(compartment) {
VARIANT var;
::VariantInit(&var);
var.vt = VT_I4;
var.lVal = value;
compartment->SetValue(clientId_, &var);
}
}
void TextService::addCompartmentMonitor(const GUID key, bool isGlobal) {
CompartmentMonitor monitor;
monitor.guid = key;
monitor.cookie = 0;
monitor.isGlobal = isGlobal;
// if the text service is activated
if(threadMgr_) {
ComQIPtr<ITfSource> source;
if(isGlobal)
source = globalCompartment(key);
else
source = threadCompartment(key);
if(source) {
source->AdviseSink(IID_ITfCompartmentEventSink, (ITfCompartmentEventSink*)this, &monitor.cookie);
}
}
compartmentMonitors_.push_back(monitor);
}
void TextService::removeCompartmentMonitor(const GUID key) {
vector<CompartmentMonitor>::iterator it;
it = find(compartmentMonitors_.begin(), compartmentMonitors_.end(), key);
if(it != compartmentMonitors_.end()) {
if(threadMgr_) {
ComQIPtr<ITfSource> source;
if(it->isGlobal)
source = globalCompartment(key);
else
source = threadCompartment(key);
source->UnadviseSink(it->cookie);
}
compartmentMonitors_.erase(it);
}
}
// virtual
void TextService::onActivate() {
}
// virtual
void TextService::onDeactivate() {
}
// virtual
bool TextService::filterKeyDown(KeyEvent& keyEvent) {
return false;
}
// virtual
bool TextService::onKeyDown(KeyEvent& keyEvent, EditSession* session) {
return false;
}
// virtual
bool TextService::filterKeyUp(KeyEvent& keyEvent) {
return false;
}
// virtual
bool TextService::onKeyUp(KeyEvent& keyEvent, EditSession* session) {
return false;
}
// virtual
bool TextService::onPreservedKey(const GUID& guid) {
return false;
}
// virtual
void TextService::onSetFocus() {
}
// virtual
void TextService::onKillFocus() {
}
bool TextService::onCommand(UINT id, CommandType type) {
return false;
}
// virtual
void TextService::onCompartmentChanged(const GUID& key) {
// keyboard status changed, this is threadMgr specific
// See explanations on TSF aware blog:
// http://blogs.msdn.com/b/tsfaware/archive/2007/05/30/what-is-a-keyboard.aspx
if(::IsEqualGUID(key, GUID_COMPARTMENT_KEYBOARD_OPENCLOSE)) {
isKeyboardOpened_ = threadCompartmentValue(key) ? true : false;
onKeyboardStatusChanged(isKeyboardOpened_);
}
}
// virtual
void TextService::onLangBarStatusChanged(int newStatus) {
}
// called when the keyboard is opened or closed
// virtual
void TextService::onKeyboardStatusChanged(bool opened) {
}
// called just before current composition is terminated for doing cleanup.
// if forced is true, the composition is terminated by others, such as
// the input focus is grabbed by another application.
// if forced is false, the composition is terminated gracefully by endComposition().
// virtual
void TextService::onCompositionTerminated(bool forced) {
}
// called when a language profile is activated (only useful for text services that supports multiple language profiles)
void TextService::onLangProfileActivated(REFGUID guidProfile) {
}
// called when a language profile is deactivated
void TextService::onLangProfileDeactivated(REFGUID guidProfile) {
}
// COM stuff
// IUnknown
STDMETHODIMP TextService::QueryInterface(REFIID riid, void **ppvObj) {
if (ppvObj == NULL)
return E_INVALIDARG;
if(IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_ITfTextInputProcessor))
*ppvObj = (ITfTextInputProcessor*)this;
else if(IsEqualIID(riid, IID_ITfTextInputProcessorEx))
*ppvObj = (ITfTextInputProcessorEx*)this;
//else if(IsEqualIID(riid, IID_ITfThreadMgrEventSink))
// *ppvObj = (ITfThreadMgrEventSink*)this;
else if(IsEqualIID(riid, IID_ITfTextEditSink))
*ppvObj = (ITfTextEditSink*)this;
else if(IsEqualIID(riid, IID_ITfKeyEventSink))
*ppvObj = (ITfKeyEventSink*)this;
else if(IsEqualIID(riid, IID_ITfCompositionSink))
*ppvObj = (ITfCompositionSink*)this;
else if(IsEqualIID(riid, IID_ITfCompartmentEventSink))
*ppvObj = (ITfCompartmentEventSink*)this;
else if(IsEqualIID(riid, IID_ITfLangBarEventSink))
*ppvObj = (ITfLangBarEventSink*)this;
else if(IsEqualIID(riid, IID_ITfActiveLanguageProfileNotifySink))
*ppvObj = (ITfActiveLanguageProfileNotifySink*)this;
else
*ppvObj = NULL;
if(*ppvObj) {
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
// IUnknown implementation
STDMETHODIMP_(ULONG) TextService::AddRef(void) {
return ++refCount_;
}
STDMETHODIMP_(ULONG) TextService::Release(void) {
assert(refCount_ > 0);
const ULONG newCount = --refCount_;
if(0 == refCount_) {
// ImeModule needs to do some clean up before deleting the TextService object.
module_->removeTextService(this);
delete this;
}
return newCount;
}
// ITfTextInputProcessor
STDMETHODIMP TextService::Activate(ITfThreadMgr *pThreadMgr, TfClientId tfClientId) {
// store tsf manager & client id
threadMgr_ = pThreadMgr;
clientId_ = tfClientId;
activateFlags_ = 0;
ComQIPtr<ITfThreadMgrEx> threadMgrEx = threadMgr_;
if(threadMgrEx) {
threadMgrEx->GetActiveFlags(&activateFlags_);
}
// advice event sinks (set up event listeners)
// ITfThreadMgrEventSink, ITfActiveLanguageProfileNotifySink
ComQIPtr<ITfSource> source = threadMgr_;
if(source) {
source->AdviseSink(IID_ITfThreadMgrEventSink, (ITfThreadMgrEventSink *)this, &threadMgrEventSinkCookie_);
source->AdviseSink(IID_ITfActiveLanguageProfileNotifySink, (ITfActiveLanguageProfileNotifySink *)this, &activateLanguageProfileNotifySinkCookie_);
}
// ITfTextEditSink,
// ITfKeyEventSink
ComQIPtr<ITfKeystrokeMgr> keystrokeMgr = threadMgr_;
if(keystrokeMgr)
keystrokeMgr->AdviseKeyEventSink(clientId_, (ITfKeyEventSink*)this, TRUE);
// register preserved keys
if(!preservedKeys_.empty()) {
vector<PreservedKey>::iterator it;
for(it = preservedKeys_.begin(); it != preservedKeys_.end(); ++it) {
PreservedKey& preservedKey = *it;
keystrokeMgr->PreserveKey(clientId_, preservedKey.guid, &preservedKey, NULL, 0);
}
}
// ITfCompositionSink
// ITfCompartmentEventSink
// get current keyboard state
if(!compartmentMonitors_.empty()) {
vector<CompartmentMonitor>::iterator it;
for(it = compartmentMonitors_.begin(); it != compartmentMonitors_.end(); ++it) {
ComQIPtr<ITfSource> compartmentSource;
if(it->isGlobal) // global compartment
compartmentSource = globalCompartment(it->guid);
else // thread specific compartment
compartmentSource = threadCompartment(it->guid);
compartmentSource->AdviseSink(IID_ITfCompartmentEventSink, (ITfCompartmentEventSink*)this, &it->cookie);
}
}
isKeyboardOpened_ = threadCompartmentValue(GUID_COMPARTMENT_KEYBOARD_OPENCLOSE) != 0;
// FIXME: under Windows 7, it seems that the keyboard is closed every time
// our text service is activated. The value in the compartment is always empty. :-(
// So, we open the keyboard manually here, but I'm not sure if this is the correct behavior.
if(!isKeyboardOpened_)
setKeyboardOpen(true);
// initialize language bar
::CoCreateInstance(CLSID_TF_LangBarMgr, NULL, CLSCTX_INPROC_SERVER,
IID_ITfLangBarMgr, (void**)&langBarMgr_);
if(langBarMgr_) {
langBarMgr_->AdviseEventSink(this, NULL, 0, &langBarSinkCookie_);
}
// Note: language bar has no effects in Win 8 immersive mode
if(!langBarButtons_.empty()) {
ComPtr<ITfLangBarItemMgr> langBarItemMgr;
if(threadMgr_->QueryInterface(IID_ITfLangBarItemMgr, (void**)&langBarItemMgr) == S_OK) {
for(auto& button: langBarButtons_) {
langBarItemMgr->AddItem(button);
}
}
}
onActivate();
//::MessageBox(0, L"onActivate", 0, 0);
return S_OK;
}
STDMETHODIMP TextService::Deactivate() {
//::MessageBox(0, L"Deactivate", 0, 0);
// terminate composition properly
if(isComposing()) {
ITfContext* context = currentContext();
if(context) {
endComposition(context);
context->Release();
}
}
onDeactivate();
// uninitialize language bar
if(!langBarButtons_.empty()) {
ComPtr<ITfLangBarItemMgr> langBarItemMgr;
if(threadMgr_->QueryInterface(IID_ITfLangBarItemMgr, (void**)&langBarItemMgr) == S_OK) {
for(auto& button: langBarButtons_) {
langBarItemMgr->RemoveItem(button);
}
}
}
if(langBarMgr_) {
langBarMgr_->UnadviseEventSink(langBarSinkCookie_);
langBarSinkCookie_ = TF_INVALID_COOKIE;
langBarMgr_ = NULL;
}
// unadvice event sinks
// ITfThreadMgrEventSink
ComQIPtr<ITfSource> source = threadMgr_;
if(source) {
source->UnadviseSink(threadMgrEventSinkCookie_);
source->UnadviseSink(activateLanguageProfileNotifySinkCookie_);
threadMgrEventSinkCookie_ = TF_INVALID_COOKIE;
activateLanguageProfileNotifySinkCookie_ = TF_INVALID_COOKIE;
}
// ITfTextEditSink,
// ITfKeyEventSink
ComQIPtr<ITfKeystrokeMgr> keystrokeMgr = threadMgr_;
if(keystrokeMgr) {
keystrokeMgr->UnadviseKeyEventSink(clientId_);
// unregister preserved keys
if(!preservedKeys_.empty()) {
vector<PreservedKey>::iterator it;
for(it = preservedKeys_.begin(); it != preservedKeys_.end(); ++it) {
PreservedKey& preservedKey = *it;
keystrokeMgr->UnpreserveKey(preservedKey.guid, &preservedKey);
}
}
}
// ITfCompositionSink
// ITfCompartmentEventSink
// thread specific compartment
ComPtr<ITfCompartment> compartment = threadCompartment(GUID_COMPARTMENT_KEYBOARD_OPENCLOSE);
if(compartment) {
ComQIPtr<ITfSource> compartmentSource = compartment;
if(compartmentSource)
compartmentSource->UnadviseSink(keyboardOpenEventSinkCookie_);
keyboardOpenEventSinkCookie_ = TF_INVALID_COOKIE;
}
/*
// global compartment
compartment = globalCompartment(XXX_GUID);
if(compartment) {
ComQIPtr<ITfSource> compartmentSource = compartment;
if(compartmentSource)
compartmentSource->UnadviseSink(globalCompartmentEventSinkCookie_);
globalCompartmentEventSinkCookie_ = TF_INVALID_COOKIE;
}
*/
threadMgr_ = NULL;
clientId_ = TF_CLIENTID_NULL;
activateFlags_ = 0;
return S_OK;
}
// ITfTextInputProcessorEx
STDMETHODIMP TextService::ActivateEx(ITfThreadMgr *ptim, TfClientId tid, DWORD dwFlags) {
Activate(ptim, tid);
return S_OK;
}
// ITfThreadMgrEventSink
STDMETHODIMP TextService::OnInitDocumentMgr(ITfDocumentMgr *pDocMgr) {
return S_OK;
}
STDMETHODIMP TextService::OnUninitDocumentMgr(ITfDocumentMgr *pDocMgr) {
return S_OK;
}
STDMETHODIMP TextService::OnSetFocus(ITfDocumentMgr *pDocMgrFocus, ITfDocumentMgr *pDocMgrPrevFocus) {
return S_OK;
}
STDMETHODIMP TextService::OnPushContext(ITfContext *pContext) {
return S_OK;
}
STDMETHODIMP TextService::OnPopContext(ITfContext *pContext) {
return S_OK;
}
// ITfTextEditSink
STDMETHODIMP TextService::OnEndEdit(ITfContext *pContext, TfEditCookie ecReadOnly, ITfEditRecord *pEditRecord) {
// This method is called by the TSF whenever an edit operation ends.
// It's possible for a document to have multiple composition strings at the
// same time and it's possible for other text services to edit the same
// document. Though such a complicated senario rarely exist, it indeed happen.
// NOTE: I don't really know why this is needed and tests yielded no obvious effect
// of this piece of code, but from MS TSF samples, this is needed.
BOOL selChanged;
if(pEditRecord->GetSelectionStatus(&selChanged) == S_OK) {
if(selChanged && isComposing()) {
// we need to check if current selection is in our composition string.
// if after others' editing the selection (insertion point) has been changed and
// fell outside our composition area, terminate the composition.
TF_SELECTION selection;
ULONG selectionNum;
if(pContext->GetSelection(ecReadOnly, TF_DEFAULT_SELECTION, 1, &selection, &selectionNum) == S_OK) {
ComPtr<ITfRange> compRange;
if(composition_->GetRange(&compRange) == S_OK) {
// check if two ranges overlaps
// check if current selection is covered by composition range
LONG compareResult1;
LONG compareResult2;
if(compRange->CompareStart(ecReadOnly, selection.range, TF_ANCHOR_START, &compareResult1) == S_OK
&& compRange->CompareEnd(ecReadOnly, selection.range, TF_ANCHOR_END, &compareResult2) == S_OK) {
if(compareResult1 == +1 || compareResult2 == -1) {
// the selection is not entirely in composion
// end compositon here
endComposition(pContext);
}
}
}
selection.range->Release();
}
}
}
return S_OK;
}
// ITfKeyEventSink
STDMETHODIMP TextService::OnSetFocus(BOOL fForeground) {
if(fForeground)
onSetFocus();
else
onKillFocus();
return S_OK;
}
STDMETHODIMP TextService::OnTestKeyDown(ITfContext *pContext, WPARAM wParam, LPARAM lParam, BOOL *pfEaten) {
if(isKeyboardDisabled(pContext) || !isKeyboardOpened())
*pfEaten = FALSE;
else {
KeyEvent keyEvent(WM_KEYDOWN, wParam, lParam);
*pfEaten = (BOOL)filterKeyDown(keyEvent);
}
return S_OK;
}
STDMETHODIMP TextService::OnKeyDown(ITfContext *pContext, WPARAM wParam, LPARAM lParam, BOOL *pfEaten) {
// Some applications do not trigger OnTestKeyDown()
// So we need to test it again here! Windows TSF sucks!
if(isKeyboardDisabled(pContext) || !isKeyboardOpened())
*pfEaten = FALSE;
else {
KeyEvent keyEvent(WM_KEYDOWN, wParam, lParam);
*pfEaten = (BOOL)filterKeyDown(keyEvent);
if(*pfEaten) { // we want to eat the key
HRESULT sessionResult;
// ask TSF for an edit session. If editing is approved by TSF,
// KeyEditSession::DoEditSession will be called, which in turns
// call back to TextService::doKeyEditSession().
// So the real key handling is relayed to TextService::doKeyEditSession().
KeyEditSession* session = new KeyEditSession(this, pContext, keyEvent);
// We use TF_ES_SYNC here, so the request becomes synchronus and blocking.
// KeyEditSession::DoEditSession() and TextService::doKeyEditSession() will be
// called before RequestEditSession() returns.
pContext->RequestEditSession(clientId_, session, TF_ES_SYNC|TF_ES_READWRITE, &sessionResult);
*pfEaten = session->result_; // tell TSF if we handled the key
session->Release();
}
}
return S_OK;
}
STDMETHODIMP TextService::OnTestKeyUp(ITfContext *pContext, WPARAM wParam, LPARAM lParam, BOOL *pfEaten) {
if(isKeyboardDisabled(pContext) || !isKeyboardOpened())
*pfEaten = FALSE;
else {
KeyEvent keyEvent(WM_KEYDOWN, wParam, lParam);
*pfEaten = (BOOL)filterKeyUp(keyEvent);
}
return S_OK;
}
STDMETHODIMP TextService::OnKeyUp(ITfContext *pContext, WPARAM wParam, LPARAM lParam, BOOL *pfEaten) {
// Some applications do not trigger OnTestKeyDown()
// So we need to test it again here! Windows TSF sucks!
if(isKeyboardDisabled(pContext) || !isKeyboardOpened())
*pfEaten = FALSE;
else {
KeyEvent keyEvent(WM_KEYUP, wParam, lParam);
*pfEaten = (BOOL)filterKeyUp(keyEvent);
if(*pfEaten) {
HRESULT sessionResult;
KeyEditSession* session = new KeyEditSession(this, pContext, keyEvent);
pContext->RequestEditSession(clientId_, session, TF_ES_SYNC|TF_ES_READWRITE, &sessionResult);
*pfEaten = session->result_; // tell TSF if we handled the key
session->Release();
}
}
return S_OK;
}
STDMETHODIMP TextService::OnPreservedKey(ITfContext *pContext, REFGUID rguid, BOOL *pfEaten) {
*pfEaten = (BOOL)onPreservedKey(rguid);
return S_OK;
}
// ITfCompositionSink
STDMETHODIMP TextService::OnCompositionTerminated(TfEditCookie ecWrite, ITfComposition *pComposition) {
// This is called by TSF when our composition is terminated by others.
// For example, when the user click on another text editor and the input focus is
// grabbed by others, we're ``forced'' to terminate current composition.
// If we end the composition by calling ITfComposition::EndComposition() ourselves,
// this event is not triggered.
onCompositionTerminated(true);
if(composition_) {
composition_->Release();
composition_ = NULL;
}
return S_OK;
}
// ITfCompartmentEventSink
STDMETHODIMP TextService::OnChange(REFGUID rguid) {
// The TSF ITfCompartment is kind of key-value storage
// It uses GUIDs as keys and stores integer and string values.
// Global compartment is a storage for cross-process key-value pairs.
// However, it only handles integers. String values cannot be stored.
// The thread manager specific compartment, however, handles strings.
// Every value stored in the storage has an key, which is a GUID.
// global keyboard states and some other values are in the compartments
// So we need to monitor for their changes and do some handling.
// For more detailed introduction, see TSF aware blog:
// http://blogs.msdn.com/b/tsfaware/archive/2007/05/30/what-is-a-keyboard.aspx
onCompartmentChanged(rguid);
return S_OK;
}
// ITfLangBarEventSink
STDMETHODIMP TextService::OnSetFocus(DWORD dwThreadId) {
return E_NOTIMPL;
}
STDMETHODIMP TextService::OnThreadTerminate(DWORD dwThreadId) {
return E_NOTIMPL;
}
STDMETHODIMP TextService::OnThreadItemChange(DWORD dwThreadId) {
return E_NOTIMPL;
}
STDMETHODIMP TextService::OnModalInput(DWORD dwThreadId, UINT uMsg, WPARAM wParam, LPARAM lParam) {
return E_NOTIMPL;
}
STDMETHODIMP TextService::ShowFloating(DWORD dwFlags) {
onLangBarStatusChanged(dwFlags);
return S_OK;
}
STDMETHODIMP TextService::GetItemFloatingRect(DWORD dwThreadId, REFGUID rguid, RECT *prc) {
return E_NOTIMPL;
}
// ITfActiveLanguageProfileNotifySink
STDMETHODIMP TextService::OnActivated(REFCLSID clsid, REFGUID guidProfile, BOOL fActivated) {