This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
keyboard.js
1847 lines (1551 loc) · 56.6 KB
/
keyboard.js
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: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/**
* @fileoverview Keyboard Overview.
*
* **keyboard.js**:
*
* This is the main module of the Gaia keyboard app. It does these things:
*
* - Hides and shows the keyboard in response to focuschange events from
* navigator.mozInputMethod.inputcontext
*
* - Loads the input method (from imes/) module required by a keyboard
*
* - Handles settings changes for the user's language, keyboard layouts, and
* preferences for word suggestions, and updates the keyboard accordingly.
*
* - Handles resize events (caused by orientation changes) and updates
* the keyboard accordingly.
*
* - Handles (using code that was formerly in a separate controller.js module)
* mouse events over the keyboard and passes them to the input method.
*
* - When the input method sends value back to the keyboard, it turns
* them into synthetic key events using the inputmethod API.
*
* This module includes code that was formerly in the controller.js and
* feedback.js modules. Other modules handle other parts of the keyboard:
*
* * **layout.js**: defines data structures that represent keyboard layouts
* * **render.js**: creates the on-screen keyboard with HTML and CSS
*
*/
'use strict';
// A timer for time measurement
// XXX: render.js is using this variable from other script.
var perfTimer = new PerformanceTimer();
perfTimer.start();
perfTimer.printTime('keyboard.js');
var inputContext = null;
// The keyboard app can display different layouts for different languages
// We sometimes refer to these different layouts as "keyboards", so this single
// keyboard app can display many different keyboards. The currently displayed
// keyboard is specified with updateCurrentLayout(). That function sets the
// following variables based on its argument.
//
// See keyboard/layouts for layout data.
//
// The keyboardName is always the URL hash this page loaded with.
// updateCurrentLayout() is called when pages loads, when visibility changes,
// and when URL hash changes.
var keyboardName = null;
// These are the possible layout page values
const LAYOUT_PAGE_DEFAULT = 'Default';
const LAYOUT_PAGE_SYMBOLS_I = 'Symbols_1';
const LAYOUT_PAGE_SYMBOLS_II = 'Symbols_2';
// Layout page: what set of symbols should the keyboard display?
var layoutPage = LAYOUT_PAGE_DEFAULT;
// This object is based on the keyboard layout from layout.js, but is
// modified (see modifyLayout()) to include keys for switching keyboards
// and layouts, and type specific keys like ".com" for url keyboards.
var currentLayout = null;
var isWaitingForSecondTap = false;
var isShowingAlternativesMenu = false;
var isShowingKeyboardLayoutMenu = false;
var isContinousSpacePressed = false;
var isUpperCase = false;
var isUpperCaseLocked = false;
var currentKey = null;
var touchEventsPresent = false;
var touchedKeys = {};
var touchCount = 0;
var currentInputType = null;
var currentInputMode = null;
var menuLockedArea = null;
var isKeyboardRendered = false;
var currentCandidates = [];
var candidatePanelScrollTimer = null;
// Show accent char menu (if there is one) after ACCENT_CHAR_MENU_TIMEOUT
const ACCENT_CHAR_MENU_TIMEOUT = 700;
// Backspace repeat delay and repeat rate
const REPEAT_RATE = 75;
const REPEAT_TIMEOUT = 700;
// How long to wait for more focuschange events before processing
const FOCUS_CHANGE_DELAY = 100;
// Taps the shift key twice within CAPS_LOCK_TIMEOUT
// to lock the keyboard at upper case state.
const CAPS_LOCK_TIMEOUT = 450;
// Time we wait after blur to hide the keyboard
// in case we get a focus event right after
const HIDE_KEYBOARD_TIMEOUT = 500;
// timeout and interval for delete, they could be cancelled on mouse over
var deleteTimeout = 0;
var deleteInterval = 0;
var menuTimeout = 0;
var hideKeyboardTimeout = 0;
// Special key codes
const BASIC_LAYOUT = -1;
const ALTERNATE_LAYOUT = -2;
const SWITCH_KEYBOARD = -3;
const TOGGLE_CANDIDATE_PANEL = -4;
const NO_OP = -5;
const specialCodes = [
KeyEvent.DOM_VK_BACK_SPACE,
KeyEvent.DOM_VK_CAPS_LOCK,
KeyEvent.DOM_VK_RETURN,
KeyEvent.DOM_VK_ALT,
KeyEvent.DOM_VK_SPACE
];
// InputMethodManager is responsible of loading/activating input methods.
// XXX: For now let's pass a fake app object.
var fakeAppObject = {
sendCandidates: function kc_glue_sendCandidates(candidates) {
perfTimer.printTime('glue.sendCandidates');
currentCandidates = candidates;
IMERender.showCandidates(candidates);
},
setComposition: function kc_glue_setComposition(symbols, cursor) {
perfTimer.printTime('glue.setComposition');
cursor = cursor || symbols.length;
inputContext.setComposition(symbols, cursor);
},
endComposition: function kc_glue_endComposition(text) {
perfTimer.printTime('glue.endComposition');
text = text || '';
inputContext.endComposition(text);
},
sendKey: sendKey,
alterKeyboard: function kc_glue_alterKeyboard(keyboard) {
renderKeyboard(keyboard);
},
setLayoutPage: setLayoutPage,
setUpperCase: setUpperCase,
resetUpperCase: resetUpperCase,
isCapitalized: isCapitalized,
replaceSurroundingText: replaceSurroundingText,
getNumberOfCandidatesPerRow:
IMERender.getNumberOfCandidatesPerRow.bind(IMERender)
};
var inputMethodManager = new InputMethodManager(fakeAppObject);
inputMethodManager.start();
// LayoutManager loads and holds layout layouts for us.
// It also help us ensure there is only one current layout at the time.
var layoutManager = new LayoutManager();
layoutManager.start();
var layoutLoader = layoutManager.loader;
// SettingsPromiseManager wraps Settings DB methods into promises.
var settingsPromiseManager = new SettingsPromiseManager();
// L10nLoader loads l10n.js. We call it's one and only load() method
// only after we have run everything in the critical cold launch path.
var l10nLoader = new L10nLoader();
// User settings (in Settings database) are tracked within these modules
var soundFeedbackSettings;
var vibrationFeedbackSettings;
var imEngineSettings;
// We keep this promise in the global scope for the time being,
// so they can be called as soon as we need it to.
var inputContextGetTextPromise;
// data URL for keyboard click sound
const CLICK_SOUND = './resources/sounds/key.ogg';
const SPECIAL_SOUND = './resources/sounds/special.ogg';
// The audio element used to play the click sound
var clicker;
var specialClicker;
// A MutationObserver we use to spy on the renderer module
var dimensionsObserver;
// A map of event names to event handlers.
// We register these handlers on the keyboard renderer element
var eventHandlers = {
'touchstart': onTouchStart,
'mousedown': onMouseDown,
'mouseup': onMouseUp,
'mousemove': onMouseMove
};
// For tracking "scrolling the full candidate panel".
var touchStartCoordinate;
initKeyboard();
// We cannot listen to resize event right at start because of
// https://bugzil.la/1007595 ;
// only attach the event listener after 600ms.
setTimeout(function attachResizeListener() {
perfTimer.printTime('attachResizeListener');
// Handle resize events
window.addEventListener('resize', onResize);
}, 2000);
function initKeyboard() {
perfTimer.startTimer('initKeyboard');
perfTimer.printTime('initKeyboard');
// Getting initial settings values asynchronously,
// Plus monitor the value when it changes.
soundFeedbackSettings = new SoundFeedbackSettings();
soundFeedbackSettings.promiseManager = settingsPromiseManager;
soundFeedbackSettings.onsettingchange = handleKeyboardSound;
soundFeedbackSettings.initSettings().then(
handleKeyboardSound,
function rejected() {
console.warn('Failed to get initial sound settings.');
});
vibrationFeedbackSettings = new VibrationFeedbackSettings();
vibrationFeedbackSettings.promiseManager = settingsPromiseManager;
var vibrationInitPromise = vibrationFeedbackSettings.initSettings();
vibrationInitPromise.catch(function rejected() {
console.warn('Failed to get initial vibration settings.');
});
imEngineSettings = new IMEngineSettings();
imEngineSettings.promiseManager = settingsPromiseManager;
var imEngineSettingsInitPromise = imEngineSettings.initSettings();
imEngineSettingsInitPromise.catch(function rejected() {
console.error('Fatal Error! Failed to get initial imEngine settings.');
});
// Initialize the rendering module
IMERender.init(getUpperCaseValue, isSpecialKeyObj);
// Attach event listeners to the element that does rendering
for (var event in eventHandlers) {
IMERender.ime.addEventListener(event, eventHandlers[event]);
}
dimensionsObserver = new MutationObserver(function() {
perfTimer.printTime('dimensionsObserver:callback');
updateTargetWindowHeight();
});
// And observe mutation events on the renderer element
dimensionsObserver.observe(IMERender.ime, {
childList: true, // to detect changes in IMEngine
attributes: true, attributeFilter: ['class', 'style']
});
window.addEventListener('hashchange', function() {
perfTimer.printTime('hashchange');
var layoutName = window.location.hash.substring(1);
layoutLoader.getLayoutAsync(layoutName);
updateCurrentLayout(layoutName);
}, false);
// Need to listen to both mozvisibilitychange and oninputcontextchange,
// because we are not sure which will happen first and we will call
// showKeyboard() when mozHidden is false and we got inputContext
window.addEventListener('mozvisibilitychange', function visibilityHandler() {
perfTimer.printTime('mozvisibilitychange');
if (document.mozHidden && !inputContext) {
hideKeyboard();
return;
}
var layoutName = window.location.hash.substring(1);
updateCurrentLayout(layoutName);
});
window.navigator.mozInputMethod.oninputcontextchange = function() {
perfTimer.printTime('inputcontextchange');
inputContext = navigator.mozInputMethod.inputcontext;
if (inputContext) {
inputContextGetTextPromise = inputContext.getText();
}
if (document.mozHidden && !inputContext) {
hideKeyboard();
return;
}
var layoutName = window.location.hash.substring(1);
updateCurrentLayout(layoutName);
};
// Initialize the current layout according to
// the hash this page is loaded with.
var layoutName = '';
if (window.location.hash !== '') {
layoutName = window.location.hash.substring(1);
layoutLoader.getLayoutAsync(layoutName);
} else {
console.error('This page should never be loaded without an URL hash.');
return;
}
// fill inputContextGetTextPromise and inputContext
inputContext = navigator.mozInputMethod.inputcontext;
if (inputContext) {
inputContextGetTextPromise = inputContext.getText();
}
// Finally, if we are only loaded by keyboard manager when the user
// have already focused, the keyboard should show right away.
updateCurrentLayout(layoutName);
}
function handleKeyboardSound(settings) {
if (settings.clickEnabled &&
!!settings.isSoundEnabled) {
clicker = new Audio(CLICK_SOUND);
specialClicker = new Audio(SPECIAL_SOUND);
} else {
clicker = null;
specialClicker = null;
}
}
function deactivateInputMethod() {
// Switching to default IMEngine makes the current IMEngine deactivate.
// The currentIMEngine will be set and activates again in
// showKeyboard() (specifically, switchIMEngine()).
inputMethodManager.switchCurrentIMEngine('default');
}
function updateCurrentLayout(name) {
perfTimer.printTime('updateCurrentLayout');
layoutManager.switchCurrentLayout(name).then(function() {
perfTimer.printTime('updateCurrentLayout:promise resolved');
keyboardName = name;
keyboard = layoutLoader.getLayout(name);
// Ask the loader to start loading IMEngine
var imEngineloader = inputMethodManager.loader;
var imEngineName = keyboard.imEngine;
if (imEngineName && !imEngineloader.getInputMethod(imEngineName)) {
imEngineloader.getInputMethodAsync(imEngineName);
}
// Now the that we have the layout ready,
// we should either show or hide the keyboard.
if (!document.mozHidden && inputContext) {
showKeyboard();
} else {
hideKeyboard();
// Load l10n library here, there is nothing more to do left
// in the critical path.
l10nLoader.load();
}
}, function(error) {
console.warn('Failed to switch layout for ' + name + '.' +
' It might possible because we were called more than once.');
});
}
// Support function for render
function isSpecialKeyObj(key) {
var hasSpecialCode = key.keyCode !== KeyEvent.DOM_VK_SPACE &&
key.keyCode &&
specialCodes.indexOf(key.keyCode) !== -1;
return hasSpecialCode || key.keyCode <= 0;
}
// Map the input type to another type
function mapInputType(type) {
switch (type) {
// basic types
case 'url':
case 'tel':
case 'email':
case 'text':
return type;
break;
// default fallback and textual types
case 'password':
case 'search':
default:
return 'text';
break;
case 'number':
case 'range': // XXX: should be different from number
return 'number';
break;
}
}
//
// This function takes a keyboard layout, makes a copy of that layout
// and then modifies it to add meta keys for switching languages and
// switching to numbers and symbols. It may also add keys (like a
// ".com" and '@') that are specific to input of currentInputType.
//
// The return value is the modified layout data structure.
//
// Normally, this function modifies the base layout for the specified
// keyboard name, but it may use a different starting layout depending on
// currentInputType and layoutPage.
//
function modifyLayout(keyboardName) {
// One level copy
function copy(obj) {
var newObj = {};
for (var prop in obj) if (obj.hasOwnProperty(prop)) {
newObj[prop] = obj[prop];
}
return newObj;
}
// Test if a key has alternatives
function hasAlternatives(layout, value) {
if (!layout.alt)
return false;
return (value in layout.alt);
}
var altLayoutName;
switch (currentInputType) {
case 'tel':
altLayoutName = 'telLayout';
break;
case 'number':
altLayoutName = currentInputMode === 'digit' ?
'pinLayout' : 'numberLayout';
break;
// The matches when type="password", "text", or "search",
// see mapInputType() for details
case 'text':
if (currentInputMode === 'digit') {
altLayoutName = 'pinLayout';
} else if (currentInputMode === 'numeric') {
altLayoutName = 'numberLayout';
} else if (isGreekSMS()) {
altLayoutName = 'el-sms';
}
break;
}
if (layoutPage === LAYOUT_PAGE_SYMBOLS_I) {
altLayoutName = 'alternateLayout';
} else if (layoutPage === LAYOUT_PAGE_SYMBOLS_II) {
altLayoutName = 'symbolLayout';
}
// Start with this base layout
var layout;
if (altLayoutName) {
layout = layoutLoader.getLayout(keyboardName)[altLayoutName] ||
layoutLoader.getLayout(altLayoutName);
}
else {
layout = layoutLoader.getLayout(keyboardName);
}
// Look for the space key in the layout. We're going to insert
// meta keys before it or after it.
var where = false;
for (var r = 0, row; !where && (row = layout.keys[r]); r += 1) {
for (var c = 0, space; space = layout.keys[r][c]; c += 1) {
if (space.keyCode == KeyboardEvent.DOM_VK_SPACE) {
where = r;
break;
}
}
}
// if found, add special keys
if (where) {
// we will perform some alchemy here, so preserve...
layout = copy(layout); // the original space row
layout.keys = layout.keys.slice(0);
row = layout.keys[where] = layout.keys[where].slice(0);
space = copy(space); // and the original space key
row[c] = space;
// Alternate layout key
// This gives the author the ability to change the alternate layout
// key contents
var alternateLayoutKey = '12&';
if (layout['alternateLayoutKey']) {
alternateLayoutKey = layout['alternateLayoutKey'];
}
// This gives the author the ability to change the basic layout
// key contents
// 'layout' holds alternatelayout which doesn't include basicLayoutKey.
// Check and use 'basicLayoutKey' defined by each keyboard.
var basicLayoutKey = 'ABC';
if (layoutLoader.getLayout(keyboardName)['basicLayoutKey']) {
basicLayoutKey = layoutLoader.getLayout(keyboardName)['basicLayoutKey'];
}
if (!layout['disableAlternateLayout']) {
space.ratio -= 1.5;
if (layoutPage === LAYOUT_PAGE_DEFAULT) {
row.splice(c, 0, {
keyCode: ALTERNATE_LAYOUT,
value: alternateLayoutKey,
ratio: 1.5,
ariaLabel: 'alternateLayoutKey',
className: 'switch-key'
});
} else {
row.splice(c, 0, {
keyCode: BASIC_LAYOUT,
value: basicLayoutKey,
ratio: 1.5,
ariaLabel: 'basicLayoutKey'
});
}
c += 1;
}
// switch languages button
var supportsSwitching = navigator.mozInputMethod.mgmt.supportsSwitching();
var needsSwitchingKey = !layout['hidesSwitchKey'] && supportsSwitching;
if (needsSwitchingKey) {
var imeSwitchKey = {
value: '🌐',
ratio: 1,
keyCode: SWITCH_KEYBOARD,
className: 'switch-key'
};
if ('shortLabel' in layoutLoader.getLayout(keyboardName)) {
imeSwitchKey.value = layoutLoader.getLayout(keyboardName).shortLabel;
imeSwitchKey.className += ' alternate-indicator';
}
space.ratio -= 1;
row.splice(c, 0, imeSwitchKey);
c += 1;
}
// Now modify the layout some more based on the input type
var defaultPeriodSymbol = { value: '.', ratio: 1, keyCode: 46 };
if (hasAlternatives(layout, '.')) {
defaultPeriodSymbol['className'] = 'alternate-indicator';
}
if (!layout['typeInsensitive']) {
switch (currentInputType) {
// adds . / and .com
case 'url':
space.ratio -= 2;
row.splice(c, 0, { value: '/', ratio: 1, keyCode: 47 });
row.splice(c + 2, 0, defaultPeriodSymbol);
break;
// adds @ and .
case 'email':
space.ratio -= 2;
row.splice(c, 0, { value: '@', ratio: 1, keyCode: 64 });
row.splice(c + 2, 0, defaultPeriodSymbol);
break;
// adds . and , to both sides of the space bar
case 'text':
var overwrites = layout.textLayoutOverwrite || {};
var next = c;
if (overwrites['.'] !== false) {
space.ratio -= 1;
next++;
}
// Add ',' to 2nd level
if (layoutPage !== LAYOUT_PAGE_DEFAULT || !needsSwitchingKey) {
if (overwrites[','] !== false) {
space.ratio -= 1;
next++;
}
var commaKey = {value: ',', keyCode: 44, ratio: 1};
if (overwrites[',']) {
commaKey.value = overwrites[','];
commaKey.keyCode = overwrites[','].charCodeAt(0);
row.splice(c, 0, commaKey);
} else if (overwrites[','] !== false) {
row.splice(c, 0, commaKey);
}
}
if (overwrites['.']) {
var periodOverwrite = {
value: overwrites['.'],
ratio: 1,
keyCode: overwrites['.'].charCodeAt(0)
};
if (hasAlternatives(layout, overwrites['.'])) {
periodOverwrite['className'] = 'alternate-indicator';
}
row.splice(next, 0, periodOverwrite);
} else if (overwrites['.'] !== false) {
row.splice(next, 0, defaultPeriodSymbol);
}
break;
}
}
} else {
console.warn('No space key found. No special keys will be added.');
}
layout.keyboardName = keyboardName;
layout.altLayoutName = altLayoutName;
return layout;
}
//
// This function asks render.js to create an HTML layout for the keyboard.
// The layout is based on the layout in layout.js, but is augmented by
// modifyLayout() to include keyboard-switching keys and type-specific keys
// for url and email address input, e.g.
//
// This should be called when the keyboard changes or when the layout page
// changes.
//
// Note that calling this function sets the global variable currentLayout.
//
// Also note that currentInputType and layoutPage may both override
// keyboardName to produce a currentLayout that is different than the base
// layout for keyboardName
//
function renderKeyboard(keyboardName) {
perfTimer.printTime('renderKeyboard');
perfTimer.startTimer('renderKeyboard');
// Add meta keys and type-specific keys to the base layout
currentLayout = modifyLayout(keyboardName);
var keyboard = layoutLoader.getLayout(keyboardName);
IMERender.ime.classList.remove('full-candidate-panel');
// Rule of thumb: always render uppercase, unless secondLayout has been
// specified (for e.g. arabic, then depending on shift key)
var needsUpperCase = currentLayout.secondLayout ?
(isUpperCaseLocked || isUpperCase) :
true;
// And draw the layout
IMERender.draw(currentLayout, {
uppercase: needsUpperCase,
inputType: currentInputType,
showCandidatePanel: needsCandidatePanel()
}, function() {
perfTimer.printTime('IMERender.draw:callback');
perfTimer.startTimer('IMERender.draw:callback');
// So there are a couple of things that we want don't want to block
// on here, so we can do it if resizeUI is fully finished
IMERender.setUpperCaseLock(isUpperCaseLocked ? 'locked' : isUpperCase);
// Tell the input method about the new keyboard layout
updateLayoutParams();
IMERender.showCandidates(currentCandidates);
perfTimer.printTime(
'BLOCKING IMERender.draw:callback', 'IMERender.draw:callback');
});
// Tell the renderer what input method we're using. This will set a CSS
// classname that can be used to style the keyboards differently
IMERender.setInputMethodName(keyboard.imEngine || 'default');
// If needed, empty the candidate panel
if (inputMethodManager.currentIMEngine.empty) {
inputMethodManager.currentIMEngine.empty();
}
isKeyboardRendered = true;
perfTimer.printTime('BLOCKING renderKeyboard', 'renderKeyboard');
}
function setUpperCase(upperCase, upperCaseLocked) {
upperCaseLocked = (typeof upperCaseLocked == 'undefined') ?
isUpperCaseLocked : upperCaseLocked;
// Do nothing if the states are not changed
if (isUpperCase == upperCase &&
isUpperCaseLocked == upperCaseLocked)
return;
isUpperCaseLocked = upperCaseLocked;
isUpperCase = upperCase;
if (!isKeyboardRendered)
return;
// When we have secondLayout, we need to force re-render on uppercase switch
if (currentLayout.secondLayout) {
return renderKeyboard(keyboardName);
}
// Otherwise we can just update only the keys we need...
// Try to block the event loop as little as possible
requestAnimationFrame(function() {
perfTimer.startTimer('setUpperCase:requestAnimationFrame:callback');
// And make sure the caps lock key is highlighted correctly
IMERender.setUpperCaseLock(isUpperCaseLocked ? 'locked' : isUpperCase);
//restore the previous candidates
IMERender.showCandidates(currentCandidates);
perfTimer.printTime(
'BLOCKING setUpperCase:requestAnimationFrame:callback',
'setUpperCase:requestAnimationFrame:callback');
});
}
function resetUpperCase() {
if (isUpperCase &&
!isUpperCaseLocked &&
layoutPage === LAYOUT_PAGE_DEFAULT) {
setUpperCase(false);
}
}
function isCapitalized() {
return (isUpperCase || isUpperCaseLocked);
}
function setLayoutPage(newpage) {
if (newpage === layoutPage)
return;
// When layout mode changes we have to re-render the keyboard
layoutPage = newpage;
renderKeyboard(keyboardName);
if (inputMethodManager.currentIMEngine.setLayoutPage) {
inputMethodManager.currentIMEngine.setLayoutPage(layoutPage);
}
}
// Inform about a change in the displayed application via mutation observer
// http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/
function updateTargetWindowHeight(hide) {
perfTimer.printTime('updateTargetWindowHeight');
// height of the current active IME + 1px for the borderTop
var imeHeight = IMERender.getHeight() + 1;
var imeWidth = IMERender.getWidth();
window.resizeTo(imeWidth, imeHeight);
}
// Sends a delete code to remove last character
// The argument specifies whether this is an auto repeat or not.
// We call triggerFeedback() for the initial press, but we
// purposefully do not call it again for auto repeating delete.
function sendDelete(isRepeat) {
// Pass the isRepeat argument to the input method. It may not want
// to compute suggestions, for example, if this is just one in a series
// of repeating events.
inputMethodManager.currentIMEngine.click(KeyboardEvent.DOM_VK_BACK_SPACE,
null,
isRepeat);
}
// Return the upper value for a key object
function getUpperCaseValue(key) {
var hasSpecialCode = specialCodes.indexOf(key.keyCode) > -1;
if (key.keyCode < 0 || hasSpecialCode || key.compositeKey)
return key.value;
var upperCase = currentLayout.upperCase || {};
return upperCase[key.value] || key.value.toUpperCase();
}
function setMenuTimeout(target, coords, touchId) {
// Only set a timeout to show alternatives if there is one touch.
// This avoids paving over menuTimeout with a new timeout id
// from a separate touch.
if (touchCount > 1)
return;
menuTimeout = window.setTimeout(function menuTimeout() {
// Don't try to show the alternatives menu if it's already showing,
// or if there's more than one touch on the screen.
if (isShowingAlternativesMenu || touchCount > 1)
return;
// The telLayout and numberLayout do not show an alternative key
// menu, instead they send the alternative key and ignore the endPress.
if (currentInputType === 'number' || currentInputType === 'tel') {
// Does the key have an altKey?
var r = target.dataset.row, c = target.dataset.column;
var keyChar = currentLayout.keys[r][c].value;
var altKey = currentLayout.alt[keyChar] || null;
if (!altKey)
return;
// Attach a dataset property that will be used to ignore
// keypress in endPress
target.dataset.ignoreEndPress = true;
var keyCode = altKey.charCodeAt(0);
sendKey(keyCode);
return;
}
showAlternatives(target);
// If we successfuly showed the alternatives menu, redirect the
// press over the first key in the menu.
if (isShowingAlternativesMenu)
movePress(target, coords, touchId);
}, ACCENT_CHAR_MENU_TIMEOUT);
}
// Show alternatives for the HTML node key
function showAlternatives(key) {
// Get the key object from layout
var alternatives, altMap, value, keyObj, uppercaseValue, needsCapitalization;
var r = key ? key.dataset.row : -1, c = key ? key.dataset.column : -1;
if (r < 0 || c < 0 || r === undefined || c === undefined)
return;
keyObj = currentLayout.keys[r][c];
// Handle languages alternatives
if (keyObj.keyCode === SWITCH_KEYBOARD) {
showIMEList();
return;
}
// Hide the keyboard
if (keyObj.keyCode === KeyEvent.DOM_VK_SPACE) {
dismissKeyboard();
return;
}
// Handle key alternatives
altMap = currentLayout.alt || {};
value = keyObj.value;
alternatives = altMap[value] || '';
// If in uppercase, look for uppercase alternatives. If we don't find any
// then set a flag so we can manually capitalize the alternatives below.
if (isUpperCase || isUpperCaseLocked) {
uppercaseValue = getUpperCaseValue(keyObj);
if (altMap[uppercaseValue]) {
alternatives = altMap[uppercaseValue];
}
else {
needsCapitalization = true;
}
}
// Split alternatives
// If the alternatives are delimited by spaces, it means that one or more
// of them is more than a single character long.
if (alternatives.indexOf(' ') != -1) {
alternatives = alternatives.split(' ');
// If there is just a single multi-character alternative, it will have
// trailing whitespace which we have to discard here.
if (alternatives.length === 2 && alternatives[1] === '')
alternatives.pop();
if (needsCapitalization) {
for (var i = 0; i < alternatives.length; i++) {
if (isUpperCaseLocked) {
// Caps lock is on, so capitalize all the characters
alternatives[i] = alternatives[i].toLocaleUpperCase();
}
else {
// We're in uppercase, but not locked, so just capitalize 1st char.
alternatives[i] = alternatives[i][0].toLocaleUpperCase() +
alternatives[i].substring(1);
}
}
}
} else {
// No spaces, so all of the alternatives are single characters
if (needsCapitalization) // Capitalize them all at once before splitting
alternatives = alternatives.toLocaleUpperCase();
alternatives = alternatives.split('');
}
if (!alternatives.length)
return;
// Locked limits
// TODO: look for [LOCKED_AREA]
var top = getWindowTop(key);
var bottom = getWindowTop(key) + key.scrollHeight;
var keybounds = key.getBoundingClientRect();
IMERender.showAlternativesCharMenu(key, alternatives);
isShowingAlternativesMenu = true;
// Locked limits
// TODO: look for [LOCKED_AREA]
menuLockedArea = {
top: top,
bottom: bottom,
left: getWindowLeft(IMERender.menu),
right: getWindowLeft(IMERender.menu) + IMERender.menu.scrollWidth
};
menuLockedArea.width = menuLockedArea.right - menuLockedArea.left;
// Add some more properties to this locked area object that will help us
// redirect touch events to the appropriate alternative key.
menuLockedArea.keybounds = keybounds;
menuLockedArea.firstAlternative =
IMERender.menu.classList.contains('kbr-menu-left') ?
IMERender.menu.lastElementChild :
IMERender.menu.firstElementChild;
menuLockedArea.boxes = [];
var children = IMERender.menu.children;
for (var i = 0; i < children.length; i++) {
menuLockedArea.boxes[i] = children[i].getBoundingClientRect();
}
}
// Hide alternatives.
function hideAlternatives() {
if (!isShowingAlternativesMenu)
return;
IMERender.hideAlternativesCharMenu();
isShowingAlternativesMenu = false;
}
// Test if an HTML node is a normal key
function isNormalKey(key) {
var keyCode = parseInt(key.dataset.keycode);
return keyCode || key.dataset.selection || key.dataset.compositeKey;
}
//
// Event Handlers
//
function onTouchStart(evt) {
// Prevent a mouse event from firing (this doesn't currently work
// because of bug 819102)
if (!IMERender.isFullCandidataPanelShown())
evt.preventDefault();
// Let the world know that we're using touch events.
touchEventsPresent = true;
// Don't allow new touches if the alternatives menu is showing.
if (isShowingAlternativesMenu)
return;
touchCount = evt.touches.length;
handleTouches(evt, function handleTouchStart(touch, touchId) {
var target = touch.target;
// Add touchmove and touchend listeners directly to the target so that we
// will always hear these events, even if the target is removed from the
// DOM.
// This can happen when the keyboard switches cases, as well as when we
// show the alternate characters menu for a key.
target.addEventListener('touchmove', onTouchMove);
target.addEventListener('touchend', onTouchEnd);
target.addEventListener('touchcancel', onTouchEnd);
touchedKeys[touchId] = { target: target, x: touch.pageX, y: touch.pageY };
startPress(target, touch, touchId);
touchStartCoordinate = { touchId: touchId,
pageX: touch.pageX,
pageY: touch.pageY,
timeStamp: evt.timeStamp };
});
}