-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
KMManager.java
3062 lines (2645 loc) · 115 KB
/
KMManager.java
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
/**
* Copyright (C) 2017 SIL International. All rights reserved.
*/
package com.tavultesoft.kmea;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.inputmethodservice.InputMethodService;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.InputType;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import androidx.core.content.ContextCompat;
import io.sentry.Breadcrumb;
import io.sentry.Sentry;
import io.sentry.SentryLevel;
import com.tavultesoft.kmea.KeyboardEventHandler.EventType;
import com.tavultesoft.kmea.KeyboardEventHandler.OnKeyboardDownloadEventListener;
import com.tavultesoft.kmea.KeyboardEventHandler.OnKeyboardEventListener;
import com.tavultesoft.kmea.cloud.CloudDataJsonUtil;
import com.tavultesoft.kmea.cloud.CloudDownloadMgr;
import com.tavultesoft.kmea.data.Dataset;
import com.tavultesoft.kmea.data.Keyboard;
import com.tavultesoft.kmea.data.KeyboardController;
import com.tavultesoft.kmea.logic.ResourcesUpdateTool;
import com.tavultesoft.kmea.packages.JSONUtils;
import com.tavultesoft.kmea.packages.LexicalModelPackageProcessor;
import com.tavultesoft.kmea.packages.PackageProcessor;
import com.tavultesoft.kmea.util.BCP47;
import com.tavultesoft.kmea.util.CharSequenceUtil;
import com.tavultesoft.kmea.util.FileUtils;
import com.tavultesoft.kmea.util.KMLog;
import com.tavultesoft.kmea.util.KMString;
import com.tavultesoft.kmea.util.MapCompat;
import com.tavultesoft.kmea.util.WebViewUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public final class KMManager {
private static final String TAG = "KMManager";
private static ResourcesUpdateTool updateTool;
// Keyboard types
public enum KeyboardType {
KEYBOARD_TYPE_UNDEFINED,
KEYBOARD_TYPE_INAPP,
KEYBOARD_TYPE_SYSTEM;
}
// Keyboard states
public enum KeyboardState {
KEYBOARD_STATE_UNDEFINED,
KEYBOARD_STATE_NEEDS_DOWNLOAD,
KEYBOARD_STATE_NEEDS_UPDATE,
KEYBOARD_STATE_UP_TO_DATE;
}
// Globe key actions
public enum GlobeKeyAction {
GLOBE_KEY_ACTION_SHOW_MENU,
// GLOBE_KEY_ACTION_SWITCH_TO_PREVIOUS_KEYBOARD, // Switch to previous Keyman keyboard (reserved for flick)
GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD, // Switch to next Keyman keyboard
GLOBE_KEY_ACTION_ADVANCE_TO_PREVIOUS_SYSTEM_KEYBOARD, // Advance to previous system keyboard
GLOBE_KEY_ACTION_ADVANCE_TO_NEXT_SYSTEM_KEYBOARD, // Advance to next system keyboard
GLOBE_KEY_ACTION_SHOW_SYSTEM_KEYBOARDS,
GLOBE_KEY_ACTION_DO_NOTHING,
}
public enum GlobeKeyState {
GLOBE_KEY_STATE_UP,
GLOBE_KEY_STATE_DOWN,
GLOBE_KEY_STATE_LONGPRESS
}
public enum FormFactor {
PHONE,
TABLET;
}
public enum Tier {
ALPHA,
BETA,
STABLE
}
public enum SpacebarText {
LANGUAGE,
KEYBOARD,
LANGUAGE_KEYBOARD,
BLANK;
// Maps to enum SpacebarText in kmwbase.ts
public static SpacebarText fromString(String mode) {
if(mode == null) return LANGUAGE_KEYBOARD;
switch(mode) {
case "language": return LANGUAGE;
case "keyboard": return KEYBOARD;
case "languageKeyboard": return LANGUAGE_KEYBOARD;
case "blank": return BLANK;
}
return LANGUAGE_KEYBOARD;
}
public String toString() {
String modes[] = { "language", "keyboard", "languageKeyboard", "blank" };
return modes[this.ordinal()];
}
};
private static InputMethodService IMService;
private static boolean debugMode = false;
private static boolean shouldAllowSetKeyboard = true;
private static boolean didCopyAssets = false;
private static boolean didLogHardwareKeystrokeException = false;
private static GlobeKeyAction inappKbGlobeKeyAction = GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD;
private static GlobeKeyAction sysKbGlobeKeyAction = GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD;
// This is used to keep track of the starting system keyboard index while the screen is locked
private static int startingKeyboardIndexOnLockScreen = -1;
// This is used to keep track of the globe key shortpress and longpress
private static GlobeKeyState globeKeyState = GlobeKeyState.GLOBE_KEY_STATE_UP;
private static KMManager.SpacebarText spacebarText = KMManager.SpacebarText.LANGUAGE_KEYBOARD; // must match default given in kmwbase.ts
protected static boolean InAppKeyboardLoaded = false;
protected static boolean SystemKeyboardLoaded = false;
protected static boolean InAppKeyboardShouldIgnoreTextChange = false;
protected static boolean InAppKeyboardShouldIgnoreSelectionChange = false;
protected static boolean SystemKeyboardShouldIgnoreTextChange = false;
protected static boolean SystemKeyboardShouldIgnoreSelectionChange = false;
protected static KMKeyboard InAppKeyboard = null;
protected static KMKeyboard SystemKeyboard = null;
protected static HashMap<String, String> currentLexicalModel = null;
protected static WebViewUtils.EngineWebViewVersionStatus engineWebViewVersionStatus =
WebViewUtils.EngineWebViewVersionStatus.UNDETERMINED;
public final static String predictionPrefSuffix = ".mayPredict";
public final static String correctionPrefSuffix = ".mayCorrect";
/**
* Banner state value: "blank" - no banner available.
*/
protected static final String KM_BANNER_STATE_BLANK = "blank";
/**
* Banner state value: "suggestion" - dictionary suggestions are shown.
*/
protected static final String KM_BANNER_STATE_SUGGESTION = "suggestion";
//TODO: should be part of kmkeyboard
/**
* Current banner state.
*/
protected static String currentBanner = KM_BANNER_STATE_BLANK;
// Special override for when the keyboard may have haptic feedback when typing.
// haptic feedback disabled for hardware keystrokes
private static boolean mayHaveHapticFeedback = false;
// Special override for when keyboard is entering a password text field.
// When mayPredictOverride is true, the option {'mayPredict' = false} is set in the lm-layer
// regardless what the Settings preference is.
private static boolean mayPredictOverride = false;
// Boolean for whether a keyboard can send embedded KMW crash reports to Sentry
// When maySendCrashReport is false, KMW will still attempt to send crash reports, but it
// will be blocked.
private static boolean maySendCrashReport = true;
// Keyman public keys
public static final String KMKey_ID = "id";
public static final String KMKey_Name = "name";
public static final String KMKey_Version = "version";
public static final String KMKey_PackageID = "packageId";
public static final String KMKey_LanguageID = "langId";
public static final String KMKey_LanguageName = "langName";
public static final String KMKey_KeyboardCount = "kbCount";
public static final String KMKey_Icon = "icon";
public static final String KMKey_Keyboard = "keyboard";
public static final String KMKey_KeyboardID = "kbId";
public static final String KMKey_KeyboardName = "kbName";
public static final String KMKey_KeyboardVersion = "version";
public static final String KMKey_Font = "font";
public static final String KMKey_DisplayFont = "displayFont";
public static final String KMKey_OskFont = "oskFont";
public static final String KMKey_FontSource = "source";
public static final String KMKey_FontFiles = "files";
public static final String KMKey_FontFamily = "family";
public static final String KMKey_KMPInstall_Mode = "kmpInstallMode";
public static final String KMKey_KeyboardModified = "lastModified";
public static final String KMKey_KeyboardRTL = "rtl";
public static final String KMKey_KeyboardHeightPortrait = "keyboardHeightPortrait";
public static final String KMKey_KeyboardHeightLandscape = "keyboardHeightLandscape";
public static final String KMKey_CustomHelpLink = "CustomHelpLink";
public static final String KMKey_KMPLink = "kmp";
public static final String KMKey_UserKeyboardIndex = "UserKeyboardIndex";
public static final String KMKey_DisplayKeyboardSwitcher = "DisplayKeyboardSwitcher";
public static final String KMKey_LexicalModel = "lm";
public static final String KMKey_LexicalModelID = "lmId";
public static final String KMKey_LexicalModelName = "lmName";
public static final String KMKey_LexicalModelVersion = "lmVersion";
public static final String KMKey_LexicalModelPackageFilename = "kmpPackageFilename";
// DEPRECATED keys
public static final String KMKey_CustomKeyboard = "CustomKeyboard";
public static final String KMKey_CustomModel = "CustomModel";
public static final String KMKey_HelpLink = "helpLink";
// Keyman internal keys
protected static final String KMKey_ShouldShowHelpBubble = "ShouldShowHelpBubble";
// Default Legacy Asset Paths
// Previous keyboards installed from the cloud went to /languages/ and /fonts/
// Keyboards that have an undefined packageID were installed into /cloud/
public static final String KMDefault_LegacyAssetLanguages = "languages";
public static final String KMDefault_LegacyAssetFonts = "fonts";
public static final String KMDefault_UndefinedPackageID = "cloud";
// Keyboards now get installed into /packages/packageID/
public static final String KMDefault_AssetPackages = "packages";
public static final String KMDefault_LexicalModelPackages = "models";
// Default Keyboard Info
public static final String KMDefault_PackageID = "sil_euro_latin";
public static final String KMDefault_KeyboardID = "sil_euro_latin";
public static final String KMDefault_LanguageID = "en";
public static final String KMDefault_KeyboardName = "EuroLatin (SIL) Keyboard";
public static final String KMDefault_LanguageName = "English";
public static final String KMDefault_KeyboardFont = "DejaVuSans.ttf";
public static final String KMDefault_KeyboardKMP = KMDefault_PackageID + FileUtils.KEYMANPACKAGE;
// Default Dictionary Info
public static final String KMDefault_DictionaryPackageID = "nrc.en.mtnt";
public static final String KMDefault_DictionaryModelID = "nrc.en.mtnt";
public static final String KMDefault_DictionaryModelName = "English dictionary (MTNT)";
public static final String KMDefault_DictionaryVersion = "0.1.4";
public static final String KMDefault_DictionaryKMP = KMDefault_DictionaryPackageID + FileUtils.MODELPACKAGE;
// Keyman files
protected static final String KMFilename_KeyboardHtml = "keyboard.html";
protected static final String KMFilename_JSEngine = "keymanandroid.js";
protected static final String KMFilename_JSEngine_Sourcemap = "keyman.js.map";
protected static final String KMFilename_JSSentry = "keyman-sentry.js";
protected static final String KMFilename_AndroidHost = "android-host.js";
protected static final String KMFilename_KmwCss = "kmwosk.css";
protected static final String KMFilename_Osk_Ttf_Font = "keymanweb-osk.ttf";
protected static final String KMFilename_JSPolyfill = "es6-shim.min.js";
// Deprecated by KeyboardController.KMFilename_Installed_KeyboardsList
public static final String KMFilename_KeyboardsList = "keyboards_list.dat";
public static final String KMFilename_LexicalModelsList = "lexical_models_list.dat";
private static Context appContext;
public static String getResourceRoot() {
return appContext.getDir("data", Context.MODE_PRIVATE).toString() + File.separator;
}
public static String getPackagesDir() {
return getResourceRoot() + KMDefault_AssetPackages + File.separator;
}
public static String getLexicalModelsDir() {
return getResourceRoot() + KMDefault_LexicalModelPackages + File.separator;
}
public static String getCloudDir() {
return getResourceRoot() + KMDefault_UndefinedPackageID + File.separator;
}
public static FormFactor getFormFactor() {
String device_type = appContext.getResources().getString(R.string.device_type);
return device_type.equals("AndroidMobile") ? FormFactor.PHONE : FormFactor.TABLET;
}
/**
* Extract KMEA tier from versionName. Uses parameter so we can unit test.
* @param versionName String - If not provided, determine tier from
* com.tavultesoft.kmea.BuildConfig.KEYMAN_ENGINE_VERSION_NAME
* @return Tier (ALPHA, BETA, STABLE)
*/
public static Tier getTier(String versionName) {
if (versionName == null || versionName.isEmpty()) {
versionName = com.tavultesoft.kmea.BuildConfig.KEYMAN_ENGINE_VERSION_NAME;
}
Pattern pattern = Pattern.compile("^(\\d+\\.\\d+\\.\\d+)-(alpha|beta|stable).*");
Matcher matcher = pattern.matcher(versionName);
if (matcher.matches() && matcher.groupCount() >= 2) {
switch (matcher.group(2)) {
case "alpha": return Tier.ALPHA;
case "beta": return Tier.BETA;
default:
return Tier.STABLE;
}
}
return Tier.STABLE;
}
/**
* Extract KMEA major version #.# from KEYMAN_ENGINE_VERSION_NAME
* @return String
*/
public static String getMajorVersion() {
// Regex needs to match the entire string
String appVersion = com.tavultesoft.kmea.BuildConfig.KEYMAN_ENGINE_VERSION_NAME;
Pattern pattern = Pattern.compile("^(\\d+\\.\\d+)\\.\\d+.*");
Matcher matcher = pattern.matcher(appVersion);
if (matcher.matches() && matcher.groupCount() >= 1) {
appVersion = matcher.group(1);
}
return appVersion;
}
/**
* Extract KMEA version #.#.# from KEYMAN_ENGINE_VERSION_NAME
* @return String
*/
public static String getVersion() {
// Regex needs to match the entire string
String appVersion = com.tavultesoft.kmea.BuildConfig.KEYMAN_ENGINE_VERSION_NAME;
Pattern pattern = Pattern.compile("^(\\d+\\.\\d+\\.\\d+).*");
Matcher matcher = pattern.matcher(appVersion);
if (matcher.matches() && matcher.groupCount() >= 1) {
appVersion = matcher.group(1);
}
return appVersion;
}
/**
* Get the Keyman Engine mode.
* @return WebViewUtils.EngineWebViewVersionStatus
*/
public static WebViewUtils.EngineWebViewVersionStatus getEngineWebViewVersionStatus() {
return engineWebViewVersionStatus;
}
/**
* Set the Keyman Engine mode based on the Chrome version
* @param aContext
* @param webView - If provided, the Chrome version of the WebView is determined
*/
public static void setEngineWebViewVersionStatus(Context aContext, WebView webView) {
engineWebViewVersionStatus = WebViewUtils.getEngineWebViewVersionStatus(aContext, webView, "");
}
// Check if a keyboard namespace is reserved
public static boolean isReservedNamespace(String packageID) {
if (packageID.equals(KMDefault_UndefinedPackageID)) {
return true;
}
return false;
}
public static void initialize(final Context context, KeyboardType keyboardType) {
appContext = context.getApplicationContext();
if (!didCopyAssets || isTestMode()) {
// Copy and install assets
copyAssets(appContext);
migrateOldKeyboardFiles(appContext);
// UpdateOldKeyboardsList() handled with KeyboardController later
didCopyAssets = true;
}
if (keyboardType == KeyboardType.KEYBOARD_TYPE_INAPP) {
initInAppKeyboard(appContext);
} else if (keyboardType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
initSystemKeyboard(appContext);
} else {
String msg = "Cannot initialize: Invalid keyboard type";
KMLog.LogError(TAG, msg);
}
JSONUtils.initialize(new File(getPackagesDir()));
KeyboardController.getInstance().initialize(appContext);
migrateCloudKeyboards(appContext);
CloudDownloadMgr.getInstance().initialize(appContext);
}
public static void executeResourceUpdate(Context aContext)
{
getUpdateTool().checkForResourceUpdates(aContext,true);
}
public static ResourcesUpdateTool getUpdateTool() {
if(updateTool==null) {
updateTool = new ResourcesUpdateTool();
updateTool.createNotificationChannel(appContext);
KMKeyboardDownloaderActivity.addKeyboardDownloadEventListener(updateTool);
}
return updateTool;
}
public static void setInputMethodService(InputMethodService service) {
IMService = service;
}
public static InputMethodService getInputMethodService() { return IMService; }
public static boolean executeHardwareKeystroke(int code, int shift, int lstates, int eventModifiers) {
if (SystemKeyboard != null) {
return executeHardwareKeystroke(code, shift, KeyboardType.KEYBOARD_TYPE_SYSTEM, lstates, eventModifiers);
} else if (InAppKeyboard != null) {
return executeHardwareKeystroke(code, shift, KeyboardType.KEYBOARD_TYPE_INAPP, lstates, eventModifiers);
}
return false;
}
public static boolean executeHardwareKeystroke(
int code, int shift, KeyboardType keyboard, int lstates, int eventModifiers) {
if (keyboard == KeyboardType.KEYBOARD_TYPE_INAPP && InAppKeyboard != null) {
InAppKeyboard.executeHardwareKeystroke(code, shift, lstates, eventModifiers);
return true;
} else if (keyboard == KeyboardType.KEYBOARD_TYPE_SYSTEM && SystemKeyboard != null) {
SystemKeyboard.executeHardwareKeystroke(code, shift, lstates, eventModifiers);
return true;
} else if (!didLogHardwareKeystrokeException) {
KMLog.LogError(TAG, "executeHardwareKeystroke: " + keyboard.toString() + " keyboard is null");
didLogHardwareKeystrokeException = true;
}
return false;
}
/**
* Handle the globe key action on the lock screen
* @param context
*/
private static void doGlobeKeyLockscreenAction(Context context) {
// Override globe key action if screen is locked:
// 1. Switch to next Keyman keyboard (no menu)
// 2. When all the Keyman keyboards have been cycled through, advance to the next system keyboard
if (startingKeyboardIndexOnLockScreen == getCurrentKeyboardIndex(context) ||
KeyboardController.getInstance().get().size() == 1) {
// all the Keyman keyboards have been cycled through
advanceToNextInputMode();
} else {
if (startingKeyboardIndexOnLockScreen == -1) {
// Initialize the system keyboard starting index while the screen is locked
startingKeyboardIndexOnLockScreen = getCurrentKeyboardIndex(context);
}
switchToNextKeyboard(context);
}
}
/**
* Handle the globe key longpress action.
* @param context
* @param keyboard
*/
private static void doGlobeKeyLongpressAction(Context context, KeyboardType keyboard) {
if (keyboard == KeyboardType.KEYBOARD_TYPE_INAPP) {
if (InAppKeyboard == null || !InAppKeyboard.keyboardPickerEnabled) {
return;
}
} else if (keyboard == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
if (SystemKeyboard == null || !SystemKeyboard.keyboardPickerEnabled) {
return;
}
} else {
// assertion failure?
KMLog.LogError(TAG, "doGlobeKeyLongpressAction with keyboard type " + keyboard);
return;
}
showKeyboardPicker(context, keyboard);
}
/**
* Handle the globe key shortpress action
* @param context
* @param keyboard KeyboardType of KEYBOARD_TYPE_INAPP or KEYBOARD_TYPE_SYSTEM
*/
private static void doGlobeKeyShortpressAction(Context context, KeyboardType keyboard) {
GlobeKeyAction action = GlobeKeyAction.GLOBE_KEY_ACTION_DO_NOTHING;
if (keyboard == KeyboardType.KEYBOARD_TYPE_INAPP) {
if (InAppKeyboard == null || !InAppKeyboard.keyboardPickerEnabled) {
return;
}
action = inappKbGlobeKeyAction;
} else if (keyboard == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
if (SystemKeyboard == null || !SystemKeyboard.keyboardPickerEnabled) {
return;
}
action = sysKbGlobeKeyAction;
} else {
// assertion failure?
KMLog.LogError(TAG, "doGlobeKeyShortpressAction with keyboard type " + keyboard);
return;
}
if (action == GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD &&
KeyboardController.getInstance().get().size() == 1) {
// Override when keyboard switch and only 1 keyboard installed
if (keyboard == KeyboardType.KEYBOARD_TYPE_INAPP) {
// In-app keyboard shows keyboard menu
action = GlobeKeyAction.GLOBE_KEY_ACTION_SHOW_MENU;
} else if (keyboard == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
// System keyboard switches back to previous system keyboard (Issue #6175)
action = GlobeKeyAction.GLOBE_KEY_ACTION_ADVANCE_TO_PREVIOUS_SYSTEM_KEYBOARD;
}
}
switch (action) {
case GLOBE_KEY_ACTION_SHOW_MENU:
showKeyboardPicker(context, keyboard);
break;
case GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD:
switchToNextKeyboard(context);
break;
case GLOBE_KEY_ACTION_ADVANCE_TO_PREVIOUS_SYSTEM_KEYBOARD:
// Only do this for system keyboard
if (keyboard == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
advanceToPreviousInputMethod();
}
break;
case GLOBE_KEY_ACTION_ADVANCE_TO_NEXT_SYSTEM_KEYBOARD:
// Only do this for system keyboard
if (keyboard == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
advanceToNextInputMode();
}
break;
case GLOBE_KEY_ACTION_SHOW_SYSTEM_KEYBOARDS:
// Only do this for system keyboard
if (keyboard == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showInputMethodPicker();
}
break;
default:
// Do nothing
}
}
/**
* Adjust the keyboard dimensions. If the suggestion banner is active, use the
* combined banner height and keyboard height
* @return RelativeLayout.LayoutParams
*/
public static RelativeLayout.LayoutParams getKeyboardLayoutParams() {
int bannerHeight = getBannerHeight(appContext);
int kbHeight = getKeyboardHeight(appContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, bannerHeight + kbHeight);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
return params;
}
private static void initInAppKeyboard(Context appContext) {
if (InAppKeyboard == null) {
InAppKeyboard = new KMKeyboard(appContext, KeyboardType.KEYBOARD_TYPE_INAPP);
RelativeLayout.LayoutParams params = getKeyboardLayoutParams();
InAppKeyboard.setLayoutParams(params);
InAppKeyboard.setVerticalScrollBarEnabled(false);
InAppKeyboard.setHorizontalScrollBarEnabled(false);
InAppKeyboard.setWebViewClient(new KMInAppKeyboardWebViewClient(appContext));
InAppKeyboard.addJavascriptInterface(new KMInAppKeyboardJSHandler(appContext, InAppKeyboard), "jsInterface");
InAppKeyboard.loadKeyboard();
setEngineWebViewVersionStatus(appContext, InAppKeyboard);
}
}
private static void initSystemKeyboard(Context appContext) {
if (SystemKeyboard == null) {
SystemKeyboard = new KMKeyboard(appContext, KeyboardType.KEYBOARD_TYPE_SYSTEM);
RelativeLayout.LayoutParams params = getKeyboardLayoutParams();
SystemKeyboard.setLayoutParams(params);
SystemKeyboard.setVerticalScrollBarEnabled(false);
SystemKeyboard.setHorizontalScrollBarEnabled(false);
SystemKeyboard.setWebViewClient(new KMSystemKeyboardWebViewClient(appContext));
SystemKeyboard.addJavascriptInterface(new KMSystemKeyboardJSHandler(appContext, SystemKeyboard), "jsInterface");
SystemKeyboard.loadKeyboard();
setEngineWebViewVersionStatus(appContext, SystemKeyboard);
}
}
public static String getLanguagePredictionPreferenceKey(String langID) {
return langID + predictionPrefSuffix;
}
public static String getLanguageCorrectionPreferenceKey(String langID) {
return langID + correctionPrefSuffix;
}
public static void hideSystemKeyboard() {
if (SystemKeyboard != null) {
SystemKeyboard.hideKeyboard();
}
}
public static void showSystemKeyboard() {
if (SystemKeyboard != null) {
SystemKeyboard.showKeyboard();
}
}
public static boolean isKeyboardLoaded(KeyboardType type) {
if (type == KeyboardType.KEYBOARD_TYPE_INAPP) {
return InAppKeyboardLoaded;
} else if (type == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
return SystemKeyboardLoaded;
} else {
String msg = "Keyboard type undefined";
KMLog.LogError(TAG, msg);
return false;
}
}
@SuppressLint("InflateParams")
public static View createInputView(InputMethodService inputMethodService) {
//final Context context = appContext;
IMService = inputMethodService;
Context appContext = IMService.getApplicationContext();
final FrameLayout mainLayout = new FrameLayout(appContext);
mainLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
RelativeLayout keyboardLayout = new RelativeLayout(appContext);
keyboardLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
ViewGroup parent = (ViewGroup) SystemKeyboard.getParent();
if (parent != null)
parent.removeView(SystemKeyboard);
keyboardLayout.addView(SystemKeyboard);
mainLayout.addView(keyboardLayout);
//mainLayout.addView(overlayLayout);
return mainLayout;
}
public static void onStartInput(EditorInfo attribute, boolean restarting) {
if (!restarting && SystemKeyboard != null) {
String packageName = attribute.packageName;
int inputType = attribute.inputType;
if (packageName.equals("android") && inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {
SystemKeyboard.keyboardPickerEnabled = false;
} else {
SystemKeyboard.keyboardPickerEnabled = true;
}
}
}
public static void onResume() {
if (InAppKeyboard != null) {
InAppKeyboard.resumeTimers();
InAppKeyboard.onResume();
}
if (SystemKeyboard != null) {
SystemKeyboard.resumeTimers();
SystemKeyboard.onResume();
}
}
public static void onPause() {
if (InAppKeyboard != null) {
InAppKeyboard.onPause();
}
if (SystemKeyboard != null) {
SystemKeyboard.onPause();
}
// Lock screen triggers onPause, so clear globeKeyState
globeKeyState = GlobeKeyState.GLOBE_KEY_STATE_UP;
}
public static void onDestroy() {
if (InAppKeyboard != null) {
InAppKeyboard.onDestroy();
}
if (SystemKeyboard != null) {
SystemKeyboard.onDestroy();
}
updateTool.destroyNotificationChannel(appContext);
CloudDownloadMgr.getInstance().shutdown(appContext);
}
public static void onConfigurationChanged(Configuration newConfig) {
// KMKeyboard
if (InAppKeyboard != null) {
RelativeLayout.LayoutParams params = getKeyboardLayoutParams();
InAppKeyboard.setLayoutParams(params);
InAppKeyboard.onConfigurationChanged(newConfig);
}
if (SystemKeyboard != null) {
RelativeLayout.LayoutParams params = getKeyboardLayoutParams();
SystemKeyboard.setLayoutParams(params);
SystemKeyboard.onConfigurationChanged(newConfig);
}
}
/**
* Query the AndroidManifest file to see if a permission is granted.
* @param permission - The manifest permission to query
* @return boolean - true if the manifest permission is granted
*/
protected static boolean hasPermission(Context context, String permission) {
// API to check permission depends on Android SDK level
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
/**
* Check if KMManager has an active network connection.
* Requires Manifest.permission.ACCESS_NETWORK_STATE to be granted
* @param context - The context
* @return boolean - true if manifest permission ACCESS_NETWORK_STATE is granted and the device
* has an active network connection
*/
@SuppressLint("MissingPermission")
public static boolean hasConnection(Context context) {
if (hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
return false;
}
public static boolean hasInternetPermission(Context context) {
return hasPermission(context, Manifest.permission.INTERNET);
}
private static void copyAssets(Context context) {
AssetManager assetManager = context.getAssets();
try {
// Copy KMW files
copyAsset(context, KMFilename_KeyboardHtml, "", true);
copyAsset(context, KMFilename_JSEngine, "", true);
copyAsset(context, KMFilename_JSSentry, "", true);
copyAsset(context, KMFilename_AndroidHost, "", true);
if(KMManager.isDebugMode()) {
copyAsset(context, KMFilename_JSEngine_Sourcemap, "", true);
}
copyAsset(context, KMFilename_KmwCss, "", true);
copyAsset(context, KMFilename_Osk_Ttf_Font, "", true);
// Copy default keyboard font
copyAsset(context, KMDefault_KeyboardFont, "", true);
copyAsset(context, KMFilename_JSPolyfill, "", true);
// Keyboard packages directory
File packagesDir = new File(getPackagesDir());
if (!packagesDir.exists()) {
packagesDir.mkdir();
}
/*
// default cloud keyboard
// Intend to deprecate cloud/keyboards in Keyman 15.0
*/
File cloudDir = new File(getCloudDir());
if (!cloudDir.exists()) {
cloudDir.mkdir();
}
String[] keyboardFiles = assetManager.list(KMDefault_UndefinedPackageID);
for (String keyboardFile : keyboardFiles) {
copyAsset(context, keyboardFile, KMDefault_UndefinedPackageID, true);
}
// Copy lexical model directory and subfolders
File lexicalModelsDir = new File(getLexicalModelsDir());
if (!lexicalModelsDir.exists()) {
lexicalModelsDir.mkdir();
}
String[] modelNames = assetManager.list(KMDefault_LexicalModelPackages);
for (String modelName : modelNames) {
File lexicalModelDir = new File(lexicalModelsDir, modelName);
if (!lexicalModelDir.exists()) {
lexicalModelDir.mkdir();
}
String[] modelFiles = assetManager.list(KMDefault_LexicalModelPackages + File.separator + modelName);
for (String modelFile : modelFiles) {
copyAsset(context, modelFile, KMDefault_LexicalModelPackages + File.separator + modelName, true);
}
}
File resourceRoot = new File(getResourceRoot());
PackageProcessor kmpProcessor = new PackageProcessor(resourceRoot);
LexicalModelPackageProcessor lmkmpProcessor = new LexicalModelPackageProcessor(resourceRoot);
String assetFiles[] = assetManager.list("");
for (String assetFile : assetFiles) {
File kmpFile, tempPackagePath;
boolean isPackageFile = FileUtils.hasKeymanPackageExtension(assetFile) ||
FileUtils.hasLexicalModelPackageExtension(assetFile);
// Copy asset KMP files
if (isPackageFile) {
kmpFile = new File(getResourceRoot(), assetFile);
if (kmpFile.exists()) {
// Skip if kmp file already exists.
// Admittedly, we'll miss out on kmp updates with Keyman upgrades
continue;
}
copyAsset(context, assetFile, "", true);
tempPackagePath = kmpProcessor.unzipKMP(kmpFile);
// Determine package info
JSONObject pkgInfo = kmpProcessor.loadPackageInfo(tempPackagePath);
if (pkgInfo == null) {
KMLog.LogError(TAG, "Invalid kmp.json in default asset " + assetFile);
}
String assetPackageID = kmpProcessor.getPackageID(kmpFile);
String assetPackageTarget = kmpProcessor.getPackageTarget(pkgInfo);
// Only install if asset package is not a downgrade
try {
if (assetPackageTarget.equals(PackageProcessor.PP_TARGET_KEYBOARDS)) {
if (!kmpProcessor.isDowngrade(kmpFile, true)) {
// Not using the list of entries returned from processKMP()
// because the main App will add the keyboard/lexical model info
kmpProcessor.processKMP(kmpFile, tempPackagePath, PackageProcessor.PP_KEYBOARDS_KEY);
}
} else if (assetPackageTarget.equals(PackageProcessor.PP_TARGET_LEXICAL_MODELS)) {
if (!lmkmpProcessor.isDowngrade(kmpFile)) {
lmkmpProcessor.processKMP(kmpFile, tempPackagePath, PackageProcessor.PP_LEXICAL_MODELS_KEY);
}
}
} catch (JSONException e) {
KMLog.LogException(TAG, "Unable to determine isDowngrade for " + kmpFile.toString(), e);
}
// Cleanup tempPackagePath
if (tempPackagePath.exists()) {
FileUtils.deleteDirectory(tempPackagePath);
}
}
}
} catch (Exception e) {
KMLog.LogException(TAG, "Failed to copy assets. Error: ", e);
}
}
private static int copyAsset(Context context, String filename, String directory, boolean overwrite) {
int result;
AssetManager assetManager = context.getAssets();
try {
if (directory == null)
directory = "";
directory = directory.trim();
String dirPath;
if (directory.length() != 0) {
directory = directory + File.separator;
dirPath = getResourceRoot() + directory;
} else {
dirPath = getResourceRoot();
}
File file = new File(dirPath, filename);
if (!file.exists() || overwrite) {
InputStream inputStream = assetManager.open(directory + filename);
FileOutputStream outputStream = new FileOutputStream(file);
FileUtils.copy(inputStream, outputStream);
result = 1;
} else {
result = 0;
}
} catch (Exception e) {
KMLog.LogException(TAG, "Failed to copy asset. Error: ", e);
result = -1;
}
return result;
}
/**
* Migrates legacy keyboards in the /languages/ and /fonts/ directories so that:
* 1) Default eurolatin2 or us.js keyboards are deleted
* 2) Keyboards missing a version number are assigned "-1.0"
* 3) Remaining keyboards are moved to /cloud/ (default packageID of "cloud")
* 4) Remove legacy /languages/ and /fonts/ directories
*
* Fonts used in legacy keyboards are also migrated from /fonts/ to /cloud/
*
* At some point, we might migrate /cloud/ keyboards into packages
* 5) For now, delete cloud/sil_euro_latin*.js
*
* Assumption: No legacy keyboards exist in /packages/*.js
* @param context
*/
private static void migrateOldKeyboardFiles(Context context) {
String legacyLanguagesPath = getResourceRoot() + KMDefault_LegacyAssetLanguages + File.separator;
String legacyFontsPath = getResourceRoot() + KMDefault_LegacyAssetFonts + File.separator;
File legacyLanguagesDir = new File(legacyLanguagesPath);
File legacyFontsDir = new File(legacyFontsPath);
File migratedDir = new File(getCloudDir());
if (!legacyLanguagesDir.exists() && !legacyFontsDir.exists() && !migratedDir.exists()) {
return;
}
if (!migratedDir.exists()) {
migratedDir.mkdir();
}
FileFilter keyboardFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isFile() && FileUtils.hasJavaScriptExtension(pathname.getName())) {
return true;
}
return false;
}
};
try {
if (legacyLanguagesDir.exists()) {
File[] files = legacyLanguagesDir.listFiles(keyboardFilter);
for (File file : files) {
String filename = file.getName();
// Keyboards can have filenames "keyboardID.js" or "keyboardID-version.js"
boolean versionNumberMissing = filename.lastIndexOf("-") < 0;
String keyboardID = (versionNumberMissing) ? filename.substring(0, filename.length() - 4) :
filename.substring(0, filename.indexOf("-"));
// Handle keyboards missing version number
if (versionNumberMissing) {
if (filename.equals("us.js")) {
file.delete();
} else {
// Append default version number to keyboard and move
filename = filename.substring(0, filename.lastIndexOf(".js")) + "-1.0.js";
File migratedFile = new File(migratedDir, filename);
if (!migratedFile.exists()) {
file.renameTo(new File(migratedDir, filename));
}
}
// Handle keyboards with version number