-
-
Notifications
You must be signed in to change notification settings - Fork 112
/
KMKeyboard.java
1509 lines (1318 loc) · 53.5 KB
/
KMKeyboard.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-2018 SIL International. All rights reserved.
*/
package com.tavultesoft.kmea;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.tavultesoft.kmea.BaseActivity;
import com.tavultesoft.kmea.data.Keyboard;
import com.tavultesoft.kmea.data.KeyboardController;
import com.tavultesoft.kmea.KMManager.KeyboardType;
import com.tavultesoft.kmea.KeyboardEventHandler.EventType;
import com.tavultesoft.kmea.KeyboardEventHandler.OnKeyboardEventListener;
import com.tavultesoft.kmea.util.FileUtils;
import com.tavultesoft.kmea.util.KMLog;
import com.tavultesoft.kmea.util.KMString;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import io.sentry.Breadcrumb;
import io.sentry.Sentry;
import io.sentry.SentryLevel;
final class KMKeyboard extends WebView {
private static final String TAG = "KMKeyboard";
private final Context context;
private KeyboardType keyboardType = KeyboardType.KEYBOARD_TYPE_UNDEFINED;
private String packageID;
private String keyboardID;
private String keyboardName;
private String keyboardVersion;
protected ArrayList<String> javascriptAfterLoad = new ArrayList<String>();
private static String currentKeyboard = null;
private static String txtFont = "";
private static String oskFont = null;
private static String keyboardRoot = "";
private final String fontUndefined = "undefined";
private GestureDetector gestureDetector;
private static ArrayList<OnKeyboardEventListener> kbEventListeners = null;
private boolean ShouldShowHelpBubble = false;
private boolean isChiral = false;
private int currentKeyboardErrorReports = 0;
protected boolean keyboardSet = false;
protected boolean keyboardPickerEnabled = true;
protected boolean isHelpBubbleEnabled = true;
public PopupWindow subKeysWindow = null;
public PopupWindow keyPreviewWindow = null;
public PopupWindow helpBubbleWindow = null;
public ArrayList<HashMap<String, String>> subKeysList = null;
public String[] subKeysWindowPos = {"0", "0"};
// public something-something for the suggestion.
public PopupWindow suggestionMenuWindow = null;
public double[] suggestionWindowPos = {0, 0};
public String suggestionJSON = null;
public String specialOskFont = "";
public KMKeyboard(Context context) {
super(context);
this.context = context;
this.keyboardType = KeyboardType.KEYBOARD_TYPE_INAPP;
initKMKeyboard(context);
}
public KMKeyboard(Context context, KeyboardType keyboardType) {
super(context);
this.context = context;
this.keyboardType = keyboardType;
initKMKeyboard(context);
}
@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
public void initKMKeyboard(final Context context) {
setFocusable(false);
clearCache(true);
getSettings().setJavaScriptEnabled(true);
getSettings().setAllowFileAccess(true);
// Normally, this would be true to prevent the WebView from accessing the network.
// But this needs to false for sending embedded KMW crash reports to Sentry (keymanapp/keyman#3825)
if (KMManager.hasInternetPermission(context)) {
// Throws SecurityException if INTERNET permission not granted
getSettings().setBlockNetworkLoads(!KMManager.getMaySendCrashReport());
}
getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
getSettings().setSupportZoom(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getSettings().setUseWideViewPort(true);
getSettings().setLoadWithOverviewMode(true);
setWebContentsDebuggingEnabled(true);
}
if (keyboardType == KeyboardType.KEYBOARD_TYPE_INAPP && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
setLayerType(View.LAYER_TYPE_SOFTWARE, null); // Disable hardware acceleration for API < 17, Keyman keyboard is slower without HWA but it causes some display issues.
// (Tested on Samsung Galaxy Nexus running Android 4.1.2)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
// These were deprecated in API 18
getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
}
setWebChromeClient(new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cm) {
String msg = KMString.format("KMW JS Log: Line %d, %s:%s", cm.lineNumber(), cm.sourceId(), cm.message());
if (KMManager.isDebugMode()) {
if (cm.messageLevel() == ConsoleMessage.MessageLevel.ERROR) {
Log.d(TAG, msg);
}
}
// Send console errors to Sentry in case they're missed by KMW sentryManager
// (Ignoring spurious message "No keyboard stubs exist = ...")
// TODO: Fix base error rather than trying to ignore it "No keyboard stubs exist"
if ((cm.messageLevel() == ConsoleMessage.MessageLevel.ERROR) && (!cm.message().startsWith("No keyboard stubs exist"))) {
// Make Toast notification of error and send log about falling back to default keyboard (ignore language ID)
// Sanitize sourceId info
String NAVIGATION_PATTERN = "^(.*)?(keyboard\\.html#[^-]+)-.*$";
String sourceID = cm.sourceId().replaceAll(NAVIGATION_PATTERN, "$1$2");
sendKMWError(cm.lineNumber(), sourceID, cm.message());
// This duplicates the sendKMWError message, which itself duplicates the reporting now
// managed by sentry-manager on the js side in patch in #6890. It does not give us
// additional useful information. So we don't re-send to Sentry.
sendError(packageID, keyboardID, "", false);
}
return true;
}
});
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent event) {
// https://developer.android.com/training/gestures/detector#detect-a-subset-of-supported-gestures
// If we return false, the system assumes we want to ignore the rest of the gesture
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(e2.getY() - e1.getY() < -5) { // TODO: get better threshold value from KMW
if (subKeysList != null && (subKeysWindow == null || !subKeysWindow.isShowing())) {
showSubKeys(context);
return true;
}
}
return false;
}
@Override
public void onLongPress(MotionEvent event) {
// This is also called for banner longpresses! Need a way to differentiate the sources.
if (subKeysList != null && (subKeysWindow == null || !subKeysWindow.isShowing())) {
showSubKeys(context);
return;
} else if (KMManager.getGlobeKeyState() == KMManager.GlobeKeyState.GLOBE_KEY_STATE_DOWN) {
KMManager.setGlobeKeyState(KMManager.GlobeKeyState.GLOBE_KEY_STATE_LONGPRESS);
KMManager.handleGlobeKeyAction(context, true, keyboardType);
return;
/* For future implementation
else if(suggestionJSON != null) {
showSuggestionLongpress(context);
return;
}*/
}
}
@Override
public boolean onSingleTapUp(MotionEvent event) {
return false;
}
});
}
public void loadKeyboard() {
keyboardSet = false;
this.javascriptAfterLoad.clear();
if(keyboardType == KeyboardType.KEYBOARD_TYPE_INAPP)
KMManager.InAppKeyboardLoaded = false;
else
KMManager.SystemKeyboardLoaded = false;
String htmlPath = "file://" + getContext().getDir("data", Context.MODE_PRIVATE) + "/" + KMManager.KMFilename_KeyboardHtml;
loadUrl(htmlPath);
setBackgroundColor(0);
}
public void loadJavascript(String func) {
this.javascriptAfterLoad.add(func);
if((keyboardType == KeyboardType.KEYBOARD_TYPE_INAPP && KMManager.InAppKeyboardLoaded) ||
(keyboardType == KeyboardType.KEYBOARD_TYPE_SYSTEM && KMManager.SystemKeyboardLoaded)) {
// If !this.keyboardSet, then pageLoaded hasn't fired yet.
// When pageLoaded fires, it'll call `callJavascriptAfterLoad` safely.
if(this.javascriptAfterLoad.size() == 1 && keyboardSet)
callJavascriptAfterLoad();
}
}
public void callJavascriptAfterLoad() {
if(this.javascriptAfterLoad.size() > 0) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(javascriptAfterLoad.size() > 0) {
loadUrl("javascript:" + javascriptAfterLoad.get(0));
javascriptAfterLoad.remove(0);
// Make sure we didn't reset the page in the middle of the queue!
if(keyboardSet) {
if (javascriptAfterLoad.size() > 0) {
callJavascriptAfterLoad();
}
}
}
}
}, 1);
}
}
public void hideKeyboard() {
dismissKeyPreview(0);
dismissSubKeysWindow();
String jsString = "hideKeyboard()";
loadJavascript(jsString);
}
public void showKeyboard() {
String jsString = "showKeyboard()";
loadJavascript(jsString);
}
public void executeHardwareKeystroke(int code, int shift, int lstates, int eventModifiers) {
String jsFormat = "executeHardwareKeystroke(%d,%d, %d, %d)";
String jsString = KMString.format(jsFormat, code, shift, lstates, eventModifiers);
loadJavascript(jsString);
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
// JH: I'm not sure if we even USE the suggestionMenuWindow construct anywhere, but either way,
// this if block is designed explicitly for handling the subKeysWindow.
//
// Come to think of it, I wonder if suggestionMenuWindow was work being done to link with
// suggestion banner longpresses - if so, it's not yet ready for proper integration...
// and would need its own rung in this if-else ladder.
if (subKeysWindow != null && suggestionMenuWindow == null && subKeysWindow.isShowing()) {
// Passes KMKeyboard (subclass of WebView)'s touch events off to our subkey window
// if active, allowing for smooth, integrated gesture control.
subKeysWindow.getContentView().findViewById(R.id.grid).dispatchTouchEvent(event);
} else {
if (event.getPointerCount() > 1) {
// Multiple points touch the screen at the same time, so dismiss any pending subkeys
dismissKeyPreview(0);
dismissSubKeysWindow();
}
gestureDetector.onTouchEvent(event);
}
if (action == MotionEvent.ACTION_UP) {
// Cleanup popups. #6636
dismissKeyPreview(0);
dismissSubKeysWindow();
}
return super.onTouchEvent(event);
}
public void onResume() {
DisplayMetrics dms = context.getResources().getDisplayMetrics();
int kbWidth = (int) (dms.widthPixels / dms.density);
// Ensure window is loaded for javascript functions
loadJavascript(KMString.format(
"window.onload = function(){ setOskWidth(\"%d\");"+
"setOskHeight(\"0\"); };", kbWidth));
if (ShouldShowHelpBubble) {
ShouldShowHelpBubble = false;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
loadJavascript("showHelpBubble()");
}
}, 2000);
}
}
public void onPause() {
dismissKeyPreview(0);
dismissSubKeysWindow();
ShouldShowHelpBubble = dismissHelpBubble();
}
public void onDestroy() {
dismissKeyPreview(0);
dismissSubKeysWindow();
dismissHelpBubble();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
dismissKeyPreview(0);
dismissSubKeysWindow();
RelativeLayout.LayoutParams params = KMManager.getKeyboardLayoutParams();
this.setLayoutParams(params);
int bannerHeight = KMManager.getBannerHeight(context);
int oskHeight = KMManager.getKeyboardHeight(context);
loadJavascript(KMString.format("setBannerHeight(%d)", bannerHeight));
loadJavascript(KMString.format("setOskWidth(%d)", newConfig.screenWidthDp));
loadJavascript(KMString.format("setOskHeight(%d)", oskHeight));
if (dismissHelpBubble()) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
loadJavascript("showHelpBubble()");
}
}, 2000);
}
}
public void dismissSubKeysWindow() {
try {
if (subKeysWindow != null && subKeysWindow.isShowing()) {
subKeysWindow.dismiss();
}
subKeysList = null;
} catch (Exception e) {
KMLog.LogException(TAG, "", e);
}
}
public void dismissSuggestionMenuWindow() {
try {
if (suggestionMenuWindow != null && suggestionMenuWindow.isShowing()) {
suggestionMenuWindow.dismiss();
}
} catch (Exception e) {
KMLog.LogException(TAG, "", e);
}
}
public static String currentKeyboard() {
return currentKeyboard;
}
/**
* Return the full path to the display text font. Usually used for creating a Typeface font
* @return String
*/
public static String textFontFilename() {
return txtFont;
}
/**
* Return the full path to the OSK font. Usually used for creating a Typeface font
* @return String
*/
public static String oskFontFilename() {
return oskFont;
}
/**
* Return the full path to the special OSK font,
* which is with all the keyboard assets at the root app_data folder
* @param filename
* @return String
*/
public String specialOSKFontFilename(String filename) {
return context.getDir("data", Context.MODE_PRIVATE).toString() + File.separator + filename;
}
public boolean setKeyboard(Keyboard k) {
boolean retVal = false;
if (k != null) {
retVal = setKeyboard(
k.getPackageID(),
k.getKeyboardID(),
k.getLanguageID(),
k.getKeyboardName(),
k.getLanguageName(),
k.getFont(),
k.getOSKFont(),
k.getDisplayName());
}
return retVal;
}
public boolean setKeyboard(String packageID, String keyboardID, String languageID) {
if (packageID == null || keyboardID == null || languageID == null)
return false;
boolean retVal = true;
int index = KeyboardController.getInstance().getKeyboardIndex(packageID, languageID, keyboardID);
Keyboard kbInfo = null;
if (index != KeyboardController.INDEX_NOT_FOUND) {
kbInfo = KeyboardController.getInstance().getKeyboardInfo(index);
}
if (!KMManager.shouldAllowSetKeyboard() || kbInfo == null) {
sendError(packageID, keyboardID, languageID, true);
kbInfo = KeyboardController.getInstance().getKeyboardInfo(0);
retVal = false;
} else {
retVal = setKeyboard(kbInfo);
}
return retVal;
}
/**
* preapre keyboard switch. The switch is executed in next reload.
* @param packageID the package id
* @param keyboardID the keyman keyboard id
* @param languageID the langauge id
* @param keyboardName the keyboard name
* @return the result
*/
public boolean prepareKeyboardSwitch(String packageID, String keyboardID, String languageID, String keyboardName)
{
if (packageID == null || keyboardID == null || languageID == null)
return false;
boolean retVal = true;
// keyboardVersion only needed for legacy cloud/ keyboards.
// Otherwise, no need for the JSON overhead of determining the keyboard version from kmp.json
String keyboardVersion = packageID.equals(KMManager.KMDefault_UndefinedPackageID) ?
KMManager.getLatestKeyboardFileVersion(getContext(), packageID, keyboardID) : null;
if (!KMManager.shouldAllowSetKeyboard() ||
(packageID.equals(KMManager.KMDefault_UndefinedPackageID) && keyboardVersion == null)) {
sendError(packageID, keyboardID, languageID, true);
Keyboard kbInfo = KeyboardController.getInstance().getKeyboardInfo(0);
packageID = kbInfo.getPackageID();
keyboardID = kbInfo.getKeyboardID();
languageID = kbInfo.getLanguageID();
retVal = false;
// Keyboard changed, so determine version again
keyboardVersion = packageID.equals(KMManager.KMDefault_UndefinedPackageID) ?
KMManager.getLatestKeyboardFileVersion(getContext(), packageID, keyboardID) : null;
}
String kbKey = KMString.format("%s_%s", languageID, keyboardID);
setKeyboardRoot(packageID);
// Escape single-quoted names for javascript call
keyboardName = keyboardName.replaceAll("\'", "\\\\'"); // Double-escaped-backslash b/c regex.
this.packageID = packageID;
this.keyboardID = keyboardID;
this.keyboardName = keyboardName;
this.keyboardVersion = keyboardVersion;
currentKeyboard = kbKey;
saveCurrentKeyboardIndex();
return retVal;
}
public boolean setKeyboard(String packageID, String keyboardID, String languageID,
String keyboardName, String languageName, String kFont,
String kOskFont) {
return setKeyboard(packageID, keyboardID, languageID, keyboardName, languageName,
kFont, kOskFont, null);
}
public boolean setKeyboard(String packageID, String keyboardID, String languageID,
String keyboardName, String languageName, String kFont,
String kOskFont, String displayName) {
if (packageID == null || keyboardID == null || languageID == null || keyboardName == null || languageName == null) {
return false;
}
// Reset the counter for showing / sending errors related to the selected keybard
currentKeyboardErrorReports = 0;
boolean retVal = true;
// keyboardVersion only needed for legacy cloud/ keyboards.
// Otherwise, no need for the JSON overhead of determining the keyboard version from kmp.json
String keyboardVersion = packageID.equals(KMManager.KMDefault_UndefinedPackageID) ?
KMManager.getLatestKeyboardFileVersion(getContext(), packageID, keyboardID) : null;
if (!KMManager.shouldAllowSetKeyboard() ||
(packageID.equals(KMManager.KMDefault_UndefinedPackageID) && keyboardVersion == null)) {
sendError(packageID, keyboardID, languageID, true);
Keyboard kbInfo = KeyboardController.getInstance().getKeyboardInfo(0);
packageID = kbInfo.getPackageID();
keyboardID = kbInfo.getKeyboardID();
languageID = kbInfo.getLanguageID();
keyboardName = kbInfo.getKeyboardName();
languageName = kbInfo.getLanguageName();
kFont = kbInfo.getFont();
kOskFont = kbInfo.getOSKFont();
retVal = false;
// Keyboard changed, so determine version again
keyboardVersion = packageID.equals(KMManager.KMDefault_UndefinedPackageID) ?
KMManager.getLatestKeyboardFileVersion(getContext(), packageID, keyboardID) : null;
}
setKeyboardRoot(packageID);
if(kOskFont == null || kOskFont.isEmpty())
kOskFont = kFont;
JSONObject jDisplayFont = makeFontPaths(kFont);
JSONObject jOskFont = makeFontPaths(kOskFont);
txtFont = getFontFilename(jDisplayFont);
oskFont = getFontFilename(jOskFont);
String kbKey = KMString.format("%s_%s", languageID, keyboardID);
String keyboardPath = makeKeyboardPath(packageID, keyboardID, keyboardVersion);
JSONObject reg = new JSONObject();
try {
reg.put("KN", keyboardName);
reg.put("KI", "Keyboard_" + keyboardID);
reg.put("KLC", languageID);
reg.put("KL", languageName);
reg.put("KF", keyboardPath);
reg.put("KP", packageID);
if (jDisplayFont != null) reg.put("KFont", jDisplayFont);
if (jOskFont != null) reg.put("KOskFont", jOskFont);
if (displayName != null) reg.put("displayName", displayName);
} catch(JSONException e) {
KMLog.LogException(TAG, "", e);
return false;
}
String jsString = KMString.format("setKeymanLanguage(%s)", reg.toString());
loadJavascript(jsString);
this.packageID = packageID;
this.keyboardID = keyboardID;
this.keyboardName = keyboardName;
this.keyboardVersion = keyboardVersion;
currentKeyboard = kbKey;
keyboardSet = true;
saveCurrentKeyboardIndex();
if (dismissHelpBubble()) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
loadJavascript("showHelpBubble()");
}
}, 2000);
}
KeyboardEventHandler.notifyListeners(kbEventListeners, keyboardType, EventType.KEYBOARD_CHANGED, currentKeyboard);
return retVal;
}
public void setChirality(boolean flag) {
this.isChiral = flag;
}
public boolean getChirality() {
return this.isChiral;
}
// Display localized Toast notification that keyboard selection failed, so loading default keyboard.
// Also sends a message to Sentry (not localized)
private void sendError(String packageID, String keyboardID, String languageID, boolean reportToSentry) {
this.currentKeyboardErrorReports++;
if(this.currentKeyboardErrorReports == 1) {
BaseActivity.makeToast(context, R.string.fatal_keyboard_error_short, Toast.LENGTH_LONG, packageID, keyboardID, languageID);
}
if(this.currentKeyboardErrorReports < 5 && reportToSentry) {
// We'll only report up to 5 errors in a given keyboard to avoid spamming
// errors and using unnecessary bandwidth doing so
// Don't use localized string R.string.fatal_keyboard_error msg for Sentry
String msg = KMString.format("Error in keyboard %1$s:%2$s for %3$s language.",
packageID, keyboardID, languageID);
Sentry.captureMessage(msg);
}
}
// Set the base path of the keyboard depending on the package ID
private void setKeyboardRoot(String packageID) {
if (packageID.equals(KMManager.KMDefault_UndefinedPackageID)) {
this.keyboardRoot = (context.getDir("data", Context.MODE_PRIVATE).toString() +
File.separator + KMManager.KMDefault_UndefinedPackageID + File.separator);
} else {
this.keyboardRoot = (context.getDir("data", Context.MODE_PRIVATE).toString() +
File.separator + KMManager.KMDefault_AssetPackages + File.separator + packageID + File.separator);
}
}
public String getKeyboardRoot() {
return this.keyboardRoot;
}
private String makeKeyboardPath(String packageID, String keyboardID, String keyboardVersion) {
String keyboardPath;
if (packageID.equals(KMManager.KMDefault_UndefinedPackageID)) {
keyboardPath = getKeyboardRoot() + keyboardID + "-" + keyboardVersion + ".js";
} else {
keyboardPath = getKeyboardRoot() + keyboardID + ".js";
}
return keyboardPath;
}
private void sendKMWError(int lineNumber, String sourceId, String message) {
if (Sentry.isEnabled()) {
Breadcrumb breadcrumb = new Breadcrumb();
breadcrumb.setMessage("KMKeyboard.sendKMWError");
breadcrumb.setCategory("KMWError");
breadcrumb.setLevel(SentryLevel.ERROR);
// Error info
breadcrumb.setData("cm_lineNumber", lineNumber);
breadcrumb.setData("cm_sourceID", sourceId);
breadcrumb.setData("cm_message", message);
// Keyboard info
if (keyboardType == KeyboardType.KEYBOARD_TYPE_INAPP) {
breadcrumb.setData("keyboardType", "INAPP");
} else if (keyboardType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
breadcrumb.setData("keyboardType", "SYSTEM");
} else {
breadcrumb.setData("keyboardType", "UNDEFINED");
}
if (this.packageID != null) {
breadcrumb.setData("packageID", this.packageID);
}
if (this.keyboardID != null) {
breadcrumb.setData("keyboardID", this.keyboardID);
}
if (this.keyboardName != null) {
breadcrumb.setData("keyboardName", this.keyboardName);
}
if (this.keyboardVersion != null) {
breadcrumb.setData("keyboardVersion", this.keyboardVersion);
}
Sentry.addBreadcrumb(breadcrumb);
//
// We now rely on Sentry within KMW to capture these errors
// We'll continue to capture breadcrumbs so we can associate
// java-side errors with javascript-side errors.
//Sentry.captureMessage(message, SentryLevel.ERROR);
//
}
}
/**
* Extract Unicode numbers (\\u_xxxx_yyyy) from a layer to character string.
* Ignores empty strings and layer names
* Refer to web/source/osk/oskKey.ts
* @param ktext Unicode string in the format \\uxxxx_yyyy
* @return String to display on subkey
*/
protected String convertKeyText(String ktext) {
String title = "";
String[] values = ktext.split("\\\\u");
int length = values.length;
for (int j = 0; j < length; j++) {
if (!values[j].isEmpty() && !values[j].contains("-")) {
// Split U_xxxx_yyyy
String[] codePoints = values[j].split("_");
for (String codePoint : codePoints) {
int codePointValue = Integer.parseInt(codePoint, 16);
if ((0x0 <= codePointValue && codePointValue <= 0x1F) || (0x80 <= codePointValue && codePointValue <= 0x9F)
|| (codePointValue > 0x10FFFF)) {
continue;
} else {
title += new String(Character.toChars(codePointValue));
}
}
}
}
return title;
}
private void saveCurrentKeyboardIndex() {
SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(KMManager.KMKey_UserKeyboardIndex, KMManager.getCurrentKeyboardIndex(context));
editor.commit();
}
/**
* getFontFilename
* Parse a Font JSON object and return the font filename (ending in .ttf or .otf)
* @param fontObj JSONObject - Font JSON object
* @return String - Filename for the font. If font is invalid, return ""
*/
private String getFontFilename(JSONObject fontObj) {
String font = "";
if (fontObj == null) {
return font;
}
try {
JSONArray sourceArray = fontObj.optJSONArray(KMManager.KMKey_FontFiles);
if (sourceArray != null) {
String fontFile;
int length = sourceArray.length();
for (int i = 0; i < length; i++) {
fontFile = sourceArray.getString(i);
if (FileUtils.hasFontExtension(fontFile)) {
font = fontFile;
break;
}
}
} else {
String fontFile = fontObj.optString(KMManager.KMKey_FontFiles);
if (fontFile != null) {
if (FileUtils.hasFontExtension(fontFile)) {
font = fontFile;
}
}
}
} catch (JSONException e) {
KMLog.LogException(TAG, "", e);
font = "";
}
return font;
}
@SuppressLint("InflateParams")
private void showSuggestionLongpress(Context context) {
if(suggestionJSON == null || suggestionMenuWindow != null) {
return;
}
// Construct from resources.
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.predictive_submenu, null, false);
suggestionMenuWindow = new PopupWindow(contentView, 300, 120, false);
suggestionMenuWindow.setFocusable(false);
suggestionMenuWindow.setContentView(contentView);
Button rotateSuggestions = contentView.findViewById(R.id.rotateSuggestionBtn);
rotateSuggestions.setClickable(false);
// Compute the actual display position (offset coordinate by actual screen pos of kbd)
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
int posX, posY;
if (keyboardType == KeyboardType.KEYBOARD_TYPE_INAPP) {
int[] kbPos = new int[2];
KMKeyboard.this.getLocationOnScreen(kbPos);
posX = (int) (this.suggestionWindowPos[0] * density);
posY = kbPos[1] + (int) (this.suggestionWindowPos[1] * density);
} else {
int[] kbPos = new int[2];
KMKeyboard.this.getLocationInWindow(kbPos);
posX = (int) (this.suggestionWindowPos[0] * density);
posY = kbPos[1] + (int) (this.suggestionWindowPos[1] * density);
}
suggestionMenuWindow.setTouchable(true);
suggestionMenuWindow.setTouchInterceptor(new View.OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (action == MotionEvent.ACTION_UP) {
// int count = ((ViewGroup) v).getChildCount();
// for (int i = 0; i < count; i++) {
// FrameLayout frame = (FrameLayout) ((ViewGroup) v).getChildAt(i);
// Button button = (Button) frame.getChildAt(0);
// if (button.isPressed()) {
// button.performClick();
// break;
// }
// }
dismissSuggestionMenuWindow();
} else if (action == MotionEvent.ACTION_MOVE) {
// int count = ((ViewGroup) v).getChildCount();
// for (int i = 0; i < count; i++) {
// FrameLayout frame = (FrameLayout) ((ViewGroup) v).getChildAt(i);
// Button button = (Button) frame.getChildAt(0);
// int[] pos = new int[2];
// button.getLocationOnScreen(pos);
// Rect rect = new Rect();
// button.getDrawingRect(rect);
// rect.offset(pos[0], pos[1]);
// if (rect.contains(tx, ty)) {
// button.setPressed(true);
// } else {
// button.setPressed(false);
// }
// }
}
return false;
}
});
suggestionMenuWindow.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
suggestionJSON = null;
suggestionMenuWindow = null;
String jsString = "popupVisible(0)";
loadJavascript(jsString);
}
});
suggestionMenuWindow.showAtLocation(KMKeyboard.this, Gravity.TOP | Gravity.LEFT, posX , posY);
String jsString = "popupVisible(1)";
loadJavascript(jsString);
return;
}
@SuppressLint({"InflateParams", "ClickableViewAccessibility"})
private void showSubKeys(Context context) {
if (subKeysList == null || subKeysWindow != null) {
return;
}
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
String[] pos = subKeysWindowPos;
int x = (int) (Float.valueOf(pos[0]) * density);
int y = (int) (Float.valueOf(pos[1]) * density);
// Calculate desired size for subkey display, # of rows/cols, etc.
int kbWidth = getWidth();
float pvWidth, pvHeight;
float margin = getResources().getDimension(R.dimen.popup_margin);
int padding = getResources().getDimensionPixelSize(R.dimen.popup_padding);
int rows, columns;
float buttonWidth = getResources().getDimension(R.dimen.key_width);
float buttonHeight = getResources().getDimension(R.dimen.key_height);
float arrowWidth = getResources().getDimension(R.dimen.popup_arrow_width);
float arrowHeight = getResources().getDimension(R.dimen.popup_arrow_height);
float offset_y = getResources().getDimension(R.dimen.popup_offset_y);
//int orientation = getResources().getConfiguration().orientation;
//columns = (orientation == Configuration.ORIENTATION_PORTRAIT)?6:10;
columns = (int) ((getWidth() - margin) / (buttonWidth + margin));
int subKeysCount = subKeysList.size();
if (subKeysCount <= columns) {
rows = 1;
pvWidth = (subKeysCount * (buttonWidth + padding)) + 2 * margin + padding;
pvHeight = (buttonHeight + padding) + 2 * margin + padding + arrowHeight;
} else {
rows = (subKeysCount / columns);
if (subKeysCount % columns > 0) {
rows++;
}
if (subKeysCount % rows == 0) {
columns = subKeysCount / rows;
} else {
int s = (columns * rows - subKeysCount) / 2;
columns -= s / (rows - 1);
}
pvWidth = (columns * (buttonWidth + padding)) + 2 * margin + padding;
pvHeight = (rows * (buttonHeight + padding)) + 2 * margin + padding + arrowHeight;
}
// Construct from resources.
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.subkeys_popup_layout, null, false);
// Configure the popover view with desired size and construct its popup "arrow."
KMPopoverView popoverView = (KMPopoverView) contentView.findViewById(R.id.kmPopoverView);
popoverView.setSize((int) pvWidth, (int) pvHeight);
popoverView.setArrowSize(arrowWidth, arrowHeight);
float px = x - pvWidth / 2.0f;
float py = y + offset_y - pvHeight;
if (px < 0) {
px = 0;
} else if ((px + pvWidth) > kbWidth) {
px = kbWidth - pvWidth;
}
if (px == 0) {
popoverView.setArrowPosX(x);
} else if (px == (kbWidth - pvWidth)) {
popoverView.setArrowPosX(x - px);
} else {
popoverView.setArrowPosX(pvWidth / 2.0f);
}
popoverView.redraw();
// Add needed subkeys to the popup view.
GridLayout grid = (GridLayout) contentView.findViewById(R.id.grid);
grid.setColumnCount(columns);
for (int i = 0; i < subKeysCount; i++) {
Button button = (Button) inflater.inflate(R.layout.subkey_layout, null);
button.setId(i + 1);
button.setLayoutParams(new FrameLayout.LayoutParams((int) buttonWidth, (int) buttonHeight));
// May as well set them here, keeping them in a closure than a prone-to-change field.
// Helps keep things from totally breaking when the event handler triggering subkey menu
// generation and the menu's event handler stop talking to each other.
final ArrayList<HashMap<String, String>> subkeyList = subKeysList;
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int index = v.getId() - 1;
String keyId = subkeyList.get(index).get("keyId");
String keyText = getSubkeyText(keyId, subkeyList.get(index).get("keyText"));
String jsFormat = "executePopupKey('%s','%s')";
String jsString = KMString.format(jsFormat, keyId, keyText);
loadJavascript(jsString);
}
});
button.setClickable(false);
// Show existing text for subkeys. If subkey text is blank, get from id
String kId = subKeysList.get(i).get("keyId");
String kText = getSubkeyText(kId, subKeysList.get(i).get("keyText"));
String title = convertKeyText(kText);
// Disable Android's default uppercasing transformation on buttons.
button.setTransformationMethod(null);
button.setText(title);
if (!specialOskFont.isEmpty()) {
button.setTypeface(KMManager.getFontTypeface(context, specialOSKFontFilename(specialOskFont)));