forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
TextInputHandler.mm
1821 lines (1542 loc) · 51.4 KB
/
TextInputHandler.mm
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=80: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Mozilla Japan.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Masayuki Nakano <masayuki@d-toybox.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "TextInputHandler.h"
#include "nsChildView.h"
#include "nsObjCExceptions.h"
#include "nsBidiUtils.h"
#ifdef MOZ_LOGGING
#define FORCE_PR_LOG
#endif
#include "prlog.h"
using namespace mozilla::widget;
#undef DEBUG_IME_HANDLER
#undef DEBUG_TEXT_INPUT_HANDLER
//#define DEBUG_IME_HANDLER 1
//#define DEBUG_TEXT_INPUT_HANDLER 1
// TODO: static methods should be moved to nsCocoaUtils
static void
GetStringForNSString(const NSString *aSrc, nsAString& aDist)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (!aSrc) {
aDist.Truncate();
return;
}
aDist.SetLength([aSrc length]);
[aSrc getCharacters: aDist.BeginWriting()];
NS_OBJC_END_TRY_ABORT_BLOCK;
}
static NSString* ToNSString(const nsAString& aString)
{
return [NSString stringWithCharacters:aString.BeginReading()
length:aString.Length()];
}
static inline void
GeckoRectToNSRect(const nsIntRect& inGeckoRect, NSRect& outCocoaRect)
{
outCocoaRect.origin.x = inGeckoRect.x;
outCocoaRect.origin.y = inGeckoRect.y;
outCocoaRect.size.width = inGeckoRect.width;
outCocoaRect.size.height = inGeckoRect.height;
}
#ifdef DEBUG_IME_HANDLER
static const char*
TrueOrFalse(PRBool aBool)
{
return aBool ? "TRUE" : "FALSE";
}
static void
DebugPrintPointer(IMEInputHandler* aHandler)
{
static IMEInputHandler* sLastHandler = nsnull;
if (aHandler == sLastHandler)
return;
sLastHandler = aHandler;
NSLog(@"%8p ************************************************", aHandler);
}
static const char*
GetWindowLevelName(NSInteger aWindowLevel)
{
switch (aWindowLevel) {
case kCGBaseWindowLevelKey:
return "kCGBaseWindowLevelKey (NSNormalWindowLevel)";
case kCGMinimumWindowLevelKey:
return "kCGMinimumWindowLevelKey";
case kCGDesktopWindowLevelKey:
return "kCGDesktopWindowLevelKey";
case kCGBackstopMenuLevelKey:
return "kCGBackstopMenuLevelKey";
case kCGNormalWindowLevelKey:
return "kCGNormalWindowLevelKey";
case kCGFloatingWindowLevelKey:
return "kCGFloatingWindowLevelKey (NSFloatingWindowLevel)";
case kCGTornOffMenuWindowLevelKey:
return "kCGTornOffMenuWindowLevelKey (NSSubmenuWindowLevel, NSTornOffMenuWindowLevel)";
case kCGDockWindowLevelKey:
return "kCGDockWindowLevelKey (NSDockWindowLevel)";
case kCGMainMenuWindowLevelKey:
return "kCGMainMenuWindowLevelKey (NSMainMenuWindowLevel)";
case kCGStatusWindowLevelKey:
return "kCGStatusWindowLevelKey (NSStatusWindowLevel)";
case kCGModalPanelWindowLevelKey:
return "kCGModalPanelWindowLevelKey (NSModalPanelWindowLevel)";
case kCGPopUpMenuWindowLevelKey:
return "kCGPopUpMenuWindowLevelKey (NSPopUpMenuWindowLevel)";
case kCGDraggingWindowLevelKey:
return "kCGDraggingWindowLevelKey";
case kCGScreenSaverWindowLevelKey:
return "kCGScreenSaverWindowLevelKey (NSScreenSaverWindowLevel)";
case kCGMaximumWindowLevelKey:
return "kCGMaximumWindowLevelKey";
case kCGOverlayWindowLevelKey:
return "kCGOverlayWindowLevelKey";
case kCGHelpWindowLevelKey:
return "kCGHelpWindowLevelKey";
case kCGUtilityWindowLevelKey:
return "kCGUtilityWindowLevelKey";
case kCGDesktopIconWindowLevelKey:
return "kCGDesktopIconWindowLevelKey";
case kCGCursorWindowLevelKey:
return "kCGCursorWindowLevelKey";
case kCGNumberOfWindowLevelKeys:
return "kCGNumberOfWindowLevelKeys";
default:
return "unknown window level";
}
}
#endif // DEBUG_IME_HANDLER
static PRUint32 gHandlerInstanceCount = 0;
static TISInputSourceWrapper gCurrentKeyboardLayout;
static void
InitCurrentKeyboardLayout()
{
if (gHandlerInstanceCount > 0 &&
!gCurrentKeyboardLayout.IsInitializedByCurrentKeyboardLayout()) {
gCurrentKeyboardLayout.InitByCurrentKeyboardLayout();
}
}
static void
FinalizeCurrentKeyboardLayout()
{
gCurrentKeyboardLayout.Clear();
}
#pragma mark -
/******************************************************************************
*
* TISInputSourceWrapper implementation
*
******************************************************************************/
// static
TISInputSourceWrapper&
TISInputSourceWrapper::CurrentKeyboardLayout()
{
InitCurrentKeyboardLayout();
return gCurrentKeyboardLayout;
}
// static
PRBool
TISInputSourceWrapper::UCKeyTranslateToString(
const UCKeyboardLayout* aHandle,
UInt32 aKeyCode, UInt32 aModifiers,
UInt32 aKbType, nsAString &aStr)
{
#ifdef DEBUG_TEXT_INPUT_HANDLER
NSLog(@"**** TISInputSourceWrapper::UCKeyTranslateToString: aHandle: %p, aKeyCode: %X, aModifiers: %X, aKbType: %X",
aHandle, aKeyCode, aModifiers, aKbType);
PRBool isShift = aModifiers & shiftKey;
PRBool isCtrl = aModifiers & controlKey;
PRBool isOpt = aModifiers & optionKey;
PRBool isCmd = aModifiers & cmdKey;
PRBool isCL = aModifiers & alphaLock;
PRBool isNL = aModifiers & kEventKeyModifierNumLockMask;
NSLog(@" Shift: %s, Ctrl: %s, Opt: %s, Cmd: %s, CapsLock: %s, NumLock: %s",
isShift ? "ON" : "off", isCtrl ? "ON" : "off", isOpt ? "ON" : "off",
isCmd ? "ON" : "off", isCL ? "ON" : "off", isNL ? "ON" : "off");
#endif
NS_PRECONDITION(aStr.IsEmpty(), "aStr isn't empty");
UInt32 deadKeyState = 0;
UniCharCount len;
UniChar chars[5];
OSStatus err = ::UCKeyTranslate(aHandle, aKeyCode,
kUCKeyActionDown, aModifiers >> 8,
aKbType, kUCKeyTranslateNoDeadKeysMask,
&deadKeyState, 5, &len, chars);
if (err != noErr) {
return PR_FALSE;
}
if (len == 0) {
return PR_TRUE;
}
if (!EnsureStringLength(aStr, len)) {
return PR_FALSE;
}
NS_ASSERTION(sizeof(PRUnichar) == sizeof(UniChar),
"size of PRUnichar and size of UniChar are different");
memcpy(aStr.BeginWriting(), chars, len * sizeof(PRUnichar));
#ifdef DEBUG_TEXT_INPUT_HANDLER
for (PRUint32 i = 0; i < PRUint32(len); i++) {
NSLog(@" result: %X(%C)", chars[i], chars[i] > ' ' ? chars[i] : ' ');
}
#endif
return PR_TRUE;
}
void
TISInputSourceWrapper::InitByInputSourceID(const char* aID)
{
Clear();
if (!aID)
return;
CFStringRef idstr = ::CFStringCreateWithCString(kCFAllocatorDefault, aID,
kCFStringEncodingASCII);
InitByInputSourceID(idstr);
::CFRelease(idstr);
}
void
TISInputSourceWrapper::InitByInputSourceID(const nsAFlatString &aID)
{
Clear();
if (aID.IsEmpty())
return;
CFStringRef idstr = ::CFStringCreateWithCharacters(kCFAllocatorDefault,
aID.get(), aID.Length());
InitByInputSourceID(idstr);
::CFRelease(idstr);
}
void
TISInputSourceWrapper::InitByInputSourceID(const CFStringRef aID)
{
Clear();
if (!aID)
return;
const void* keys[] = { kTISPropertyInputSourceID };
const void* values[] = { aID };
CFDictionaryRef filter =
::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL);
NS_ASSERTION(filter, "failed to create the filter");
mInputSourceList = ::TISCreateInputSourceList(filter, true);
::CFRelease(filter);
if (::CFArrayGetCount(mInputSourceList) > 0) {
mInputSource = static_cast<TISInputSourceRef>(
const_cast<void *>(::CFArrayGetValueAtIndex(mInputSourceList, 0)));
}
}
void
TISInputSourceWrapper::InitByLayoutID(SInt32 aLayoutID)
{
Clear();
// XXX On TIS, the LayoutID is abolished completely. Therefore, the numbers
// have no meaning. If you need to add other keyboard layouts for
// nsIWidget::SynthesizeNativeKeyEvent, you don't need to check the old
// resource, you can use any numbers.
switch (aLayoutID) {
case 0:
InitByInputSourceID("com.apple.keylayout.US");
break;
case -18944:
InitByInputSourceID("com.apple.keylayout.Greek");
break;
case 3:
InitByInputSourceID("com.apple.keylayout.German");
break;
case 224:
InitByInputSourceID("com.apple.keylayout.Swedish-Pro");
break;
}
}
void
TISInputSourceWrapper::InitByCurrentInputSource()
{
Clear();
mInputSource = ::TISCopyCurrentKeyboardInputSource();
}
void
TISInputSourceWrapper::InitByCurrentKeyboardLayout()
{
Clear();
mInputSource = ::TISCopyCurrentKeyboardLayoutInputSource();
}
void
TISInputSourceWrapper::InitByCurrentASCIICapableInputSource()
{
Clear();
mInputSource = ::TISCopyCurrentASCIICapableKeyboardInputSource();
}
void
TISInputSourceWrapper::InitByCurrentASCIICapableKeyboardLayout()
{
Clear();
mInputSource = ::TISCopyCurrentASCIICapableKeyboardLayoutInputSource();
}
void
TISInputSourceWrapper::InitByTISInputSourceRef(TISInputSourceRef aInputSource)
{
Clear();
mInputSource = aInputSource;
}
void
TISInputSourceWrapper::InitByLanguage(CFStringRef aLanguage)
{
Clear();
mInputSource = ::TISCopyInputSourceForLanguage(aLanguage);
}
const UCKeyboardLayout*
TISInputSourceWrapper::GetUCKeyboardLayout()
{
NS_ENSURE_TRUE(mInputSource, nsnull);
if (mUCKeyboardLayout) {
return mUCKeyboardLayout;
}
CFDataRef uchr = static_cast<CFDataRef>(
::TISGetInputSourceProperty(mInputSource,
kTISPropertyUnicodeKeyLayoutData));
// We should be always able to get the layout here.
NS_ENSURE_TRUE(uchr, nsnull);
mUCKeyboardLayout =
reinterpret_cast<const UCKeyboardLayout*>(CFDataGetBytePtr(uchr));
return mUCKeyboardLayout;
}
PRBool
TISInputSourceWrapper::GetBoolProperty(const CFStringRef aKey)
{
CFBooleanRef ret = static_cast<CFBooleanRef>(
::TISGetInputSourceProperty(mInputSource, aKey));
return ::CFBooleanGetValue(ret);
}
PRBool
TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey,
CFStringRef &aStr)
{
aStr = static_cast<CFStringRef>(
::TISGetInputSourceProperty(mInputSource, aKey));
return aStr != nsnull;
}
PRBool
TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey,
nsAString &aStr)
{
CFStringRef str;
GetStringProperty(aKey, str);
GetStringForNSString((const NSString*)str, aStr);
return !aStr.IsEmpty();
}
PRBool
TISInputSourceWrapper::IsOpenedIMEMode()
{
NS_ENSURE_TRUE(mInputSource, PR_FALSE);
if (!IsIMEMode())
return PR_FALSE;
return !IsASCIICapable();
}
PRBool
TISInputSourceWrapper::IsIMEMode()
{
NS_ENSURE_TRUE(mInputSource, PR_FALSE);
CFStringRef str;
GetInputSourceType(str);
NS_ENSURE_TRUE(str, PR_FALSE);
return ::CFStringCompare(kTISTypeKeyboardInputMode,
str, 0) == kCFCompareEqualTo;
}
PRBool
TISInputSourceWrapper::GetLanguageList(CFArrayRef &aLanguageList)
{
NS_ENSURE_TRUE(mInputSource, PR_FALSE);
aLanguageList = static_cast<CFArrayRef>(
::TISGetInputSourceProperty(mInputSource,
kTISPropertyInputSourceLanguages));
return aLanguageList != nsnull;
}
PRBool
TISInputSourceWrapper::GetPrimaryLanguage(CFStringRef &aPrimaryLanguage)
{
NS_ENSURE_TRUE(mInputSource, PR_FALSE);
CFArrayRef langList;
NS_ENSURE_TRUE(GetLanguageList(langList), PR_FALSE);
if (::CFArrayGetCount(langList) == 0)
return PR_FALSE;
aPrimaryLanguage =
static_cast<CFStringRef>(::CFArrayGetValueAtIndex(langList, 0));
return aPrimaryLanguage != nsnull;
}
PRBool
TISInputSourceWrapper::GetPrimaryLanguage(nsAString &aPrimaryLanguage)
{
NS_ENSURE_TRUE(mInputSource, PR_FALSE);
CFStringRef primaryLanguage;
NS_ENSURE_TRUE(GetPrimaryLanguage(primaryLanguage), PR_FALSE);
GetStringForNSString((const NSString*)primaryLanguage, aPrimaryLanguage);
return !aPrimaryLanguage.IsEmpty();
}
PRBool
TISInputSourceWrapper::IsForRTLLanguage()
{
if (mIsRTL < 0) {
// Get the input character of the 'A' key of ANSI keyboard layout.
nsAutoString str;
PRBool ret = TranslateToString(kVK_ANSI_A, 0, eKbdType_ANSI, str);
NS_ENSURE_TRUE(ret, ret);
PRUnichar ch = str.IsEmpty() ? PRUnichar(0) : str.CharAt(0);
mIsRTL = UCS2_CHAR_IS_BIDI(ch) || ch == 0xD802 || ch == 0xD803;
}
return mIsRTL != 0;
}
PRBool
TISInputSourceWrapper::IsInitializedByCurrentKeyboardLayout()
{
return mInputSource == ::TISCopyCurrentKeyboardLayoutInputSource();
}
PRBool
TISInputSourceWrapper::TranslateToString(UInt32 aKeyCode, UInt32 aModifiers,
UInt32 aKbdType, nsAString &aStr)
{
aStr.Truncate();
const UCKeyboardLayout* UCKey = GetUCKeyboardLayout();
NS_ENSURE_TRUE(UCKey, PR_FALSE);
return UCKeyTranslateToString(UCKey, aKeyCode, aModifiers, aKbdType, aStr);
}
void
TISInputSourceWrapper::Select()
{
if (!mInputSource)
return;
::TISSelectInputSource(mInputSource);
}
void
TISInputSourceWrapper::Clear()
{
if (mInputSourceList) {
::CFRelease(mInputSourceList);
}
mInputSourceList = nsnull;
mInputSource = nsnull;
mIsRTL = -1;
mUCKeyboardLayout = nsnull;
}
#pragma mark -
/******************************************************************************
*
* TextInputHandler implementation (static methods)
*
******************************************************************************/
// static
CFArrayRef
TextInputHandler::CreateAllKeyboardLayoutList()
{
const void* keys[] = { kTISPropertyInputSourceType };
const void* values[] = { kTISTypeKeyboardLayout };
CFDictionaryRef filter =
::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL);
NS_ASSERTION(filter, "failed to create the filter");
CFArrayRef list = ::TISCreateInputSourceList(filter, true);
::CFRelease(filter);
return list;
}
// static
void
TextInputHandler::DebugPrintAllKeyboardLayouts(PRLogModuleInfo* aLogModuleInfo)
{
CFArrayRef list = CreateAllKeyboardLayoutList();
PR_LOG(aLogModuleInfo, PR_LOG_ALWAYS, ("Keyboard layout configuration:"));
CFIndex idx = ::CFArrayGetCount(list);
TISInputSourceWrapper tis;
for (CFIndex i = 0; i < idx; ++i) {
TISInputSourceRef inputSource = static_cast<TISInputSourceRef>(
const_cast<void *>(::CFArrayGetValueAtIndex(list, i)));
tis.InitByTISInputSourceRef(inputSource);
nsAutoString name, isid;
tis.GetLocalizedName(name);
tis.GetInputSourceID(isid);
PR_LOG(aLogModuleInfo, PR_LOG_ALWAYS,
(" %s\t<%s>%s%s\n",
NS_ConvertUTF16toUTF8(name).get(),
NS_ConvertUTF16toUTF8(isid).get(),
tis.IsASCIICapable() ? "" : "\t(Isn't ASCII capable)",
tis.GetUCKeyboardLayout() ? "" : "\t(uchr is NOT AVAILABLE)"));
}
::CFRelease(list);
}
#pragma mark -
/******************************************************************************
*
* TextInputHandler implementation
*
******************************************************************************/
TextInputHandler::TextInputHandler(nsChildView* aWidget,
NSView<mozView> *aNativeView) :
IMEInputHandler(aWidget, aNativeView)
{
[mView installTextInputHandler:this];
}
TextInputHandler::~TextInputHandler()
{
[mView uninstallTextInputHandler];
}
#pragma mark -
/******************************************************************************
*
* IMEInputHandler implementation (static methods)
*
******************************************************************************/
PRBool IMEInputHandler::sStaticMembersInitialized = PR_FALSE;
CFStringRef IMEInputHandler::sLatestIMEOpenedModeInputSourceID = nsnull;
IMEInputHandler* IMEInputHandler::sFocusedIMEHandler = nsnull;
// static
void
IMEInputHandler::InitStaticMembers()
{
if (sStaticMembersInitialized)
return;
sStaticMembersInitialized = PR_TRUE;
// We need to check the keyboard layout changes on all applications.
CFNotificationCenterRef center = ::CFNotificationCenterGetDistributedCenter();
// XXX Don't we need to remove the observer at shut down?
// Mac Dev Center's document doesn't say how to remove the observer if
// the second parameter is NULL.
::CFNotificationCenterAddObserver(center, NULL,
OnCurrentTextInputSourceChange,
kTISNotifySelectedKeyboardInputSourceChanged, NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
// Initiailize with the current keyboard layout
OnCurrentTextInputSourceChange(NULL, NULL,
kTISNotifySelectedKeyboardInputSourceChanged,
NULL, NULL);
}
// static
void
IMEInputHandler::OnCurrentTextInputSourceChange(CFNotificationCenterRef aCenter,
void* aObserver,
CFStringRef aName,
const void* aObject,
CFDictionaryRef aUserInfo)
{
// Cache the latest IME opened mode to sLatestIMEOpenedModeInputSourceID.
TISInputSourceWrapper tis;
tis.InitByCurrentInputSource();
if (tis.IsOpenedIMEMode()) {
tis.GetInputSourceID(sLatestIMEOpenedModeInputSourceID);
}
#ifdef DEBUG_IME_HANDLER
static CFStringRef sLastTIS = nsnull;
CFStringRef newTIS;
tis.GetInputSourceID(newTIS);
if (!sLastTIS ||
::CFStringCompare(sLastTIS, newTIS, 0) != kCFCompareEqualTo) {
TISInputSourceWrapper tis1, tis2, tis3;
tis1.InitByCurrentKeyboardLayout();
tis2.InitByCurrentASCIICapableInputSource();
tis3.InitByCurrentASCIICapableKeyboardLayout();
CFStringRef is0, is1, is2, is3, type0, lang0, bundleID0;
tis.GetInputSourceID(is0);
tis1.GetInputSourceID(is1);
tis2.GetInputSourceID(is2);
tis3.GetInputSourceID(is3);
tis.GetInputSourceType(type0);
tis.GetPrimaryLanguage(lang0);
tis.GetBundleID(bundleID0);
NSLog(@"********************************************");
NSLog(@"Current Input Source is changed to:");
NSLog(@" current InputManager: %p", [NSInputManager currentInputManager]);
NSLog(@" %@", is0);
NSLog(@" type: %@ %s", type0,
tis.IsASCIICapable() ? "- ASCII capable " : "");
NSLog(@" primary language: %@", lang0);
NSLog(@" bundle ID: %@", bundleID0);
NSLog(@" current ASCII capable Input Source: %@", is2);
NSLog(@" current Keyboard Layout: %@", is1);
NSLog(@" current ASCII capable Keyboard Layout: %@", is3);
NSLog(@"********************************************");
}
sLastTIS = newTIS;
#endif // DEBUG_IME_HANDLER
}
// static
void
IMEInputHandler::FlushPendingMethods(nsITimer* aTimer, void* aClosure)
{
NS_ASSERTION(aClosure, "aClosure is null");
static_cast<IMEInputHandler*>(aClosure)->ExecutePendingMethods();
}
// static
CFArrayRef
IMEInputHandler::CreateAllIMEModeList()
{
const void* keys[] = { kTISPropertyInputSourceType };
const void* values[] = { kTISTypeKeyboardInputMode };
CFDictionaryRef filter =
::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL);
NS_ASSERTION(filter, "failed to create the filter");
CFArrayRef list = ::TISCreateInputSourceList(filter, true);
::CFRelease(filter);
return list;
}
// static
void
IMEInputHandler::DebugPrintAllIMEModes(PRLogModuleInfo* aLogModuleInfo)
{
CFArrayRef list = CreateAllIMEModeList();
PR_LOG(aLogModuleInfo, PR_LOG_ALWAYS, ("IME mode configuration:"));
CFIndex idx = ::CFArrayGetCount(list);
TISInputSourceWrapper tis;
for (CFIndex i = 0; i < idx; ++i) {
TISInputSourceRef inputSource = static_cast<TISInputSourceRef>(
const_cast<void *>(::CFArrayGetValueAtIndex(list, i)));
tis.InitByTISInputSourceRef(inputSource);
nsAutoString name, isid;
tis.GetLocalizedName(name);
tis.GetInputSourceID(isid);
PR_LOG(aLogModuleInfo, PR_LOG_ALWAYS,
(" %s\t<%s>%s%s\n",
NS_ConvertUTF16toUTF8(name).get(),
NS_ConvertUTF16toUTF8(isid).get(),
tis.IsASCIICapable() ? "" : "\t(Isn't ASCII capable)",
tis.IsEnabled() ? "" : "\t(Isn't Enabled)"));
}
::CFRelease(list);
}
//static
TSMDocumentID
IMEInputHandler::GetCurrentTSMDocumentID()
{
// On OS X 10.6.x at least, ::TSMGetActiveDocument() has a bug that prevents
// it from returning accurate results unless
// [NSInputManager currentInputManager] is called first.
// So, we need to call [NSInputManager currentInputManager] first here.
[NSInputManager currentInputManager];
return ::TSMGetActiveDocument();
}
#pragma mark -
/******************************************************************************
*
* IMEInputHandler implementation #1
* The methods are releated to the pending methods. Some jobs should be
* run after the stack is finished, e.g, some methods cannot run the jobs
* during processing the focus event. And also some other jobs should be
* run at the next focus event is processed.
* The pending methods are recorded in mPendingMethods. They are executed
* by ExecutePendingMethods via FlushPendingMethods.
*
******************************************************************************/
void
IMEInputHandler::ResetIMEWindowLevel()
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
#ifdef DEBUG_IME_HANDLER
DebugPrintPointer(this);
NSLog(@"IMEInputHandler::ResetIMEWindowLevel");
NSLog(@" IsFocused:%s GetCurrentTSMDocumentID():%p",
TrueOrFalse(IsFocused()), GetCurrentTSMDocumentID());
#endif // DEBUG_IME_HANDLER
if (Destroyed()) {
return;
}
if (!IsFocused()) {
// retry at next focus event
mPendingMethods |= kResetIMEWindowLevel;
return;
}
TSMDocumentID doc = GetCurrentTSMDocumentID();
if (!doc) {
// retry
mPendingMethods |= kResetIMEWindowLevel;
NS_WARNING("Application is active but there is no active document");
ResetTimer();
return;
}
// When the focus of Gecko is on a text box of a popup panel, the actual
// focused view is the panel's parent view (mView). But the editor is
// displayed on the popuped widget's view (editorView). So, their window
// level may be different.
NSView<mozView>* editorView = mWidget->GetEditorView();
if (!editorView) {
NS_ERROR("editorView is null");
return;
}
// We need to set the focused window level to TSMDocument. Then, the popup
// windows of IME (E.g., a candidate list window) will be over the focused
// view. See http://developer.apple.com/technotes/tn2005/tn2128.html#TNTAG1
NSInteger windowLevel = [[editorView window] level];
#ifdef DEBUG_IME_HANDLER
NSLog(@" windowLevel:%s (%x)",
GetWindowLevelName(windowLevel), windowLevel);
#endif // DEBUG_IME_HANDLER
// Chinese IMEs on 10.5 don't work fine if the level is NSNormalWindowLevel,
// then, we need to increment the value.
if (windowLevel == NSNormalWindowLevel)
windowLevel++;
::TSMSetDocumentProperty(GetCurrentTSMDocumentID(),
kTSMDocumentWindowLevelPropertyTag,
sizeof(windowLevel), &windowLevel);
NS_OBJC_END_TRY_ABORT_BLOCK;
}
void
IMEInputHandler::DiscardIMEComposition()
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
#ifdef DEBUG_IME_HANDLER
DebugPrintPointer(this);
NSLog(@"IMEInputHandler::DiscardIMEComposition");
NSLog(@" currentInputManager:%p", [NSInputManager currentInputManager]);
#endif // DEBUG_IME_HANDLER
if (Destroyed()) {
return;
}
if (!IsFocused()) {
// retry at next focus event
mPendingMethods |= kDiscardIMEComposition;
return;
}
NSInputManager* im = [NSInputManager currentInputManager];
if (!im) {
// retry
mPendingMethods |= kDiscardIMEComposition;
NS_WARNING("Application is active but there is no currentInputManager");
ResetTimer();
return;
}
mIgnoreIMECommit = PR_TRUE;
[im markedTextAbandoned: mView];
mIgnoreIMECommit = PR_FALSE;
NS_OBJC_END_TRY_ABORT_BLOCK
}
void
IMEInputHandler::SyncASCIICapableOnly()
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
#ifdef DEBUG_IME_HANDLER
DebugPrintPointer(this);
NSLog(@"IMEInputHandler::SyncASCIICapableOnly");
NSLog(@" IsFocused:%s GetCurrentTSMDocumentID():%p",
TrueOrFalse(IsFocused()), GetCurrentTSMDocumentID());
#endif
if (Destroyed()) {
return;
}
if (!IsFocused()) {
// retry at next focus event
mPendingMethods |= kSyncASCIICapableOnly;
return;
}
TSMDocumentID doc = GetCurrentTSMDocumentID();
if (!doc) {
// retry
mPendingMethods |= kSyncASCIICapableOnly;
NS_WARNING("Application is active but there is no active document");
ResetTimer();
return;
}
if (mIsASCIICapableOnly) {
CFArrayRef ASCIICapableTISList = ::TISCreateASCIICapableInputSourceList();
::TSMSetDocumentProperty(doc,
kTSMDocumentEnabledInputSourcesPropertyTag,
sizeof(CFArrayRef),
&ASCIICapableTISList);
::CFRelease(ASCIICapableTISList);
} else {
::TSMRemoveDocumentProperty(doc,
kTSMDocumentEnabledInputSourcesPropertyTag);
}
NS_OBJC_END_TRY_ABORT_BLOCK;
}
void
IMEInputHandler::ResetTimer()
{
NS_ASSERTION(mPendingMethods != 0,
"There are not pending methods, why this is called?");
if (mTimer) {
mTimer->Cancel();
} else {
mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
NS_ENSURE_TRUE(mTimer, );
}
mTimer->InitWithFuncCallback(FlushPendingMethods, this, 0,
nsITimer::TYPE_ONE_SHOT);
}
void
IMEInputHandler::ExecutePendingMethods()
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (mTimer) {
mTimer->Cancel();
mTimer = nsnull;
}
if (![[NSApplication sharedApplication] isActive]) {
mIsInFocusProcessing = PR_FALSE;
// If we're not active, we should retry at focus event
return;
}
PRUint32 pendingMethods = mPendingMethods;
// First, reset the pending method flags because if each methods cannot
// run now, they can reentry to the pending flags by theirselves.
mPendingMethods = 0;
if (pendingMethods & kDiscardIMEComposition)
DiscardIMEComposition();
if (pendingMethods & kSyncASCIICapableOnly)
SyncASCIICapableOnly();
if (pendingMethods & kResetIMEWindowLevel)
ResetIMEWindowLevel();
mIsInFocusProcessing = PR_FALSE;
NS_OBJC_END_TRY_ABORT_BLOCK;
}
#pragma mark -
/******************************************************************************
*
* IMEInputHandler implementation (native event handlers)
*
******************************************************************************/
PRUint32
IMEInputHandler::ConvertToTextRangeType(PRUint32 aUnderlineStyle,
NSRange& aSelectedRange)
{
#ifdef DEBUG_IME_HANDLER
NSLog(@"****in ConvertToTextRangeType = %d", aUnderlineStyle);
#endif
// We assume that aUnderlineStyle is NSUnderlineStyleSingle or
// NSUnderlineStyleThick. NSUnderlineStyleThick should indicate a selected
// clause. Otherwise, should indicate non-selected clause.
if (aSelectedRange.length == 0) {
switch (aUnderlineStyle) {
case NSUnderlineStyleSingle:
return NS_TEXTRANGE_RAWINPUT;
case NSUnderlineStyleThick:
return NS_TEXTRANGE_SELECTEDRAWTEXT;
default:
NS_WARNING("Unexpected line style");
return NS_TEXTRANGE_SELECTEDRAWTEXT;
}
}
switch (aUnderlineStyle) {
case NSUnderlineStyleSingle:
return NS_TEXTRANGE_CONVERTEDTEXT;
case NSUnderlineStyleThick:
return NS_TEXTRANGE_SELECTEDCONVERTEDTEXT;
default:
NS_WARNING("Unexpected line style");
return NS_TEXTRANGE_SELECTEDCONVERTEDTEXT;
}
}
PRUint32
IMEInputHandler::GetRangeCount(NSAttributedString *aAttrString)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
// Iterate through aAttrString for the NSUnderlineStyleAttributeName and
// count the different segments adjusting limitRange as we go.
PRUint32 count = 0;
NSRange effectiveRange;
NSRange limitRange = NSMakeRange(0, [aAttrString length]);
while (limitRange.length > 0) {
[aAttrString attribute:NSUnderlineStyleAttributeName
atIndex:limitRange.location
longestEffectiveRange:&effectiveRange
inRange:limitRange];
limitRange =
NSMakeRange(NSMaxRange(effectiveRange),
NSMaxRange(limitRange) - NSMaxRange(effectiveRange));
count++;
}
return count;
NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(0);
}
void
IMEInputHandler::SetTextRangeList(nsTArray<nsTextRange>& aTextRangeList,
NSAttributedString *aAttrString,
NSRange& aSelectedRange)
{