This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 305
/
TextInputHandler.mm
3847 lines (3281 loc) · 122 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 "mozilla/Util.h"
#include "TextInputHandler.h"
#ifdef MOZ_LOGGING
#define FORCE_PR_LOG /* Allow logging in the release build */
#endif // MOZ_LOGGING
#include "prlog.h"
#include "nsChildView.h"
#include "nsObjCExceptions.h"
#include "nsBidiUtils.h"
#include "nsToolkit.h"
#include "nsCocoaUtils.h"
#include "nsPrintfCString.h"
#ifdef __LP64__
#include "ComplexTextInputPanel.h"
#endif // __LP64__
#ifndef NP_NO_CARBON
#include <objc/runtime.h>
#endif // NP_NO_CARBON
#ifdef MOZ_LOGGING
#define FORCE_PR_LOG
#endif
#include "prlog.h"
using namespace mozilla;
using namespace mozilla::widget;
#ifdef PR_LOGGING
PRLogModuleInfo* gLog = nsnull;
static const char*
OnOrOff(bool aBool)
{
return aBool ? "ON" : "off";
}
static const char*
TrueOrFalse(bool aBool)
{
return aBool ? "TRUE" : "FALSE";
}
static const char*
GetKeyNameForNativeKeyCode(unsigned short aNativeKeyCode)
{
switch (aNativeKeyCode) {
case kEscapeKeyCode: return "Escape";
case kRCommandKeyCode: return "Right-Command";
case kCommandKeyCode: return "Command";
case kShiftKeyCode: return "Shift";
case kCapsLockKeyCode: return "CapsLock";
case kOptionkeyCode: return "Option";
case kControlKeyCode: return "Control";
case kRShiftKeyCode: return "Right-Shift";
case kROptionKeyCode: return "Right-Option";
case kRControlKeyCode: return "Right-Control";
case kClearKeyCode: return "Clear";
case kF1KeyCode: return "F1";
case kF2KeyCode: return "F2";
case kF3KeyCode: return "F3";
case kF4KeyCode: return "F4";
case kF5KeyCode: return "F5";
case kF6KeyCode: return "F6";
case kF7KeyCode: return "F7";
case kF8KeyCode: return "F8";
case kF9KeyCode: return "F9";
case kF10KeyCode: return "F10";
case kF11KeyCode: return "F11";
case kF12KeyCode: return "F12";
case kF13KeyCode: return "F13/PrintScreen";
case kF14KeyCode: return "F14/ScrollLock";
case kF15KeyCode: return "F15/Pause";
case kKeypad0KeyCode: return "NumPad-0";
case kKeypad1KeyCode: return "NumPad-1";
case kKeypad2KeyCode: return "NumPad-2";
case kKeypad3KeyCode: return "NumPad-3";
case kKeypad4KeyCode: return "NumPad-4";
case kKeypad5KeyCode: return "NumPad-5";
case kKeypad6KeyCode: return "NumPad-6";
case kKeypad7KeyCode: return "NumPad-7";
case kKeypad8KeyCode: return "NumPad-8";
case kKeypad9KeyCode: return "NumPad-9";
case kKeypadMultiplyKeyCode: return "NumPad-*";
case kKeypadAddKeyCode: return "NumPad-+";
case kKeypadSubtractKeyCode: return "NumPad--";
case kKeypadDecimalKeyCode: return "NumPad-.";
case kKeypadDivideKeyCode: return "NumPad-/";
case kKeypadEqualsKeyCode: return "NumPad-=";
case kEnterKeyCode: return "NumPad-Enter";
case kReturnKeyCode: return "NumPad-Return";
case kPowerbookEnterKeyCode: return "NumPad-EnterOnPowerBook";
case kInsertKeyCode: return "Insert/Help";
case kDeleteKeyCode: return "Delete";
case kTabKeyCode: return "Tab";
case kTildeKeyCode: return "Tilde";
case kBackspaceKeyCode: return "Backspace";
case kHomeKeyCode: return "Home";
case kEndKeyCode: return "End";
case kPageUpKeyCode: return "PageUp";
case kPageDownKeyCode: return "PageDown";
case kLeftArrowKeyCode: return "LeftArrow";
case kRightArrowKeyCode: return "RightArrow";
case kUpArrowKeyCode: return "UpArrow";
case kDownArrowKeyCode: return "DownArrow";
default: return "undefined";
}
}
static const char*
GetCharacters(const NSString* aString)
{
nsAutoString str;
nsCocoaUtils::GetStringForNSString(aString, str);
if (str.IsEmpty()) {
return "";
}
nsAutoString escapedStr;
for (PRUint32 i = 0; i < str.Length(); i++) {
PRUnichar ch = str[i];
if (ch < 0x20) {
nsPrintfCString utf8str("(U+%04X)", ch);
escapedStr += NS_ConvertUTF8toUTF16(utf8str);
} else if (ch <= 0x7E) {
escapedStr += ch;
} else {
nsPrintfCString utf8str("(U+%04X)", ch);
escapedStr += ch;
escapedStr += NS_ConvertUTF8toUTF16(utf8str);
}
}
// the result will be freed automatically by cocoa.
NSString* result = nsCocoaUtils::ToNSString(escapedStr);
return [result UTF8String];
}
static const char*
GetCharacters(const CFStringRef aString)
{
const NSString* str = reinterpret_cast<const NSString*>(aString);
return GetCharacters(str);
}
static const char*
GetNativeKeyEventType(NSEvent* aNativeEvent)
{
switch ([aNativeEvent type]) {
case NSKeyDown: return "NSKeyDown";
case NSKeyUp: return "NSKeyUp";
case NSFlagsChanged: return "NSFlagsChanged";
default: return "not key event";
}
}
static const char*
GetGeckoKeyEventType(const nsEvent &aEvent)
{
switch (aEvent.message) {
case NS_KEY_DOWN: return "NS_KEY_DOWN";
case NS_KEY_UP: return "NS_KEY_UP";
case NS_KEY_PRESS: return "NS_KEY_PRESS";
default: return "not key event";
}
}
static const char*
GetRangeTypeName(PRUint32 aRangeType)
{
switch (aRangeType) {
case NS_TEXTRANGE_RAWINPUT:
return "NS_TEXTRANGE_RAWINPUT";
case NS_TEXTRANGE_CONVERTEDTEXT:
return "NS_TEXTRANGE_CONVERTEDTEXT";
case NS_TEXTRANGE_SELECTEDRAWTEXT:
return "NS_TEXTRANGE_SELECTEDRAWTEXT";
case NS_TEXTRANGE_SELECTEDCONVERTEDTEXT:
return "NS_TEXTRANGE_SELECTEDCONVERTEDTEXT";
case NS_TEXTRANGE_CARETPOSITION:
return "NS_TEXTRANGE_CARETPOSITION";
default:
return "invalid range type";
}
}
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 // #ifdef PR_LOGGING
static PRUint32 gHandlerInstanceCount = 0;
static TISInputSourceWrapper gCurrentKeyboardLayout;
static void
InitLogModule()
{
#ifdef PR_LOGGING
// Clear() is always called when TISInputSourceWrappper is created.
if (!gLog) {
gLog = PR_NewLogModule("TextInputHandlerWidgets");
TextInputHandler::DebugPrintAllKeyboardLayouts();
IMEInputHandler::DebugPrintAllIMEModes();
}
#endif
}
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;
}
bool
TISInputSourceWrapper::TranslateToString(UInt32 aKeyCode, UInt32 aModifiers,
UInt32 aKbType, nsAString &aStr)
{
aStr.Truncate();
const UCKeyboardLayout* UCKey = GetUCKeyboardLayout();
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::TranslateToString, aKeyCode=0x%X, "
"aModifiers=0x%X, aKbType=0x%X UCKey=%p\n "
"Shift: %s, Ctrl: %s, Opt: %s, Cmd: %s, CapsLock: %s, NumLock: %s",
this, aKeyCode, aModifiers, aKbType, UCKey,
OnOrOff(aModifiers & shiftKey), OnOrOff(aModifiers & controlKey),
OnOrOff(aModifiers & optionKey), OnOrOff(aModifiers & cmdKey),
OnOrOff(aModifiers & alphaLock),
OnOrOff(aModifiers & kEventKeyModifierNumLockMask)));
NS_ENSURE_TRUE(UCKey, false);
UInt32 deadKeyState = 0;
UniCharCount len;
UniChar chars[5];
OSStatus err = ::UCKeyTranslate(UCKey, aKeyCode,
kUCKeyActionDown, aModifiers >> 8,
aKbType, kUCKeyTranslateNoDeadKeysMask,
&deadKeyState, 5, &len, chars);
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::TranslateToString, err=0x%X, len=%llu",
this, err, len));
NS_ENSURE_TRUE(err == noErr, false);
if (len == 0) {
return true;
}
NS_ENSURE_TRUE(EnsureStringLength(aStr, len), false);
NS_ASSERTION(sizeof(PRUnichar) == sizeof(UniChar),
"size of PRUnichar and size of UniChar are different");
memcpy(aStr.BeginWriting(), chars, len * sizeof(PRUnichar));
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::TranslateToString, aStr=\"%s\"",
this, NS_ConvertUTF16toUTF8(aStr).get()));
return true;
}
PRUint32
TISInputSourceWrapper::TranslateToChar(UInt32 aKeyCode, UInt32 aModifiers,
UInt32 aKbType)
{
nsAutoString str;
if (!TranslateToString(aKeyCode, aModifiers, aKbType, str) ||
str.Length() != 1) {
return 0;
}
return static_cast<PRUint32>(str.CharAt(0));
}
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,
bool aOverrideKeyboard)
{
// NOTE: Doument new layout IDs in TextInputHandler.h when you add ones.
switch (aLayoutID) {
case 0:
InitByInputSourceID("com.apple.keylayout.US");
break;
case 1:
InitByInputSourceID("com.apple.keylayout.Greek");
break;
case 2:
InitByInputSourceID("com.apple.keylayout.German");
break;
case 3:
InitByInputSourceID("com.apple.keylayout.Swedish-Pro");
break;
case 4:
InitByInputSourceID("com.apple.keylayout.DVORAK-QWERTYCMD");
break;
case 5:
InitByInputSourceID("com.apple.keylayout.Thai");
break;
default:
Clear();
break;
}
mOverrideKeyboard = aOverrideKeyboard;
}
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;
}
bool
TISInputSourceWrapper::GetBoolProperty(const CFStringRef aKey)
{
CFBooleanRef ret = static_cast<CFBooleanRef>(
::TISGetInputSourceProperty(mInputSource, aKey));
return ::CFBooleanGetValue(ret);
}
bool
TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey,
CFStringRef &aStr)
{
aStr = static_cast<CFStringRef>(
::TISGetInputSourceProperty(mInputSource, aKey));
return aStr != nsnull;
}
bool
TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey,
nsAString &aStr)
{
CFStringRef str;
GetStringProperty(aKey, str);
nsCocoaUtils::GetStringForNSString((const NSString*)str, aStr);
return !aStr.IsEmpty();
}
bool
TISInputSourceWrapper::IsOpenedIMEMode()
{
NS_ENSURE_TRUE(mInputSource, false);
if (!IsIMEMode())
return false;
return !IsASCIICapable();
}
bool
TISInputSourceWrapper::IsIMEMode()
{
NS_ENSURE_TRUE(mInputSource, false);
CFStringRef str;
GetInputSourceType(str);
NS_ENSURE_TRUE(str, false);
return ::CFStringCompare(kTISTypeKeyboardInputMode,
str, 0) == kCFCompareEqualTo;
}
bool
TISInputSourceWrapper::GetLanguageList(CFArrayRef &aLanguageList)
{
NS_ENSURE_TRUE(mInputSource, false);
aLanguageList = static_cast<CFArrayRef>(
::TISGetInputSourceProperty(mInputSource,
kTISPropertyInputSourceLanguages));
return aLanguageList != nsnull;
}
bool
TISInputSourceWrapper::GetPrimaryLanguage(CFStringRef &aPrimaryLanguage)
{
NS_ENSURE_TRUE(mInputSource, false);
CFArrayRef langList;
NS_ENSURE_TRUE(GetLanguageList(langList), false);
if (::CFArrayGetCount(langList) == 0)
return false;
aPrimaryLanguage =
static_cast<CFStringRef>(::CFArrayGetValueAtIndex(langList, 0));
return aPrimaryLanguage != nsnull;
}
bool
TISInputSourceWrapper::GetPrimaryLanguage(nsAString &aPrimaryLanguage)
{
NS_ENSURE_TRUE(mInputSource, false);
CFStringRef primaryLanguage;
NS_ENSURE_TRUE(GetPrimaryLanguage(primaryLanguage), false);
nsCocoaUtils::GetStringForNSString((const NSString*)primaryLanguage,
aPrimaryLanguage);
return !aPrimaryLanguage.IsEmpty();
}
bool
TISInputSourceWrapper::IsForRTLLanguage()
{
if (mIsRTL < 0) {
// Get the input character of the 'A' key of ANSI keyboard layout.
nsAutoString str;
bool 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;
}
bool
TISInputSourceWrapper::IsInitializedByCurrentKeyboardLayout()
{
return mInputSource == ::TISCopyCurrentKeyboardLayoutInputSource();
}
void
TISInputSourceWrapper::Select()
{
if (!mInputSource)
return;
::TISSelectInputSource(mInputSource);
}
void
TISInputSourceWrapper::Clear()
{
// Clear() is always called when TISInputSourceWrappper is created.
InitLogModule();
if (mInputSourceList) {
::CFRelease(mInputSourceList);
}
mInputSourceList = nsnull;
mInputSource = nsnull;
mIsRTL = -1;
mUCKeyboardLayout = nsnull;
mOverrideKeyboard = false;
}
void
TISInputSourceWrapper::InitKeyEvent(NSEvent *aNativeKeyEvent,
nsKeyEvent& aKeyEvent)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyEvent, aNativeKeyEvent=%p"
"aKeyEvent.message=%s",
this, aNativeKeyEvent, GetGeckoKeyEventType(aKeyEvent)));
NS_ENSURE_TRUE(aNativeKeyEvent, );
aKeyEvent.time = PR_IntervalNow();
NSUInteger modifiers = [aNativeKeyEvent modifierFlags];
aKeyEvent.isShift = ((modifiers & NSShiftKeyMask) != 0);
aKeyEvent.isControl = ((modifiers & NSControlKeyMask) != 0);
aKeyEvent.isAlt = ((modifiers & NSAlternateKeyMask) != 0);
aKeyEvent.isMeta = ((modifiers & NSCommandKeyMask) != 0);
aKeyEvent.refPoint = nsIntPoint(0, 0);
aKeyEvent.isChar = false; // XXX not used in XP level
NSString* str = nil;
if ([aNativeKeyEvent type] != NSFlagsChanged) {
str = [aNativeKeyEvent charactersIgnoringModifiers];
}
aKeyEvent.keyCode =
TextInputHandler::ComputeGeckoKeyCode([aNativeKeyEvent keyCode], str);
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyEvent, "
"shift=%s, ctrl=%s, alt=%s, meta=%s",
this, OnOrOff(aKeyEvent.isShift), OnOrOff(aKeyEvent.isControl),
OnOrOff(aKeyEvent.isAlt), OnOrOff(aKeyEvent.isMeta)));
if (aKeyEvent.message == NS_KEY_PRESS &&
!TextInputHandler::IsSpecialGeckoKey([aNativeKeyEvent keyCode])) {
InitKeyPressEvent(aNativeKeyEvent, aKeyEvent);
return;
}
aKeyEvent.charCode = 0;
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyEvent, keyCode=0x%X charCode=0x0",
this, aKeyEvent.keyCode));
NS_OBJC_END_TRY_ABORT_BLOCK
}
void
TISInputSourceWrapper::InitKeyPressEvent(NSEvent *aNativeKeyEvent,
nsKeyEvent& aKeyEvent)
{
NS_ASSERTION(aKeyEvent.message == NS_KEY_PRESS,
"aKeyEvent must be NS_KEY_PRESS event");
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyPressEvent, aNativeKeyEvent=%p"
"aKeyEvent.message=%s",
this, aNativeKeyEvent, GetGeckoKeyEventType(aKeyEvent)));
aKeyEvent.isChar = true; // this is not a special key XXX not used in XP
aKeyEvent.charCode = 0;
NSString* chars = [aNativeKeyEvent characters];
if ([chars length] > 0) {
aKeyEvent.charCode = [chars characterAtIndex:0];
}
// convert control-modified charCode to raw charCode (with appropriate case)
if (aKeyEvent.isControl && aKeyEvent.charCode <= 26) {
aKeyEvent.charCode += (aKeyEvent.isShift) ? ('A' - 1) : ('a' - 1);
}
if (aKeyEvent.charCode != 0) {
aKeyEvent.keyCode = 0;
}
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyPressEvent, "
"aKeyEvent.keyCode=0x%X, aKeyEvent.charCode=0x%X",
this, aKeyEvent.keyCode, aKeyEvent.charCode));
if (!aKeyEvent.isControl && !aKeyEvent.isMeta && !aKeyEvent.isAlt) {
return;
}
TISInputSourceWrapper USLayout("com.apple.keylayout.US");
bool isRomanKeyboardLayout = IsASCIICapable();
// If a keyboard layout override is set, we also need to force the
// keyboard type to something ANSI to avoid test failures on machines
// with JIS keyboards (since the pair of keyboard layout and physical
// keyboard type form the actual key layout). This assumes that the
// test setting the override was written assuming an ANSI keyboard.
UInt32 kbType = mOverrideKeyboard ? eKbdType_ANSI : ::LMGetKbdType();
UInt32 key = [aNativeKeyEvent keyCode];
// Caps lock and num lock modifier state:
UInt32 lockState = 0;
if ([aNativeKeyEvent modifierFlags] & NSAlphaShiftKeyMask) {
lockState |= alphaLock;
}
if ([aNativeKeyEvent modifierFlags] & NSNumericPadKeyMask) {
lockState |= kEventKeyModifierNumLockMask;
}
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyPressEvent, "
"isRomanKeyboardLayout=%s, kbType=0x%X, key=0x%X",
this, TrueOrFalse(isRomanKeyboardLayout), kbType, key));
nsString str;
// normal chars
PRUint32 unshiftedChar = TranslateToChar(key, lockState, kbType);
UInt32 shiftLockMod = shiftKey | lockState;
PRUint32 shiftedChar = TranslateToChar(key, shiftLockMod, kbType);
// characters generated with Cmd key
// XXX we should remove CapsLock state, which changes characters from
// Latin to Cyrillic with Russian layout on 10.4 only when Cmd key
// is pressed.
UInt32 numState = (lockState & ~alphaLock); // only num lock state
PRUint32 uncmdedChar = TranslateToChar(key, numState, kbType);
UInt32 shiftNumMod = numState | shiftKey;
PRUint32 uncmdedShiftChar = TranslateToChar(key, shiftNumMod, kbType);
PRUint32 uncmdedUSChar = USLayout.TranslateToChar(key, numState, kbType);
UInt32 cmdNumMod = cmdKey | numState;
PRUint32 cmdedChar = TranslateToChar(key, cmdNumMod, kbType);
UInt32 cmdShiftNumMod = shiftKey | cmdNumMod;
PRUint32 cmdedShiftChar = TranslateToChar(key, cmdShiftNumMod, kbType);
// Is the keyboard layout changed by Cmd key?
// E.g., Arabic, Russian, Hebrew, Greek and Dvorak-QWERTY.
bool isCmdSwitchLayout = uncmdedChar != cmdedChar;
// Is the keyboard layout for Latin, but Cmd key switches the layout?
// I.e., Dvorak-QWERTY
bool isDvorakQWERTY = isCmdSwitchLayout && isRomanKeyboardLayout;
// If the current keyboard is not Dvorak-QWERTY or Cmd is not pressed,
// we should append unshiftedChar and shiftedChar for handling the
// normal characters. These are the characters that the user is most
// likely to associate with this key.
if ((unshiftedChar || shiftedChar) &&
(!aKeyEvent.isMeta || !isDvorakQWERTY)) {
nsAlternativeCharCode altCharCodes(unshiftedChar, shiftedChar);
aKeyEvent.alternativeCharCodes.AppendElement(altCharCodes);
}
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyPressEvent, "
"aKeyEvent.isMeta=%s, isDvorakQWERTY=%s, "
"unshiftedChar=U+%X, shiftedChar=U+%X",
this, OnOrOff(aKeyEvent.isMeta), TrueOrFalse(isDvorakQWERTY),
unshiftedChar, shiftedChar));
// Most keyboard layouts provide the same characters in the NSEvents
// with Command+Shift as with Command. However, with Command+Shift we
// want the character on the second level. e.g. With a US QWERTY
// layout, we want "?" when the "/","?" key is pressed with
// Command+Shift.
// On a German layout, the OS gives us '/' with Cmd+Shift+SS(eszett)
// even though Cmd+SS is 'SS' and Shift+'SS' is '?'. This '/' seems
// like a hack to make the Cmd+"?" event look the same as the Cmd+"?"
// event on a US keyboard. The user thinks they are typing Cmd+"?", so
// we'll prefer the "?" character, replacing charCode with shiftedChar
// when Shift is pressed. However, in case there is a layout where the
// character unique to Cmd+Shift is the character that the user expects,
// we'll send it as an alternative char.
bool hasCmdShiftOnlyChar =
cmdedChar != cmdedShiftChar && uncmdedShiftChar != cmdedShiftChar;
PRUint32 originalCmdedShiftChar = cmdedShiftChar;
// If we can make a good guess at the characters that the user would
// expect this key combination to produce (with and without Shift) then
// use those characters. This also corrects for CapsLock, which was
// ignored above.
if (!isCmdSwitchLayout) {
// The characters produced with Command seem similar to those without
// Command.
if (unshiftedChar) {
cmdedChar = unshiftedChar;
}
if (shiftedChar) {
cmdedShiftChar = shiftedChar;
}
} else if (uncmdedUSChar == cmdedChar) {
// It looks like characters from a US layout are provided when Command
// is down.
PRUint32 ch = USLayout.TranslateToChar(key, lockState, kbType);
if (ch) {
cmdedChar = ch;
}
ch = USLayout.TranslateToChar(key, shiftLockMod, kbType);
if (ch) {
cmdedShiftChar = ch;
}
}
// Only charCode (not alternativeCharCodes) is available to javascript,
// so attempt to set this to the most likely intended (or most useful)
// character. Note that cmdedChar and cmdedShiftChar are usually
// Latin/ASCII characters and that is what is wanted here as accel
// keys are expected to be Latin characters.
//
// XXX We should do something similar when Control is down (bug 429510).
if (aKeyEvent.isMeta && !(aKeyEvent.isControl || aKeyEvent.isAlt)) {
// The character to use for charCode.
PRUint32 preferredCharCode = 0;
preferredCharCode = aKeyEvent.isShift ? cmdedShiftChar : cmdedChar;
if (preferredCharCode) {
aKeyEvent.charCode = preferredCharCode;
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyPressEvent, "
"aKeyEvent.charCode=U+%X",
this, aKeyEvent.charCode));
}
}
// If the current keyboard layout is switched by the Cmd key,
// we should append cmdedChar and shiftedCmdChar that are
// Latin char for the key.
// If the keyboard layout is Dvorak-QWERTY, we should append them only when
// command key is pressed because when command key isn't pressed, uncmded
// chars have been appended already.
if ((cmdedChar || cmdedShiftChar) && isCmdSwitchLayout &&
(aKeyEvent.isMeta || !isDvorakQWERTY)) {
nsAlternativeCharCode altCharCodes(cmdedChar, cmdedShiftChar);
aKeyEvent.alternativeCharCodes.AppendElement(altCharCodes);
}
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyPressEvent, "
"hasCmdShiftOnlyChar=%s, isCmdSwitchLayout=%s, isDvorakQWERTY=%s, "
"cmdedChar=U+%X, cmdedShiftChar=U+%X",
this, TrueOrFalse(hasCmdShiftOnlyChar), TrueOrFalse(isDvorakQWERTY),
TrueOrFalse(isDvorakQWERTY), cmdedChar, cmdedShiftChar));
// Special case for 'SS' key of German layout. See the comment of
// hasCmdShiftOnlyChar definition for the detail.
if (hasCmdShiftOnlyChar && originalCmdedShiftChar) {
nsAlternativeCharCode altCharCodes(0, originalCmdedShiftChar);
aKeyEvent.alternativeCharCodes.AppendElement(altCharCodes);
}
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TISInputSourceWrapper::InitKeyPressEvent, "
"hasCmdShiftOnlyChar=%s, originalCmdedShiftChar=U+%X",
this, TrueOrFalse(hasCmdShiftOnlyChar), originalCmdedShiftChar));
}
#pragma mark -
/******************************************************************************
*
* TextInputHandler implementation (static methods)
*
******************************************************************************/
NSUInteger TextInputHandler::sLastModifierState = 0;
// 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()
{
#ifdef PR_LOGGING
if (PR_LOG_TEST(gLog, PR_LOG_ALWAYS)) {
CFArrayRef list = CreateAllKeyboardLayoutList();
PR_LOG(gLog, 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(gLog, 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);
}
#endif // #ifdef PR_LOGGING
}
#pragma mark -
/******************************************************************************
*
* TextInputHandler implementation
*
******************************************************************************/
TextInputHandler::TextInputHandler(nsChildView* aWidget,
NSView<mozView> *aNativeView) :
IMEInputHandler(aWidget, aNativeView)
{
InitLogModule();
[mView installTextInputHandler:this];
}
TextInputHandler::~TextInputHandler()
{
[mView uninstallTextInputHandler];
}
bool
TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
if (Destroyed()) {
PR_LOG(gLog, PR_LOG_ALWAYS,
("%p TextInputHandler::HandleKeyDownEvent, "
"widget has been already destroyed", this));
return false;
}