-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
kmwkeyboards.ts
1770 lines (1520 loc) · 62.5 KB
/
kmwkeyboards.ts
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
/// <reference path="../kmwbase.ts" />
namespace com.keyman.keyboards {
class CloudRequestEntry {
id: string;
language?: string;
version?: string;
constructor(id: string, language?: string) {
this.id = id;
this.language = language;
}
toString(): string {
var kbid=this.id;
var lgid='';
var kvid='';
if(this.language) {
kbid=kbid+'@'+this.language;
if(this.version) {
kbid=kbid+'@'+this.version;
}
} else {
if(this.version) {
kbid=kbid+'@@'+this.version;
}
}
//TODO: add specifier validation...
return kbid;
}
}
class KeyboardFont {
'family': string;
'files': string;
'path': string;
constructor(fontObj: any, fontPath: string) {
this['family'] = fontObj['family'];
this['files'] = fontObj['source'];
this['path'] = fontPath;
}
}
export class KeyboardStub {
'KI': string;
'KLC': string;
'KN': string;
'KL': string;
'KR': string;
'KRC': string;
'KF': string;
'KFont': KeyboardFont;
'KOskFont': KeyboardFont;
'displayName': string; // Display name as shown on spacebar
// Used when loading a stub's keyboard.
asyncLoader?: any;
constructor(id: string, langCode: string) {
this['KI'] = 'Keyboard_' + id;
this['KLC'] = langCode;
}
/**
* Utility to convert stubs to KeyboardStub[]
* @param arg
* @returns (KeyboardStub|ErrorStub)[]
*/
public static toStubs(arg: any): (KeyboardStub|ErrorStub)[] {
let errorMsg: string = '';
if (!arg) {
errorMsg = "Stub undefined";
} else if (!arg.id) {
errorMsg = "KeyboardStub has undefined id";
} else if (!arg.languages) {
errorMsg = "KeyboardStub has undefined languages"
}
if (errorMsg != '') {
return [{error: new Error(errorMsg)}];
}
// Extract all the languages
let languages: any[] = [];
if (typeof arg.languages === 'object') {
languages.push(arg.languages);
} else {
arg.languages.foreach(language => {
languages.push(language);
});
}
let stubs: KeyboardStub[] = [];
languages.forEach(language => {
let stub: KeyboardStub = new KeyboardStub(arg.id, language.id);
if (arg.name) {
stub['KN'] = arg.name
}
if (arg.filename) {
stub['KF'] = arg.filename;
}
if (arg.displayName) {
stub['displayName'] = arg.displayName;
}
if (language.name) {
stub['KL'] = language.name;
}
if (language.region) {
stub['KR'] = language.region;
}
// Can ignore ['KRC'] RegionCodes used by the Toolbar UI
if (language.font) {
stub['KFont'] = language.font;
}
if (language.oskFont) {
stub['KOskFont'] = language.oskFont;
}
stubs.push(stub);
})
return stubs;
}
}
// Information about a keyboard that fails to get added
export interface ErrorStub {
keyboard?: {
id: string;
name: string;
},
language?: {
id?: string;
name?: string;
}
error: Error;
}
export class KeyboardTag {
stores: {[text: string]: text.ComplexKeyboardStore} = {};
}
export interface KeyboardChangeData {
['internalName']: string;
['languageCode']: string;
['indirect']: boolean;
}
// For when the API call straight-up times out.
const CLOUD_TIMEOUT_ERR = "The Cloud API request timed out.";
// Currently cannot distinguish between "no matching keyboard" and other script-load errors.
const CLOUD_MALFORMED_OBJECT_ERR = "Could not find a keyboard with that ID.";
// Represents unspecified errors that occur when registering the results of a successful API call.
const CLOUD_STUB_REGISTRATION_ERR = "The Cloud API failed to find an appropriate keyboard.";
// Represents custom, specified KMW errors that occur when registering the results of a successful API call.
const CLOUD_REGISTRATION_ERR = "Error occurred while registering keyboards: ";
const MISSING_KEYBOARD = function(kbdid: string) {
return kbdid + ' keyboard not found.';
}
interface RegistrationPromiseTuple {
resolve: (stubs: KeyboardStub[]) => void;
reject: (err: Error) => void;
}
export class KeyboardManager {
// Language regions as defined by cloud server
static readonly regions = ['World','Africa','Asia','Europe','South America','North America','Oceania','Central America','Middle East'];
static readonly regionCodes = ['un','af','as','eu','sa','na','oc','ca','me'];
keymanweb: KeymanBase;
activeStub: KeyboardStub = null;
keyboardStubs: KeyboardStub[] = [];
// For deferment of adding keyboards until keymanweb initializes
deferment: Promise<void> = null;
endDeferment:() => void;
// The following was not actually utilized within KeymanWeb; I think it's handled via different logic.
// See setDefaultKeyboard() below.
dfltStub = null; // First keyboard stub loaded - default for touch-screen devices, ignored on desktops
keyboards: any[] = [];
/**
* Holds the 'resolve' function for Promises built by keymanCloudRequest.
* These should be cleared when the Promise is fulfilled.
*/
registrationResolvers: {[timeoutID: number] : RegistrationPromiseTuple} = {};
languageListPromise: Promise<(KeyboardStub|ErrorStub)[]> = null;
languageList: any[] = null; // List of keyboard languages available for KeymanCloud
linkedScripts: HTMLScriptElement[] = [];
constructor(kmw: KeymanBase) {
this.keymanweb = kmw;
let _this = this;
this.deferment = new Promise(function(resolve) {
_this.endDeferment = resolve;
});
}
getActiveKeyboardName(): string {
let core = com.keyman.singleton.core;
return core.activeKeyboard ? core.activeKeyboard.id : '';
}
getActiveLanguage(fullName?: boolean): string {
if(this.activeStub == null) {
return '';
} else if(fullName) {
return this.activeStub['KL'];
} else {
return this.activeStub['KLC'];
}
}
/**
* Get an associative array of keyboard identification strings
* This was defined as an array, so is kept that way, but
* Javascript treats it as an object anyway
*
* @param {Object} Lstub Keyboard stub object
* @param {Object} Lkbd Keyboard script object
* @return {Object} Copy of keyboard identification strings
*
*/
private _GetKeyboardDetail = function(Lstub: KeyboardStub, Lkbd: any /* KeyboardScriptObject */) { // I2078 - Full keyboard detail
var Lr={};
Lr['Name'] = Lstub['KN'];
Lr['InternalName'] = Lstub['KI'];
Lr['LanguageName'] = Lstub['KL']; // I1300 - Add support for language names
Lr['LanguageCode'] = Lstub['KLC']; // I1702 - Add support for language codes, region names, region codes, country names and country codes
Lr['RegionName'] = Lstub['KR'];
Lr['RegionCode'] = Lstub['KRC'];
Lr['CountryName'] = Lstub['KC'];
Lr['CountryCode'] = Lstub['KCC'];
Lr['KeyboardID'] = Lstub['KD'];
Lr['Font'] = Lstub['KFont'];
Lr['OskFont'] = Lstub['KOskFont'];
Lr['HasLoaded'] = !!Lkbd;
Lr['IsRTL'] = Lkbd ? !!Lkbd['KRTL'] : null;
return Lr;
}
/**
* Get array of available keyboard stubs
*
* @return {Array} Array of available keyboards
*
*/
getDetailedKeyboards() {
var Lr = [], Ln, Lstub, Lrn;
for(Ln=0; Ln < this.keyboardStubs.length; Ln++) { // I1511 - array prototype extended
Lstub = this.keyboardStubs[Ln];
// In Chrome, (including on Android), Array.prototype.find() requires Chrome 45.
// This is a later version than the default on our oldest-supported Android devices.
const Lkbd = this.keyboards.find(k => k['KI'] == Lstub['KI']);
Lrn = this._GetKeyboardDetail(Lstub, Lkbd); // I2078 - Full keyboard detail
Lr=this.keymanweb._push(Lr,Lrn); // TODO: Resolve without need for the cast.
}
return Lr;
}
/**
* Register a fully specified keyboard (add meta-data for each language) immediately
*
* @param {Object} arg
* @returns {boolean}
**/
addStub(arg: any): boolean {
if(typeof(arg['id']) != 'string') {
return false;
}
if(typeof(arg['language']) != "undefined") {
console.warn("The 'language' property for keyboard stubs has been deprecated. Please use the 'languages' property instead.");
arg['languages'] = arg['language'];
}
if(typeof(arg['languages']) == 'undefined') {
return false;
}
// Default the keyboard name to its id, capitalized
if(typeof(arg['name']) != 'string') {
arg['name'] = arg['id'].replace('_',' ');
arg['name'] = arg['name'].substr(0,1).toUpperCase()+arg['name'].substr(1);
}
var lgArg=arg['languages'];
var lgList=[], i, lg;
if(typeof(lgArg.length) == 'undefined') {
lgList[0] = lgArg;
} else {
lgList = lgArg;
}
var localOptions={
'keyboardBaseUri': this.keymanweb.options['keyboards'],
'fontBaseUri': this.keymanweb.options['fonts']
};
// Add a stub for each correctly specified language
for(i=0; i<lgList.length; i++) {
this.mergeStub(arg, lgList[i], localOptions);
}
return true;
}
/**
* Create or update a keyboard meta-data 'stub' during keyboard registration
*
* Cross-reference with https://help.keyman.com/developer/engine/web/11.0/reference/core/addKeyboards.
*
* @param {Object} kp (partial) keyboard meta-data object (`spec` object)
* @param {Object} lp language object (`spec.languages` object)
* @param {Object} options KeymanCloud callback options
**/
mergeStub(kp: any, lp: any, options) {
var sp: KeyboardStub = this.findStub(kp['id'], lp['id']);
var isNew: boolean = false;
if(sp == null) {
sp= new KeyboardStub(kp['id'], lp['id']);
this.keyboardStubs.push(sp);
isNew = true;
}
// Accept region as number (from Cloud server), code, or name
var region=lp['region'], rIndex=0;
if(typeof(region) == 'number') {
if(region < 1 || region > 9) {
rIndex = 0;
} else {
rIndex = region-1;
}
} else if(typeof(region) == 'string') {
var list = (region.length == 2 ? KeyboardManager.regionCodes : KeyboardManager.regions);
for(var i=0; i<list.length; i++) {
if(region.toLowerCase() == list[i].toLowerCase()) {
rIndex=i;
break;
}
}
}
var rx: RegExp;
sp['KL'] = (typeof sp['KL'] === 'undefined') ? lp['name'] : sp['KL'];
sp['KR'] = (typeof sp['KR'] === 'undefined') ? KeyboardManager.regions[rIndex] : sp['KR'];
sp['KRC'] = (typeof sp['KRC'] === 'undefined') ? KeyboardManager.regionCodes[rIndex] : sp['KRC'];
sp['KN'] = (typeof sp['KN'] === 'undefined') ? kp['name'] : sp['KN'];
sp['displayName'] = (typeof sp['displayName'] === 'undefined') ? kp['displayName'] : sp['displayName'];
if(typeof(sp['KF']) == 'undefined') {
rx=RegExp('^(([\\.]/)|([\\.][\\.]/)|(/))|(:)');
sp['KF'] = kp['filename'];
if(!rx.test(sp['KF'])) {
sp['KF'] = options['keyboardBaseUri']+sp['KF'];
}
}
// Font path defined by cloud entry
var fontPath=options['fontBaseUri'];
// or overridden locally, in page source
if(this.keymanweb.options['fonts'] != '') {
fontPath=this.keymanweb.options['fonts'];
rx=new RegExp('^https?\\:');
if(!rx.test(fontPath)) {
if(fontPath.substr(0,2) == '//') {
fontPath = this.keymanweb.protocol + fontPath;
} else if(fontPath.substr(0,1) == '/') {
fontPath = this.keymanweb.rootPath + fontPath.substr(1);
} else {
fontPath = this.keymanweb.rootPath + fontPath;
}
}
}
else {
this.keymanweb.options.fonts=fontPath;
}
// Add font specifiers where necessary and not overridden by user
if(typeof(lp['font']) != 'undefined') {
sp['KFont'] = (typeof sp['KFont'] === 'undefined') ? new KeyboardFont(lp['font'], fontPath) : sp['KFont'];
}
// Fixed OSK font issue Github #7 (9/1/2015)
if(typeof(lp['oskFont']) != 'undefined') {
sp['KOskFont'] = (typeof sp['KOskFont'] === 'undefined') ? new KeyboardFont(lp['oskFont'], fontPath) : sp['KOskFont'];
}
// Update the UI
this.doKeyboardRegistered(sp['KI'],sp['KL'],sp['KN'],sp['KLC'],sp['KP']);
// If we have no activeStub because there were no stubs, set the new keyboard as active.
// Do not trigger on merges.
if(!this.activeStub && isNew && this.keyboardStubs.length == 1 && this.keymanweb.options['setActiveOnRegister']=='true') {
// #676: We call _SetActiveKeyboard so we can avoid overwriting
// cookies that determine our active keyboard at page load time
this.doBeforeKeyboardChange(sp['KI'], sp['KLC']);
this._SetActiveKeyboard(sp['KI'], sp['KLC'], false);
this.doKeyboardChange(sp['KI'], sp['KLC']);
}
}
/**
* Find a keyboard stub by id in the registered keyboards list
*
* @param {string} kid internal keyboard id (without 'Keyboard_' prefix)
* @param {string} lgid language code
*
**/
findStub(kid: string, lgid: string): KeyboardStub {
var i;
for(i=0; i<this.keyboardStubs.length; i++) {
if((this.keyboardStubs[i]['KI'] == 'Keyboard_'+kid) && (this.keyboardStubs[i]['KLC'] == lgid)) {
return this.keyboardStubs[i];
}
}
return null;
}
// Called on the embedded path at the end of its initialization.
setDefaultKeyboard() {
if(this.keyboardStubs.length > 0) {
// Select the first stub as our active keyboard.
this._SetActiveKeyboard(this.keyboardStubs[0]['KI'], this.keyboardStubs[0]['KLC']);
return true;
} else {
return false;
}
}
/**
* Allow to change active keyboard by (internal) keyboard name
*
* @param {string} PInternalName Internal name
* @param {string} PLgCode Language code
*/
setActiveKeyboard(PInternalName: string, PLgCode: string): Promise<void> {
//TODO: This does not make sense: the callbacks should be in _SetActiveKeyboard, not here,
// since this is always called FROM the UI, which should not need notification.
// If UI callbacks are needed at all, they should be within _SetActiveKeyboard
// Skip on embedded which namespaces packageID::Keyboard_keyboardID
if(!this.keymanweb.isEmbedded && PInternalName && PInternalName.indexOf("Keyboard_") != 0) {
PInternalName = "Keyboard_" + PInternalName;
}
this.doBeforeKeyboardChange(PInternalName,PLgCode);
let p: Promise<void> = this._SetActiveKeyboard(PInternalName,PLgCode,true);
if(this.keymanweb.domManager.lastActiveElement != null) {
this.keymanweb.domManager.focusLastActiveElement(); // TODO: Resolve without need for the cast.
}
// If we ever allow PLgCode to be set by default, we can auto-detect the language code
// after the _SetActiveKeyboard call.
// if(!PLgCode && (<KeymanBase>keymanweb).keyboardManager.activeStub) {
// PLgCode = (<KeymanBase>keymanweb).keyboardManager.activeStub['KLC'];
// }
const _this = this;
p.then(function() {
// Only mark the keyboard as having changed once the setActiveKeyboard op
// is successful.
_this.doKeyboardChange(PInternalName, PLgCode);
});
p.catch(error => {
// Rejection indicates a failure of the keyboard to load.
//
// In case p's rejection is never caught, throwing this error will generate logs that shows up
// in Sentry or in the console, with useful information for debugging either way.
throw new Error("Unable to load keyboard with internal name \"" + PInternalName + "\", language code \"" + PLgCode + "\": " + error);
});
return p;
}
/**
* Change active keyboard to keyboard selected by (internal) name and language code
*
* Test if selected keyboard already loaded, and simply update active stub if so.
* Otherwise, insert a script to download and insert the keyboard from the repository
* or user-indicated file location.
*
* Note that the test-case oriented 'recorder' stubs this method to provide active
* keyboard stub information. If changing this function, please ensure the recorder is
* not affected.
*
* @param {string} PInternalName
* @param {string=} PLgCode
* @param {boolean=} saveCookie
*/
_SetActiveKeyboard(PInternalName: string, PLgCode?: string, saveCookie?: boolean): Promise<void> {
var n, Ln;
let keyman = com.keyman.singleton;
var util = keyman.util;
var osk = keyman.osk;
let activeKeyboard = keyman.core.activeKeyboard;
// Set default language code
if(arguments.length < 2 || (!PLgCode)) {
PLgCode='---';
}
// Check that the saved keyboard is currently registered
for(n=0; n < this.keyboardStubs.length; n++) {
if(PInternalName == this.keyboardStubs[n]['KI']) {
if(PLgCode == this.keyboardStubs[n]['KLC'] || PLgCode == '---') break;
}
}
// Mobile device addition: force selection of the first keyboard if none set
if(util.device.touchable && (PInternalName == '' || PInternalName == null || n >= this.keyboardStubs.length)) {
if(this.keyboardStubs.length != 0) {
PInternalName=this.keyboardStubs[0]['KI'];
PLgCode=this.keyboardStubs[0]['KLC'];
}
}
// Save name of keyboard (with language code) as a cookie
if(arguments.length > 2 && saveCookie) {
this.saveCurrentKeyboard(PInternalName,PLgCode);
}
// Check if requested keyboard and stub are currently active
if(this.activeStub && activeKeyboard && activeKeyboard.id == PInternalName
&& this.activeStub['KI'] == PInternalName //this part of test should not be necessary, but keep anyway
&& this.activeStub['KLC'] == PLgCode && !this.keymanweb.mustReloadKeyboard
) return Promise.resolve();
// Check if current keyboard matches requested keyboard, but not stub
if(activeKeyboard && (activeKeyboard.id == PInternalName)) {
// If so, simply update the active stub
for(Ln=0; Ln<this.keyboardStubs.length; Ln++) {
if((this.keyboardStubs[Ln]['KI'] == PInternalName)
&& (this.keyboardStubs[Ln]['KLC'] == PLgCode)) {
this.activeStub = this.keyboardStubs[Ln];
// Append a stylesheet for this keyboard for keyboard specific styles
// or if needed to specify an embedded font
osk.vkbd?.appendStyleSheet();
// Re-initializate OSK before returning if required
if(this.keymanweb.mustReloadKeyboard) {
activeKeyboard.refreshLayouts();
if(osk) {
osk._Load();
}
}
return Promise.resolve();
}
}
}
keyman.core.activeKeyboard = null;
this.activeStub = null;
// Hide OSK and do not update keyboard list if using internal keyboard (desktops)
if(PInternalName == '') {
osk.startHide(false);
if(!this.keymanweb.isEmbedded) {
util.wait(false);
}
return Promise.resolve();
}
// Determine if the keyboard was previously loaded but is not active and use the prior load if so.
for(Ln=0; Ln<this.keyboards.length; Ln++) { // I1511 - array prototype extended
if(this.keyboards[Ln]['KI'] == PInternalName) {
keyman.core.activeKeyboard = new Keyboard(this.keyboards[Ln]);
// As a rotation may have occurred since the keyboard was swapped out,
// we should refresh its layouts.
keyman.core.activeKeyboard.refreshLayouts();
this.keymanweb.domManager._SetTargDir(this.keymanweb.domManager.lastActiveElement); // I2077 - LTR/RTL timing
// and update the active stub
for(var Ls=0; Ls<this.keyboardStubs.length; Ls++) {
if((this.keyboardStubs[Ls]['KI'] == PInternalName) &&
(this.keyboardStubs[Ls]['KLC'] == PLgCode || PLgCode == '---')) {
this.activeStub = this.keyboardStubs[Ls];
break;
}
}
break;
}
}
// If we've reached this point, this is the first load request for the requested keyboard.
if(keyman.core.activeKeyboard == null) {
for(Ln=0; Ln<this.keyboardStubs.length; Ln++) { // I1511 - array prototype extended
if((this.keyboardStubs[Ln]['KI'] == PInternalName)
&& ((this.keyboardStubs[Ln]['KLC'] == PLgCode) || (PLgCode == '---'))) {
// Force OSK display for CJK keyboards (keyboards using a pick list)
if(this.isCJK(this.keyboardStubs[Ln]) || util.device.touchable) {
osk.displayIfActive = true;
}
// Create a script to load from the server - when it finishes loading, it will register itself,
// detect that it is active, and focus as appropriate. The second test is needed to allow recovery from a failed script load
// Ensure we're not already loading the keyboard.
if(!this.keyboardStubs[Ln].asyncLoader) {
// Always (temporarily) hide the OSK when loading a new keyboard, to ensure that a failure to load doesn't leave the current OSK displayed
if(osk) {
osk.startHide(false);
}
var loadingStub = this.keyboardStubs[Ln];
// Tag the stub so that we don't double-load the keyboard!
loadingStub.asyncLoader = {};
var kbdName = loadingStub['KN'];
var lngName = loadingStub['KL'];
kbdName = kbdName.replace(/\s*keyboard\s*/i, '');
// Setup our default error-messaging callback if it should be implemented.
loadingStub.asyncLoader.callback = function(altString, msgType) {
var msg = altString || 'Sorry, the '+kbdName+' keyboard for '+lngName+' is not currently available.';
// Thanks, Closure errors.
if(!this.keymanweb.isEmbedded) {
util.wait(false);
util.internalAlert(altString || msg, function() {
this.keymanweb['setActiveKeyboard'](''); // The API call!
}.bind(this));
}
switch(msgType) { // in case we extend this later.
case 'err':
console.error(msg);
break;
case 'warn':
default:
console.warn(msg);
break;
}
if(Ln > 0) {
var Ps = this.keyboardStubs[0];
this._SetActiveKeyboard(Ps['KI'], Ps['KLC'], true);
}
}.bind(this);
loadingStub.asyncLoader.timer = window.setTimeout(loadingStub.asyncLoader.callback, 10000);
//Display the loading delay bar (Note: only append 'keyboard' if not included in name.)
if(!this.keymanweb.isEmbedded) {
util.wait('Installing keyboard<br/>' + kbdName);
}
// Installing the script immediately does not work reliably if two keyboards are
// loaded in succession if there is any delay in downloading the script.
// It works much more reliably if deferred (KMEW-101, build 356)
// The effect of a delay can also be tested, for example, by setting the timeout to 5000
var manager = this;
loadingStub.asyncLoader.promise = new Promise<void>(function(resolve, reject) {
window.setTimeout(function(){
manager.installKeyboard(resolve, reject, loadingStub);
},0);
});
}
this.activeStub=this.keyboardStubs[Ln];
return this.keyboardStubs[Ln].asyncLoader.promise;
}
}
this.keymanweb.domManager._SetTargDir(this.keymanweb.domManager.lastActiveElement); // I2077 - LTR/RTL timing
}
// Initialize the OSK (provided that the base code has been loaded)
if(osk) {
osk._Load();
}
return Promise.resolve();
}
/**
* Install a keyboard script that has been downloaded from a keyboard server
* Operates as the core of a Promise, hence the 'resolve' and 'reject' parameters.
*
* @param {Object} kbdStub keyboard stub to be loaded.
*
**/
installKeyboard(resolve: () => void, reject: (message?: string) => void, kbdStub: KeyboardStub) {
var util = this.keymanweb.util;
var osk = this.keymanweb.osk;
var Lscript = util._CreateElement('script');
Lscript.charset="UTF-8"; // KMEW-89
Lscript.type = 'text/javascript';
// Preserve any namespaced IDs by use of the script's id tag attribute!
if(this.keymanweb.isEmbedded) {
Lscript.id = kbdStub['KI'];
}
var kbdFile = kbdStub['KF'];
var kbdLang = kbdStub['KL'];
var kbdName = kbdStub['KN'];
const scriptSrc = this.keymanweb.getKeyboardPath(kbdFile);
var manager = this;
let core = com.keyman.singleton.core;
// Add a handler for cases where the new <script> block fails to load.
Lscript.addEventListener('error', function() {
if(kbdStub.asyncLoader.timer !== null) {
// Clear the timeout timer.
window.clearTimeout(kbdStub.asyncLoader.timer);
kbdStub.asyncLoader.timer = null;
}
// We already know the load has failed... why wait?
const msg = 'Cannot find the ' + kbdName + ' keyboard for ' + kbdLang + ' at ' + scriptSrc + '.';
kbdStub.asyncLoader.callback(msg, 'warn');
kbdStub.asyncLoader = null;
reject(msg);
});
// The load event will activate a newly-loaded keyboard if successful and report an error if it is not.
Lscript.addEventListener('load', function() {
if(kbdStub.asyncLoader.timer !== null) {
// Clear the timeout timer.
window.clearTimeout(kbdStub.asyncLoader.timer);
kbdStub.asyncLoader.timer = null;
}
// To determine if the load was successful, we'll need to check the keyboard array for our desired keyboard.
// Test if keyboard already loaded
var kbd = manager.getKeyboardByID(kbdStub['KI']);
if(kbd) { // Is cleared upon a successful load.
//Activate keyboard, if it's still the active stub.
if(kbdStub == manager.activeStub) {
manager.doBeforeKeyboardChange(kbd['KI'],kbdStub['KLC']);
core.activeKeyboard=new Keyboard(kbd);
if(manager.keymanweb.domManager.lastActiveElement != null) { // TODO: Resolve without need for the cast.
manager.keymanweb.uiManager.justActivated = true; // TODO: Resolve without need for the cast.
manager.keymanweb.domManager._SetTargDir(manager.keymanweb.domManager.lastActiveElement);
}
manager.saveCurrentKeyboard(kbd['KI'], kbdStub['KLC']);
// Prepare and show the OSK for this keyboard
if(osk) {
osk._Load();
}
if(manager.keymanweb.domManager.lastActiveElement != null) {
core.processNewContextEvent(dom.Utils.getOutputTarget(manager.keymanweb.domManager.lastActiveElement));
}
}
// Remove the wait message, if defined
if(!manager.keymanweb.isEmbedded) {
util.wait(false);
}
kbdStub.asyncLoader = null;
resolve();
// A handler portion for cases where the new <script> block loads, but fails to process.
} else { // Output error messages even when embedded - they're useful when debugging the apps and KMEA/KMEI engines.
const msg = 'Error registering the ' + kbdName + ' keyboard for ' + kbdLang + '; keyboard script at ' + scriptSrc + ' may contain an error.';
kbdStub.asyncLoader.callback(msg, 'error');
kbdStub.asyncLoader = null;
reject(msg);
}
}, false);
// Some browsers may instantly start loading the file when assigned to an element, so we do this after the rest
// of our setup. This method is not relocated here (yet) b/c it varies based upon 'native' vs 'embedded'.
Lscript.src = scriptSrc;
try {
document.body.appendChild(Lscript);
}
catch(ex) {
try {
document.getElementsByTagName('head')[0].appendChild(Lscript);
} catch(ex2) {
reject('Error registering script ' + scriptSrc + ': ' + ex2);
return;
}
}
this.linkedScripts.push(Lscript);
}
/* TODO: why not use util.loadCookie and saveCookie?? */
/**
* Function saveCurrentKeyboard
* Scope Private
* @param {string} PInternalName name of keyboard
* @param {string} PLgCode language code
* Description Saves current keyboard as a cookie
*/
private saveCurrentKeyboard(PInternalName: string, PLgCode: string) {
var s = "current="+PInternalName+":"+PLgCode;
this.keymanweb.util.saveCookie('KeymanWeb_Keyboard',{'current':PInternalName+':'+PLgCode});
// Additionally, make sure we save the (upcoming) per-control keyboard settings.
// This allows us to ensure the keyboard is set correctly without waiting for focus event
// triggers - very helpful for automated testing.
if(!this.keymanweb.isEmbedded) {
this.keymanweb.touchAliasing._BlurKeyboardSettings(this.keymanweb.domManager.lastActiveElement, PInternalName, PLgCode);
}
}
/**
* Restore the most recently used keyboard, if still available
*/
restoreCurrentKeyboard() {
var stubs = this.keyboardStubs, i, n=stubs.length;
let core = com.keyman.singleton.core;
// Do nothing if no stubs loaded
if(stubs.length < 1) return;
// If no saved keyboard, default to US English, else first loaded stub
var d=this.getSavedKeyboard();
var t=d.split(':');
// Identify the stub with the saved keyboard
t=d.split(':');
if(t.length < 2) t[1]='';
// This loop is needed to select the correct stub when several apply to a given keyboard
// TODO: There should be a better way!
for(i=0; i<n; i++)
{
if(stubs[i]['KI'] == t[0] && (stubs[i]['KLC'] == t[1] || t[1] == '')) break;
}
// Sets the default stub (as specified with the `getSavedKeyboard` call) as active.
// if((i < n) || (device.touchable && (this.activeKeyboard == null)))
if((i < n) || (core.activeKeyboard == null))
{
this._SetActiveKeyboard(t[0],t[1],false);
this.keymanweb.globalKeyboard = t[0];
this.keymanweb.globalLanguageCode = t[1];
this.doKeyboardChange(t[0],t[1]); // And update the UI if necessary
}
}
/**
* Gets the cookie for the name and language code of the most recently active keyboard
*
* Defaults to US English, but this needs to be user-set in later revision (TODO)
*
* @return {string} InternalName:LanguageCode
**/
getSavedKeyboard(): string {
var v = this.keymanweb.util.loadCookie('KeymanWeb_Keyboard');
if(typeof(v['current']) != 'string') {
return 'Keyboard_us:eng';
}
// Check that the requested keyboard is included in the available keyboard stubs
var n, stubs = this.keyboardStubs,kd;
for(n=0; n<stubs.length; n++) {
kd=stubs[n]['KI']+':'+stubs[n]['KLC'];
if(kd == v['current']) return kd;
}
// Default to US English if available (but don't assume it is first)
for(n=0; n<stubs.length; n++) {
kd=stubs[n]['KI']+':'+stubs[n]['KLC'];
if(kd == 'Keyboard_us:eng') return kd;
}
// Otherwise use the first keyboard stub
if(stubs.length > 0) {
return stubs[0]['KI']+':'+stubs[0]['KLC'];
}
// Or US English if no stubs loaded (should never happen)
return 'Keyboard_us:eng';
}
/**
* Function isCJK
* Scope Public
* @param {Object=} k0
* @return {boolean}
* Description Tests if the keyboard stub uses a pick list (Chinese, Japanese, Korean, etc.)
* (This function accepts either keyboard structure.)
*/
isCJK(k: KeyboardStub) { // I3363 (Build 301)
var lg: string;
if(typeof(k['KLC']) != 'undefined') {
lg = k['KLC'];
} else if(typeof(k['LanguageCode']) != 'undefined') {
lg = k['LanguageCode'];
}
return ((lg == 'cmn') || (lg == 'jpn') || (lg == 'kor'));
}
/**
* Function _getKeyboardByID
* Scope Private
* @param {string} keyboardID
* @return {Object|null}
* Description Returns the internal, registered keyboard object - not the stub, but the keyboard itself.
*/
private getKeyboardByID(keyboardID: string):any {
var Li;
for(Li=0; Li<this.keyboards.length; Li++) {
if(keyboardID == this.keyboards[Li]['KI']) {
return this.keyboards[Li];
}
}
return null;
}
/* ------------------------------------------------------------
* Definitions for adding, removing, and requesting keyboards.
* ------------------------------------------------------------
*/
/**
* Function isUniqueRequest
* Scope Private
* @param {Object} tEntry
* Description Checks to ensure that the stub isn't already loaded within KMW or subject
* to an already-pending request.
*/
isUniqueRequest(cloudList: {id: string, language?: string}[], tEntry: CloudRequestEntry) {
var k;
if(this.findStub(tEntry.id, tEntry.language) == null) {
for(k=0; k < cloudList.length; k++) {
if(cloudList[k].id == tEntry['id'] && cloudList[k].language == tEntry.language) {
return false;
}
}
return true;
} else {
return false;
}
};
/**
* Returns a Promise of the merged keyboard stubs and error stubs.
*
* If the keyboard stub array is empty, will return a rejected Promise,
* otherwise returns a resolved Promise.
*
* @param keyboardStubs array of keyboard stubs to merge.
* @param errorStubs array of error stubs to merge.
* @returns resolved or rejected promise with merged array of stubs.
*/
private mergeAndResolveStubPromises(keyboardStubs: (KeyboardStub|ErrorStub)[], errorStubs: ErrorStub[]) :
Promise<(KeyboardStub|ErrorStub)[]> {
if (errorStubs.length == 0) {
return Promise.resolve(keyboardStubs);
} if (keyboardStubs.length == 0) {
return Promise.reject(errorStubs);
} else {
// Merge this with errorStubs
let result: (KeyboardStub|ErrorStub)[] = keyboardStubs;
return Promise.resolve(result.concat(errorStubs));
}