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
2048 lines (1739 loc) · 62.3 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: */
/*
* 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
*
* Input methods are in subdirectories of imes/. The latin input method
* in imes/latin/ provides word suggestions, auto capitalization, and
* punctuation assistance.
*
* Each input method implements the following interface which the keyboard
* uses to communicate with it. init() and click() are the only two required
* methods; the keyboard checks that other methods are defined before
* invoking them:
*
* init(keyboard)
* keyboard is the object that the IM uses to communicate with the keyboard
*
* activate(language, suggestionsEnabled, inputstate)
* the keyboard calls this method when it becomes active.
* language is the current language. suggestionsEnabled
* specifies whether the user wants word suggestions inputstate
* is an object that holds the state of the input field or
* textarea being typed into. it includes content, cursor
* position and type and inputmode attributes.
*
* deactivate()
* called when the keyboard is hidden.
*
* empty:
* clear any currently displayed candidates/suggestions.
* The latin input method does not use this, and it is not clear
* to me whether the Asian IMs need it either.
*
* click(keycode, x, y):
* This is the main method: the keyboard calls this each time the
* user taps a key. The keyboard does not actually generate any
* key events until the input method tells it to. The x and y coordinate
* arguments can be used to improve the IM's word suggestions, in
* conjunction with the layout data from setLayoutParams().
* The coordinates aren't passed for the Backspace key, however.
*
* select(word, data):
* Called when the user selects a displayed candidate or word suggestion.
*
* setLayoutParams(params):
* Gives the IM information about the onscreen coordinates of
* each key. Used with latin IM only. Can be used with click
* coordinates to improve predictions, but it may not currently
* be used.
*
* getMoreCandidates(indicator, maxCount, callback):
* (optional) Called when the render needs more candidates to show on the
* candidate panel.
*
* The init method of each IM is passed an object that it uses to
* communicate with the keyboard. That interface object defines the following
* properties and methods:
*
* path:
* a url that the IM can use to load dictionaries or other resources
*
* sendCandidates:
* A method that makes the keyboard display candidates or suggestions
*
* sendPendingSymbols:
* like sendCandidates, but used by Asian IMs.
*
* sendKey(keycode):
* Generate output. Typically the keyboard will just pass this
* keycode to inputcontext.sendKey(). The IM could call
* inputcontext.sendKey() directly, but doing it this way allows
* us to chain IMs, I think.
*
* sendString:
* Outputs a string of text by repeated calls to sendKey().
*
* alterKeyboard(layout): allows the IM to modify the keyboard layout
* by specifying a new layout name. Only used by asian ims currently.
*
* setLayoutPage(): allows the IM to switch between default and symbol
* layouts on the keyboard. Used by the latin IM.
*
* setUpperCase(upperCase, upperCaseLocked): allows the IM to switch between
* uppercase and lowercase layout on the keyboard. Used by the latin IM.
* - upperCase: to enable the upper case or not.
* - upperCaseLocked: to change the caps lock state.
*
* resetUpperCase(): allows the IM to reset the upperCase to lowerCase
* without knowing the internal states like caps lock and current layout
* page while keeping setUpperCase simple as it is.
*
* getNumberOfCandidatesPerRow(): allow the IM to know how many candidates
* the Render need in one row so that IM can reduce search time and run the
* remaining process when "getMoreCandidates" is called.
*
*/
'use strict';
// InputMethod modules register themselves in this object
const InputMethods = {};
// The default input method is trivial: when the keyboard passes a key
// to it, it just sends that key right back. Real input methods implement
// a number of other methods
const defaultInputMethod = {
click: sendKey,
displaysCandidates: function() { return false; }
};
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 setKeyboardName(). That function sets the
// following variables based on its argument. See layout.js for a the data
// structure that maps keyboard names to their layout data.
//
// Note that keyboardName is the name of the currently displayed keyboard.
// currentKeyboardName tracks the value of the keyboard.current setting.
// We don't call setKeyboardName() when keyboard.current changes because
// that causes problems with the async loading of input methods and could
// also cause races if keyboard.current is updated before the enabled keyboards
// settings are updated. Instead, every time we show the keyboard we ensure
// that keyboardName matches currentKeyboardName and call setKeyboardName to
// update it if necessary.
var keyboardName = null;
var inputMethod = defaultInputMethod;
// 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 layoutMenuLockedArea = null;
var isKeyboardRendered = false;
var currentCandidates = [];
var candidatePanelScrollTimer = null;
const CANDIDATE_PANEL_SWITCH_TIMEOUT = 100;
// 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;
// timeout and interval for delete, they could be cancelled on mouse over
var deleteTimeout = 0;
var deleteInterval = 0;
var menuTimeout = 0;
var redrawTimeout = 0;
// This object has one property for each keyboard layout setting.
// If the user turns on that setting in the settings app, the value of
// the property specifies the keyboard layouts that are enabled.
const keyboardGroups = {
'english': ['en'],
'dvorak': ['en-Dvorak'],
'spanish' : ['es'],
'portuguese' : ['pt_BR'],
'polish' : ['pl'],
'catalan' : ['ca'],
'czech': ['cz'],
'french': ['fr'],
'german': ['de'],
'hungarian': ['hu'],
'norwegian': ['nb'],
'swedish': ['sv'],
'slovak': ['sk'],
'turkish': ['tr-Q', 'tr-F'],
'romanian': ['ro'],
'russian': ['ru'],
'serbian': ['sr-Latn', 'sr-Cyrl'],
'hebrew': ['he'],
'zhuyin': ['zh-Hant-Zhuyin'],
'pinyin': ['zh-Hans-Pinyin'],
'arabic': ['ar'],
'greek': ['el'],
'japanese': ['jp-kanji']
};
// Define language code aliases to correctly match the relevant keyboard,
// i.e. language -> relevant keyboard name
const keyboardAlias = {
'en-US': 'en',
'pt-BR': 'pt_BR'
};
// This is the default keyboard if none is selected in settings
// XXX: switch this to pt-BR?
// XXX: ideally, this should be based on the current language,
const defaultKeyboardNames = ['en'];
const keyboardHashKey = [
'en', 'en-Dvorak', 'es', 'pt-BR', 'pl',
'cz', 'fr', 'de', 'nb', 'sk',
'tr', 'ru', 'sr-Cyrl', 'ar', 'he',
'el',
'zh-Hant-Zhuyin', 'zh-Hans-Pinyin', 'jp-kanji',
'numberLayout'
];
// If we get a focuschange event from mozKeyboard for an element with
// one of these types, we'll just ignore it.
const ignoredFormElementTypes = {
'select-one': true,
'select-multiple': true,
'date': true,
'time': true,
'datetime': true,
'datetime-local': true
};
// Special key codes
const BASIC_LAYOUT = -1;
const ALTERNATE_LAYOUT = -2;
const SWITCH_KEYBOARD = -3;
const TOGGLE_CANDIDATE_PANEL = -4;
const specialCodes = [
KeyEvent.DOM_VK_BACK_SPACE,
KeyEvent.DOM_VK_CAPS_LOCK,
KeyEvent.DOM_VK_RETURN,
KeyEvent.DOM_VK_ALT,
KeyEvent.DOM_VK_SPACE
];
// These values are initialized with user settings
var currentKeyboardName;
var suggestionsEnabled;
var correctionsEnabled;
var clickEnabled;
var vibrationEnabled;
var enabledKeyboardGroups = {};
var enabledKeyboardNames;
var isSoundEnabled;
// 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 "swipe down to hide" feature
var touchStartCoordinate;
var toShowKeyboardFTU = false;
const SWIPE_VELOCICTY_THRESHOLD = 0.4;
// The first thing we do when the keyboard app loads is query all the
// keyboard-related settings. Only once we have the current settings values
// do we initialize the rest of the keyboard
window.addEventListener('load', getKeyboardSettings);
function getKeyboardSettings() {
// Before we can initialize the keyboard we need to know the current
// value of all keyboard-related settings. These are the settings
// we want to query, with the default values we'll use if the query fails
var settingsQuery = {
'keyboard.current': 'en',
'keyboard.wordsuggestion': true,
'keyboard.autocorrect': true,
'keyboard.vibration': false,
'keyboard.clicksound': false,
'keyboard.ftu.enabled': false,
'audio.volume.notification': 7
};
// Now query the settings
getSettings(settingsQuery, function gotSettings(values) {
// Copy settings values to the corresponding global variables.
currentKeyboardName = values['keyboard.current'];
suggestionsEnabled = values['keyboard.wordsuggestion'];
correctionsEnabled = values['keyboard.autocorrect'];
vibrationEnabled = values['keyboard.vibration'];
clickEnabled = values['keyboard.clicksound'];
isSoundEnabled = !!values['audio.volume.notification'];
// To see if this is first time the user launches the keyboard
toShowKeyboardFTU = values['keyboard.ftu.enabled'];
handleKeyboardSound();
// set default input method with hash value
if (window.location.hash !== '') {
var hashKey = window.location.hash.substring(1);
if (keyboardHashKey.indexOf(hashKey) !== -1) {
keyboardName = hashKey;
} else {
keyboardName = defaultKeyboardName;
}
} else {
keyboardName = defaultKeyboardName;
}
// And create an array of all enabled keyboard layouts from the set
// of enabled groups
handleNewKeyboards();
// We've got all the settings, so initialize the rest
initKeyboard();
});
}
function initKeyboard() {
// First, register handlers to track settings changes
navigator.mozSettings.addObserver('keyboard.current', function(e) {
// Switch to the language associated keyboard
// everything.me also uses this setting to improve searches
currentKeyboardName = e.settingValue;
});
navigator.mozSettings.addObserver('keyboard.wordsuggestion', function(e) {
// The keyboard won't be displayed when this setting changes, so we
// don't need to tell the keyboard about the new value right away.
// We pass the value to the input method when the keyboard is displayed
suggestionsEnabled = e.settingValue;
});
navigator.mozSettings.addObserver('keyboard.autocorrect', function(e) {
// The keyboard won't be displayed when this setting changes, so we
// don't need to tell the keyboard about the new value right away.
// We pass the value to the input method when the keyboard is displayed
correctionsEnabled = e.settingValue;
});
navigator.mozSettings.addObserver('keyboard.vibration', function(e) {
vibrationEnabled = e.settingValue;
});
navigator.mozSettings.addObserver('audio.volume.notification', function(e) {
isSoundEnabled = !!e.settingValue;
handleKeyboardSound();
});
navigator.mozSettings.addObserver('keyboard.clicksound', function(e) {
clickEnabled = e.settingValue;
handleKeyboardSound();
});
// Gaia UI Test may change this setting to disable keyboard FTU
navigator.mozSettings.addObserver('keyboard.ftu.enabled', function(e) {
toShowKeyboardFTU = e.settingValue;
});
// 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]);
}
// Prevent focus being taken away by tip window
var tipWindow = document.getElementById('confirm-dialog');
function tipFocusHandler(evt) {
evt.preventDefault();
}
tipWindow.addEventListener('mousedown', tipFocusHandler);
var tipButton = document.getElementById('ftu-ok');
tipButton.addEventListener('click', function(evt) {
// Need to preventDefault or it will make the input lose the focus
evt.preventDefault();
tipWindow.hidden = true;
});
/* To simulate :active effect for button */
tipButton.addEventListener('mousedown', function mouseDownHandler(evt) {
tipButton.classList.add('active');
});
var inActiveHandlers = ['mouseup', 'mouseleave'];
inActiveHandlers.forEach(function addInActiveHandler(evtName) {
tipButton.addEventListener(evtName, function inActiveHandler(evt) {
tipButton.classList.remove('active');
});
});
dimensionsObserver = new MutationObserver(function() {
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', 'data-hidden']
});
window.addEventListener('hashchange', function() {
var inputMethodName = window.location.hash.substring(1);
setKeyboardName(inputMethodName, function() {
resetKeyboard();
showKeyboard();
});
}, false);
// Handle resize events
window.addEventListener('resize', onResize);
// 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() {
var inputMethodName = window.location.hash.substring(1);
setKeyboardName(inputMethodName, function() {
if (!document.mozHidden && inputContext) {
showKeyboard();
} else {
hideKeyboard();
}
});
});
window.navigator.mozInputMethod.oninputcontextchange = function() {
inputContext = navigator.mozInputMethod.inputcontext;
if (!document.mozHidden && inputContext) {
showKeyboard();
} else {
hideKeyboard();
}
};
}
function handleKeyboardSound() {
if (clickEnabled && isSoundEnabled) {
clicker = new Audio(CLICK_SOUND);
specialClicker = new Audio(SPECIAL_SOUND);
} else {
clicker = null;
specialClicker = null;
}
}
function setKeyboardName(name, callback) {
var keyboard;
if (name in Keyboards) {
keyboard = Keyboards[name];
keyboardName = name;
}
else {
var alias = keyboardAlias[name];
if (alias in Keyboards) {
keyboard = Keyboards[alias];
keyboardName = alias;
}
else {
console.warn('Unknown keyboard name', name);
return;
}
}
if (inputMethod.deactivate)
inputMethod.deactivate();
if (keyboard.imEngine) {
loadIMEngine(name, function() {
inputMethod = InputMethods[keyboard.imEngine];
callback();
});
} else {
inputMethod = defaultInputMethod;
callback();
}
}
// 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;
}
// This code is only triggered on startup and when the user is in the
// Settings app. So no keyboard is displayed when it happens and we don't
// have to change anything on the screen.
function handleNewKeyboards() {
enabledKeyboardNames = [];
for (var group in keyboardGroups) {
if (enabledKeyboardGroups['keyboard.layouts.' + group]) {
keyboardGroups[group].forEach(function(name) {
if (enabledKeyboardNames.indexOf(name) === -1)
enabledKeyboardNames.push(name);
});
}
}
// If no keyboards were selected, use a default
if (enabledKeyboardNames.length === 0)
Array.prototype.push.apply(enabledKeyboardNames,
defaultKeyboardNames);
// Now load each of these keyboards and their input methods
for (var i = 0; i < enabledKeyboardNames.length; i++)
loadKeyboard(enabledKeyboardNames[i]);
// If the keyboard has been disabled, reset keyboardName allowing it to be
// properly set when showing the keyboard
if (enabledKeyboardNames.indexOf(keyboardName) == -1)
keyboardName = null;
}
// 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;
}
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';
}
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 = Keyboards[keyboardName][altLayoutName] || Keyboards[altLayoutName];
}
else {
layout = Keyboards[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 = '?123';
if (layout['alternateLayoutKey']) {
alternateLayoutKey = layout['alternateLayoutKey'];
}
// This gives the author the ability to change the basic layout
// key contents
var basicLayoutKey = 'ABC';
if (layout['basicLayoutKey']) {
basicLayoutKey = layout['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
});
} else {
row.splice(c, 0, {
keyCode: BASIC_LAYOUT,
value: basicLayoutKey,
ratio: 1.5
});
}
c += 1;
}
// switch languages button
var supportsSwitching = navigator.mozInputMethod.mgmt.supportsSwitching();
if (!layout['hidesSwitchKey'] && supportsSwitching) {
space.ratio -= 1.5;
row.splice(c, 0, {
value: '🌐',
ratio: 1.5,
keyCode: SWITCH_KEYBOARD
});
c += 1;
}
// Now modify the layout some more based on the input type
if (!layout['typeInsensitive']) {
switch (currentInputType) {
// adds . / and .com
case 'url':
space.ratio -= 5;
row.splice(c, 1, // delete space
{ value: '.', ratio: 1, keyCode: 46 },
{ value: '/', ratio: 2, keyCode: 47 },
// As we are removing the space we need to assign
// the extra space (i.e to .com)
{ value: '.com',
ratio: 2 + space.ratio,
compositeKey: '.com'
}
);
break;
// adds @ and .
case 'email':
space.ratio -= 2;
row.splice(c, 0, { value: '@', ratio: 1, keyCode: 64 });
row.splice(c + 2, 0, { value: '.', ratio: 1, keyCode: 46 });
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) {
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['.']) {
row.splice(next, 0, {
value: overwrites['.'],
ratio: 1,
keyCode: overwrites['.'].charCodeAt(0)
});
} else if (overwrites['.'] !== false) {
row.splice(next, 0, {
value: '.',
ratio: 1,
keyCode: 46
});
}
break;
}
}
} else {
console.warn('No space key found. No special keys will be added.');
}
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) {
// Add meta keys and type-specific keys to the base layout
currentLayout = modifyLayout(keyboardName);
function drawKeyboard() {
// Tell the renderer what input method we're using. This will set a CSS
// classname that can be used to style the keyboards differently
var keyboard = Keyboards[keyboardName];
IMERender.setInputMethodName(keyboard.imEngine || 'default');
IMERender.ime.classList.remove('full-candidate-panel');
// And draw the layout
IMERender.draw(currentLayout, {
uppercase: isUpperCaseLocked || isUpperCase,
inputType: currentInputType,
showCandidatePanel: needsCandidatePanel()
});
IMERender.setUpperCaseLock(isUpperCaseLocked ? 'locked' : isUpperCase);
// If needed, empty the candidate panel
if (inputMethod.empty)
inputMethod.empty();
// Tell the input method about the new keyboard layout
updateLayoutParams();
//restore the previous candidates
IMERender.showCandidates(currentCandidates);
isKeyboardRendered = true;
}
clearTimeout(redrawTimeout);
// Does this new keyboard use the candidate panel?
var showsCandidates = needsCandidatePanel();
// If it doesn't and the keyboard has be shown, then notify the keyboard
// manager update the app window size before redrawing the keyboard.
// XXX: for Bug 893755 - we would always do the delay of keyboard redrawing
// without regard to whether candidate panel was enabled or not last time.
if (!showsCandidates && isKeyboardRendered) {
var candidatePanel = document.getElementById('keyboard-candidate-panel');
var candidatePanelHeight = (candidatePanel) ?
candidatePanel.scrollHeight : 0;
var imeHeight = IMERender.ime.scrollHeight - candidatePanelHeight;
var imeWidth = IMERender.getWidth();
window.resizeTo(imeWidth, imeHeight);
redrawTimeout = window.setTimeout(drawKeyboard,
CANDIDATE_PANEL_SWITCH_TIMEOUT);
} else {
drawKeyboard();
}
// Remember whether the candidate panel is shown or not
}
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 case changes we have to re-render the keyboard.
// But note that we don't have to relayout the keyboard, so
// we call draw() directly instead of renderKeyboard()
IMERender.draw(currentLayout, {
uppercase: isUpperCaseLocked || isUpperCase,
inputType: currentInputType,
showCandidatePanel: needsCandidatePanel()
});
// And make sure the caps lock key is highlighted correctly
IMERender.setUpperCaseLock(isUpperCaseLocked ? 'locked' : isUpperCase);
//restore the previous candidates
IMERender.showCandidates(currentCandidates);
}
function resetUpperCase() {
if (isUpperCase &&
!isUpperCaseLocked &&
layoutPage === LAYOUT_PAGE_DEFAULT) {
setUpperCase(false);
}
}
function setLayoutPage(newpage) {
if (newpage === layoutPage)
return;
// When layout mode changes we have to re-render the keyboard
layoutPage = newpage;
renderKeyboard(keyboardName);
if (inputMethod.setLayoutPage)
inputMethod.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) {
var imeHeight = IMERender.ime.scrollHeight;
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.
inputMethod.click(KeyboardEvent.DOM_VK_BACK_SPACE, 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);