diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000000000000000000000000000000000000..c211bcb7f61a0f93e9c06cc7fb3df6a11eb32f7e --- /dev/null +++ b/.flake8 @@ -0,0 +1,5 @@ +[flake8] +max-line-length = 120 +ignore = + E402, # module level import not at top of file + W504, # line break after binary operator diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000000000000000000000000000000000000..7d3b6c5ac081db75f2384ed110033284e7c42dc9 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,87 @@ +# +# This file adds labels based on the scopes in resources/scopes/scopes.json. +# Currently it must be manually kept up to date. Not all labels are added, only +# common ones. The others are commented out. There is still some variance between +# folder names and labels; consider this documentation of that ;-) +# + +android/: android/** +android/app/: android/KMAPro/** +#android/browser/: +android/engine/: android/KMEA/** +#android/resources/: +android/samples/: android/Samples/** + +common/: + - common/** + - resources/** +common/core/: common/core/** +common/core/desktop/: common/core/desktop/** +common/core/web/: common/core/web/** + +common/models/: common/models/** +common/models/types/: common/models/types/** +common/models/templates/: common/models/templates/** +common/models/wordbreakers/: common/models/wordbreakers/** + +common/resources/: resources/** + +developer/: + - developer/** + - windows/src/developer/** + +developer/compilers/: + - windows/src/developer/kmcomp/** + - developer/js/** + +developer/ide/: + - windows/src/developer/TIKE/** + +# developer/resources/ +# developer/tools/ + +ios/: ios/** +ios/app/: ios/keyman/** +# ios/browser/ +ios/engine/: ios/engine/** +# ios/resources/ +ios/samples/: ios/samples/** + +linux/: linux/** +linux/config/: linux/keyman-config/** +linux/engine/: + - linux/ibus-keyman/** + - linux/ibus-kmfl/** + - linux/kmflcomp/** + - linux/libkmfl/** + - linux/scim_kmfl_imengine/** +# linux/resources/ +# linux/samples/ + +mac/: mac/** +# mac/config/: +mac/engine/: mac/** +# mac/resources/ +# mac/samples/ + +oem/: oem/** +oem/fv/: oem/firstvoices/** +oem/fv/android/: oem/firstvoices/android/** +oem/fv/ios/: oem/firstvoices/ios/** +oem/fv/windows/: oem/firstvoices/windows/** + +web/: web/** +# web/bookmarklet/ +web/engine/: web/source/** +# web/resources/ +web/ui/: web/source/kmwui* +web/samples/: web/samples/** + +# Somewhat messy since we try and exclude Developer :) +windows/: +- any: ['windows/**', '!windows/src/developer/**'] + +windows/config/: windows/src/desktop/** +windows/engine/: windows/src/engine/** +# windows/resources/ +# windows/samples/ diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 0000000000000000000000000000000000000000..1bc2f29742da0fdf29b1f842ca83a6971598e203 --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,11 @@ +name: "Pull Request Labeler" +on: +- pull_request + +jobs: + triage: + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@4b52aec09ba832eb9aecccddbccce644ba9ba69d + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" \ No newline at end of file diff --git a/.gitignore b/.gitignore index 645439b8400271f619067d3b2db20ef801979a9e..7d3fd45792d832da0ab8815e79dcf48f25710c97 100644 --- a/.gitignore +++ b/.gitignore @@ -258,3 +258,9 @@ resources/environment.sh # Copy of the master VERSION.md used for Linux packaging /common/core/desktop/VERSION.md + +**/node_modules/ +lerna-debug.log + +# Cached/auto-compiled Python bytecode +*.pyc diff --git a/HISTORY.md b/HISTORY.md index eca312efce3e82b24823f74b4352e4eb34d19568..a57940e8e92631110df7c14449df9e96a2e4f16f 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,533 @@ # Keyman Version History +## 14.0.143 alpha 2020-09-16 + +* fix(android/app): Validate language selection for "INSTALL" button (#3579) + +## 14.0.142 alpha 2020-09-15 + +* chore(deps): bump node-fetch from 2.6.0 to 2.6.1 in /resources/build/version (#3578) + +## 14.0.141 alpha 2020-09-11 + +* fix(web): default layout shift not changing layer (#3574) + +## 14.0.140 alpha 2020-09-09 + +* feat(common/models): core edit-distance calculation class (#3526) +* feat(common/models): Edit path derivation (#3547) +* feat(common/models): low-level correction-algorithm infrastructure (#3527) +* feat(common/models): correction-search algorithm core (#3534) + +## 14.0.139 alpha 2020-09-04 + +* fix(windows): BCP 47 tag canonicalization (#3545) +* fix(windows): upgrade of profiles from 13.0 (#3552) + +## 14.0.138 alpha 2020-09-02 + +* feat(windows): map installed bcp47 (#3542) +* fix(windows): simplify profile uninstall (#3543) +* fix(android/app): Remove unused intent ACTION_GET_USERDATA (#3551) +* fix(android/engine): Remove notification after installing kbd package (#3546) +* fix(android): Re-enable monitoring of Application Not Responding (ANR) (#3550) + +## 14.0.137 alpha 2020-08-31 + +* fix(android/engine): Fix package filename when downloading from cloud (#3541) +* feat(windows): select language at keyboard install (#3524) +* feat(windows): add langtags.json data (#3529) +* fix(windows): add transient profile support to keyman32 (#3539) + +## 14.0.136 alpha 2020-08-28 + +* fix(android/app): Inject meta viewport tag for viewing help (#3523) +* fix(android/app): Fix overflow menu for hdpi devices (#3532) +* feat(windows): Rework of profile installation - Engine (#3509) +* feat(windows): profile installation - Keyman for Windows (#3510) +* feat(windows): profile installation - Support Tool (#3511) +* chore(windows): remove stockeditor (#3516) +* fix(windows): refresh configuration after changes (#3517) +* feat(windows): split language registration on app install (#3520) +* fix(linux): Improve robustness when installing ibus-keyman (#3535) + +## 14.0.135 alpha 2020-08-27 + +* feat(common/models): override script defaults: spaces break words (#3506) +* fix(android/engine): Check asset package version before installing (#3514) +* feat(android): Use Stepper for navigating package installation steps (#3498) + +## 14.0.134 alpha 2020-08-26 + +* [linux] Add packaging of Linux localization files (#3504) + +## 14.0.133 alpha 2020-08-25 + +* feat(common/models): lexicon traversal (#3479) +* feat(common/models): actual priority queue for Trie models (#3480) +* feat(common/models): efficient batch-enqueue (#3486) + +## 14.0.132 alpha 2020-08-24 + +* feat(linux): Small UI improvements (#3495) + +## 14.0.131 alpha 2020-08-21 + +* feat(android/app): Add language picker for keyboard package installation (#3481) + +## 14.0.130 alpha 2020-08-19 + +* fix(android): Fix util to getting the tier on CI builds (#3491) + +## 14.0.129 alpha 2020-08-17 + +* feat(windows): rework download keyboard dialog style (#3463) +* chore: Add sample vscode settings files (#3249) +* fix(linux): Lookup language tag from keyboard (#3408) + +## 14.0.128 alpha 2020-08-13 + +* feat(linux): Hook up Sentry for km-config (#3378) +* chore(linux): Use new staging site names and use variable for downloads.keyman.com (#3406) + +## 14.0.127 alpha 2020-08-12 + +* refactor(common/models): LMLayer state management tweak, persistent ModelCompositor (#3477) + +## 14.0.126 alpha 2020-08-10 + +* fix(android): Add CI script to publish to Play Store (#3469) +* fix(android): Update sentry plugin to remove obsolete API use (#3471) +* feat(ios/app): universal links for keyboard installation (#3466) +* fix(ios/engine): Proper associating-installer deinitialization, cancellation tests (#3468) +* refactor(ios): error definitions, i18n (#3470) +* chore: cleanup keyboardprocessor.h.in (#3473) + +## 14.0.125 alpha 2020-08-07 + +* fix(android): Update Gradle wrapper to 5.6.4 (#3467) +* feat(ios/engine): Associating package installer (#3458) +* feat(ios/app): Associating package installer use within existing install paths (#3465) + +## 14.0.124 alpha 2020-08-06 + +* feat(windows): set default UI language at install (#3438) +* feat(windows): i18n for Setup (#3444) +* feat(windows): add globe icon to Configuration UI (#3446) +* feat(windows): set UI language from Setup preference on first install (#3447) +* feat(windows): docs on editing translations (#3448) +* Modify/android/improve string context (#3457) +* fix(android/app): Fix environment portion of app version string (#3462) + +## 14.0.123 alpha 2020-08-05 + +* feat(android): Use staging help site for pre-release builds (#3453) +* fix(android): Cleanup string formatting with strings.xml (#3452) +* chore(android): Add script to find unused strings. Manually remove them (#3456) +* feat(ios/engine): LanguagePickAssociator progress tracking, base integration with package lang picker (#3455) + +## 14.0.122 alpha 2020-08-04 + +* feat(android/app): Associate app with /keyboards/install links (#3449) +* fix(android): Update KMPBrowser to pass external links to user browser (#3439) +* feat(ios/engine): Language-pick associator (#3451) + +## 14.0.121 alpha 2020-08-03 + +* fix(android): Fix KMTextView to compile on Linux (#3442) + +## 14.0.120 alpha 2020-07-31 + +* feat(android): Use api.keyman-staging.com for pre-release builds (#3423) +* refactor(ios/engine): merges keyboard & lexical model info views, fixes QR code logic (#3432) +* feat(android): Add app association to keyman.com (#3431) +* chore(windows): cleanup comments in strings.xml (#3434) +* feat(ios/engine): language selection during (file-based) package installation (#3416) +* feat(ios/engine) Package-installer layout optimizations (#3437) + +## 14.0.119 alpha 2020-07-30 + +* feat(windows): convert locale.xml to strings.xml format (#3424) +* refactor(windows): add translations to windows install (#3428) +* refactor(windows): remove old locale links (#3429) +* chore(windows): remove old locale tools (#3430) +* feat(ios): Start of engine and app internationalization (#2745) + +## 14.0.118 alpha 2020-07-29 + +* fix(android/app): Use go/android/ links to download cloud keyboards (#3343) +* fix(windows): i18n of strings in Font Helper (#3414) +* refactor(windows): refactor Dialog elements (#3421) +* chore(windows): Remove usage page resources (#3422) + +## 14.0.117 alpha 2020-07-28 + +* feat(windows): i18n groundwork (#3411) +* feat(windows): Removes unused strings from locale.xml (#3412) +* refactor(ios/engine): package installer tweaks (#3410) +* chore(ios/engine): more obsoletions (#3407) + +## 14.0.116 alpha 2020-07-24 + +* refactor(ios/engine): builds package download links (#3383) +* refactor(ios/engine): chained lexical model install callback, fix (#3388) +* feat(ios/engine): download queue concurrency (#3395) +* feat(ios/engine): keyboard search core (#3384) +* feat(ios/engine): support for deferred chaining of lexical model downloads (#3401) +* docs(linux): Update readme (#3397) +* feat(ios/engine): use of Keyman staging sites (#3405) +* feat(linux): keyman:// protocol handler (#3398) +* chore(ios/engine): dead code removal + deprecations (#3402) + +## 14.0.115 alpha 2020-07-23 + +* feat(windows): keyman: protocol handler (#3382) +* feat(developer/compilers): logging errors and warnings in the lexical model compiler (#3385) + +## 14.0.114 alpha 2020-07-22 + +* chore(deps): bump lodash from 4.17.15 to 4.17.19 in /web/testing/regression-tests (#3360) + +## 14.0.113 alpha 2020-07-21 + +* refactor(ios/engine): update detection now based upon packages (#3362) +* refactor(ios/engine): package download notifications (#3363) +* refactor(ios/engine): package-based resource updates, cloud resource migration (#3372) +* fix(ios/engine): engine tier enum, proper detection (#3373) +* refactor(ios/engine): Centralized Keyman domain definitions (#3381) +* fix(linux): Use language from search when installing keyboard (#3290) +* refactor(linux): Small refactorings (#3376) +* refactor(developer/compilers): reading from a wordlist (#3380) + +## 14.0.112 alpha 2020-07-20 + +* refactor(ios/engine): package-version query caching + package state properties (#3335) +* refactor(ios/engine): keyboard downloads now retrieve KMPs (#3341) +* refactor(ios/engine): download queue & download state detection cleanup (#3342) +* chore(developer): cleanup test constants (#3350) +* change(common/models/wordbreakers): update word boundary props to 13.0 (#3365) +* feat(linux): Use staging URLs for alpha version (#3364) + +## 14.0.111 alpha 2020-07-16 + +* fix(android/engine): Update deprecated call to switch system keyboard for Android P (#3353) + +## 14.0.110 alpha 2020-07-15 + +* refactor(developer): hashmap-based wordlist compilation (#3340) +* chore(linux): Add license details for kmpdetails.* (#3355) + +## 14.0.109 alpha 2020-07-14 + +* refactor(ios/engine): lexical model query & download rework (#3327) +* refactor(ios/engine): hashable package keys (#3333) +* fix(ios/engine): version equality (#3334) +* refactor(linux): make some methods protected (#3291) +* feat(android/oem): Add nrc.str.sencoten model and update SystemKeyboard from KMAPro (#3332) + +## 14.0.108 alpha 2020-07-09 + +* chore: cleanup global ExtPath (#3315) +* feat(android): Use build-download-resources.sh for KMApro and FV apps (#3322) +* refactor(ios/engine): Centralized package download utility function (#3299) +* fix(android/oem): Add a fallback keyboard to FV Android app (#3323) + +## 14.0.107 alpha 2020-07-08 + +* feat(android): Add additional info on installed keyboards exceptions (#3319) + +## 14.0.106 alpha 2020-07-04 + +* fix(android/app) Download associated dictionary when installing cloud keyboard package (#3307) + +## 14.0.105 alpha 2020-07-03 + +* feat(android): Download default resources at build time (#3300) +* fix(android/engine): Fix unbound variable in build script (#3308) + +## 14.0.104 alpha 2020-07-01 + +* fix(android): Resize PackageActivity title text (#3297) + +## 14.0.103 alpha 2020-06-30 + +* fix(common/core/web): fixes transcription buffer cap (#3301) + +## 14.0.102 alpha 2020-06-29 + +* fix(android): Use tier to determine keyboard search host (#3296) +* refactor(ios/engine): Resource download cleanup and mocking prep (#3292) +* refactor(ios/engine): ID-based download tracking, update notification rework (#3295) + +## 14.0.101 alpha 2020-06-26 + +* feat(linux): address code review comments of #3278 (#3281) +* fix(linux): Always restart IBus when installing keyboard (#3284) +* refactor(linux): cleanup code (#3286) +* fix(linux): Fix crash converting kvk into LDML (#3288) +* feat(ios/engine): package-version query implementation (#3280) + +## 14.0.100 alpha 2020-06-25 + +* refactor(ios/engine): Download notifications via completion blocks (#3274) +* refactor(ios/engine): better resource type links (#3276) +* refactor(ios/engine): Resource-download installation closures (#3277) +* feat(linux): Install keyboard on Gnome (#3278) + +## 14.0.99 alpha 2020-06-24 + +* feat(ios/engine): adds getInstalledPackage(for:) (#3270) +* refactor(linux): address code review comments of #3272 (#3275) + +## 14.0.98 alpha 2020-06-23 + +* refactor(ios/engine): reworks download queue objects (#3267) +* feat(linux): Improve Linux package description (#3268) + +## 14.0.97 alpha 2020-06-22 + +* feat(android): Implement menu to add language for installed keyboard pkg (#3255) +* fix(mac/resources): altool is failing but we lose the log in CI (#3264) +* refactor(ios/engine): more notification rework prep (#3262) +* fix(mac): altool second call report ci errors (#3265) +* refactor(ios/engine): more dead code removal (#3266) + +## 14.0.96 alpha 2020-06-19 + +* fix(ios/engine): fixes keyboard swapping (#3259) +* fix(common/resources): shebang for lerna-based Linux builds (#3260) +* refactor(ios/engine): Notification rework prep, simplification (#3261) + +## 14.0.95 alpha 2020-06-19 + +* feat(android/app): Consolidate install menus (#3245) +* change(ios/engine): migrates legacy cloud resources to KMP format (#3237) +* change(ios/engine): Default resource update (#3244) +* fix(ios/engine): migration of preload-sourced resources (#3247) +* refactor(common/resources): web-environment package (#3248) +* chore(linux): Add some unit tests for keyman_config (#3250) +* chore(linux): Update automatically installed dependencies (#3254) +* fix(common/resources): web-environment package-lock.json (#3256) + +## 14.0.94 alpha 2020-06-16 + +* feat(linux): Add onboard as recommended package (#3241) + +## 14.0.93 alpha 2020-06-15 + +* fix(developer/ide): double click to change layer update combo (#3240) +* fix(developer/ide): fix copy and paste in touch editor (#3238) + +## 14.0.92 alpha 2020-06-12 + +* change(ios/engine): Package migration prep (#3229) +* chore: labeler (#3233) +* feat(android/engine): Migrate cloud keyboards when updating keyboard package (#3221) +* refactor(ios/engine): explicitly synchronous Package processing (#3230) +* feat(ios/engine): KeymanPackage now parses its ID (#3234) +* fix(windows): sentry exception reports (#3235) + +## 14.0.91 alpha 2020-06-11 + +* chore(android): Remove google-services and update readme (#3228) + +## 14.0.90 alpha 2020-06-10 + +* refactor(ios/engine): Language resource + keying polymorphism (#3220) +* refactor(ios): Selective resource installation via abstraction (#3207) +* feat(ios/engine): Generation of kmp.json for non-package resources (#3212) + +## 14.0.89 alpha 2020-06-09 + +* fix(android/engine): Revise updateOldKeyboardsList (#3216) +* feat(ios/engine): embedded KeymanWeb engine Sentry use (#3218) +* feat(android): Handle model picker updates (#3209) + +## 14.0.88 alpha 2020-06-08 + +* modify(android/samples): Update addKeyboard syntax for Sample and Test apps (#3213) +* fix(linux): Restart km-config after installing keyboard (#3214) + +## 14.0.87 alpha 2020-06-05 + +* fix(developer/compilers): normalise touch layout on compile (#3203) +* feat(android): Add utility to check BCP47 equivalence (#3210) +* refactor(ios/engine): KMP installation now relies on KeymanPackage class, parses (#3205) +* refactor(ios/engine): Abstraction of KMP installation methods (#3206) +* feat(linux): Make two windows modal dialogs (#3211) + +## 14.0.86 alpha 2020-06-02 + +* fix(ios): fixes lerna concurrency workaround and missing func reference (#3192) +* fix(android/engine): Use available models for ModelPickerActivity() (#3191) +* feat(android): Add system globe action to show system keyboards (#3197) +* feat(linux): Open a .kmp file in km-config (#3183) +* refactor(ios/engine): kmp.json - Keyboard info deserialization (#3193) +* refactor(ios/engine): kmp.json - Lexical model info deserialization (#3195) +* feat(ios/engine): kmp.json - full deserialization (#3198) +* fix(android): Add wrapper for logging errors & exceptions (#3196) +* fix(oem/fv/ios): new certificate (#3201) + +## 14.0.85 alpha 2020-05-30 + +* modify(android/engine): Clean up naming for formatting QR code URL (#3187) + +## 14.0.84 alpha 2020-05-29 + +* change(web): Selective Sentry uploads (#3163) +* refactor(ios/engine): Polishes HTTPDownloader to prep for unit testing (#3179) +* feat(ios/engine): HTTPDownloader unit testing (#3180) +* fix(linux): Disable buttons if no keyboard installed (#3184) +* change(ios/engine): Removes unused, deprecated JS/JSON-based adhoc install code (#3186) +* change(common/lmlayer): move joiner from LMLayer to model compiler (#3071) + +## 14.0.83 alpha 2020-05-28 + +* change(ios): Selective Sentry uploads (#3162) +* Fix/android/package updates (#3175) +* fix(common/models/types): fixes models-types build script, sets std header (#3182) + +## 14.0.82 alpha 2020-05-27 + +* fix(ios): fixes build warning on Error coersion, fixes logged error for intermediate embedded state (#3173) +* fix(linux): Don't fail (un-)install if running multiple ibus (#3169) +* chore(linux): Update maintainer in package metadata (#3168) +* feat(linux): Improve appstream metadata (#3176) + +## 14.0.81 alpha 2020-05-27 + +* refactor(resources): convert gosh into npm package 🙃 (#3159) +* chore(common,web): use consistent TypeScript dep on all packages (#3158) +* chore(common/resources): add `common/models` to build trigger definitions (#3144) +* fix(common): adds package-lock.json for gosh package (#3171) + +## 14.0.80 alpha 2020-05-25 + +* fix(android/engine): Remove LanguageListUtil (#3155) +* refactor(common/lmlayer): create package: @keymanapp/models-templates (#3128) + +## 14.0.79 alpha 2020-05-22 + +* fix(android): Fix system keyboard globe button override (#3140) +* fix(web/utils): use build script to generate environment.inc.ts (#3146) +* change(common/core/web,web): update deps to @keymanapp/models-types (#3147) + +## 14.0.78 alpha 2020-05-21 + +* refactor(common/models): factor out word breakers to their own package (#3125) +* fix(developer): crash when developer starts (#3138) +* modify(android): Refactor KeyboardPickerActivity (#3113) +* chore(common/resources): cleanup scopes (#3139) +* feat(web): starts proper KMW Sentry integration (#3122) +* refactor(common/models/types): rename @keymanapp/lexical-model-types => @keymanapp/models-types (#3143) +* change(web/utils): add and distribute type declaration (#3145) +* fix(common): drops version updates for deprecated common/lexical-model-types (#3148) + +## 14.0.77 alpha 2020-05-19 + +* refactor(web/engine): Moves common utility functions into separate `web-utils` package (#3130) +* refactor(web/engine): renames DeviceSpec, moves to utils (#3132) +* fix(ios): Fixes keyboard metadata decoding, tweaks to project files (#3137) +* feat(windows): Use http: instead of file: for Configuration UI (#3127) + +## 14.0.76 alpha 2020-05-15 + +* fix(windows): use correct name for Sentry in C++ (#3129) +* chore: Allow to override hook defs (#3112) + +## 14.0.75 alpha 2020-05-13 + +* feat(android): Add Tamil lexical model to KMSample2 (#3123) + +## 14.0.74 alpha 2020-05-11 + +* fix(windows): kmbrowserhost was missing debug info (#3117) + +## 14.0.73 alpha 2020-05-11 + +* fix(windows): force output keystroke failure (#3083) +* fix(windows): kmshell title and kmbrowserhost sentry (#3115) + +## 14.0.72 alpha 2020-05-08 + +* fix(ios/oem): Fixes FV app's system keyboard (#3105) +* fix(ios/oem): FV light mode lock and basic banner fix (#3108) +* fix(windows): sentry cef shutdown interactions (#3107) +* feat(android): Migrate installed keyboards list to keyboards_list.json (#3091) + +## 14.0.71 alpha 2020-05-08 + +* fix(windows): use consistent sentry db location (#3100) + +## 14.0.70 alpha 2020-05-07 + +* fix(android): Fix back button after System Keyboard dismissed (#3093) +* fix(android): Back button to dismiss KMSample2 system keyboard (#3095) +* fix(oem): Back button to dismiss FV Android system keyboard (#3096) + +## 14.0.69 alpha 2020-05-06 + +* fix(common): npm install required for auto inc lerna versions (#3089) +* fix(windows): sentry x64 stacks truncated pointers (#3087) + +## 14.0.68 alpha 2020-05-06 + +* fix(common): enable build for win x64, use global VERSION.md and fix decxstr() bug (#3076) +* modify(android): Add methods to go between LanguageResource and JSON (#3079) +* feat(common): auto-update for package versioning (#3078) + +## 14.0.67 alpha 2020-05-05 + +* fix(ios): Additional libraries for FirstVoices SWKeyboard (#3080) + +## 14.0.66 alpha 2020-05-04 + +* feat(web): test Recorder overhaul, Node-based tests using Recorder for KeyboardProcessor (#3060) +* fix(ios): fv add sentry framework to carthage build step (#3074) + +## 14.0.65 alpha 2020-05-03 + +* fix(ios): try embed of sentry again for fv (#3072) + +## 14.0.64 alpha 2020-05-01 + +* fix(ios): add sentry framework to fv keyboards (#3069) + +## 14.0.63 alpha 2020-05-01 + +* fix(android): Fix FileUtilsTest to be cross-platform (#3061) +* fix(windows): add LARGEADDRESSAWARE flag for all CEF processes (#3064) +* Fix/android/remove more custom (#3051) +* fix(ios): FV settings bundle for SWKeyboard (#3066) +* change(common/lmlayer): single-pass join word breaker decorator (#3059) + +## 14.0.62 alpha 2020-05-01 + +* modify(oem): Update DSN for FV Android app (#3050) +* feat(web/engine): Basic KeyboardProcessor tests (#2994) +* fix(oem,common): Update FirstVoices build_keyboards.sh script (#3045) + +## 14.0.61 alpha 2020-04-30 + +* chore(deps): bump @actions/http-client from 1.0.3 to 1.0.8 in /resources/build/version (#3047) +* fix(ios): firstvoices icon and version info (#3044) +* feat(windows): Sentry integration fixes and polish (#3006) +* feat(common/lmlayer): compile joinWordsAt property (#3032) + +## 14.0.60 alpha 2020-04-29 + +* feat(common): initial use of lerna (in-repo package links only) (#2997) +* change(web/engine): spins core/web/keyboard-processor package off from KeymanWeb (#3001) +* change(web/engine): spins core/web/input-processor package off from KeymanWeb (#3008) +* chore(common/lmlayer): change author from personal to work affiliation (#3046) + +## 14.0.59 alpha 2020-04-29 + +* chore: merge stable history (#3037) +* feat(common/lmlayer): create join word breaker decorator (#3021) +* fix(ios): download fv keyboards (#3040) +* modify(android): Refactor LanguageResource() and remove "Custom" property (#3033) + ## 14.0.58 alpha 2020-04-28 * change(common/lmlayer): improvements to default searchTermToKey (#3024) diff --git a/README.md b/README.md index f3e24fb61b6ee48b192dc6b85b1bb2bdb237b6ac..819500203d2222d3f30b41a1fa7f62a112643daf 100644 --- a/README.md +++ b/README.md @@ -69,3 +69,9 @@ Licensed under the [MIT](./windows/src/LICENSE.md) License. [linux-master]: https://build.palaso.org/app/rest/builds/buildType:(id:KeymanLinux_Master)/statusIcon [linux-beta]: https://build.palaso.org/app/rest/builds/buildType:(id:KeymanLinux_Beta)/statusIcon [linux-stable]: https://build.palaso.org/app/rest/builds/buildType:(id:KeymanLinux_Stable),branch:(default:false)/statusIcon + +# Notes for Contributors + +When cloning this repo for local development on a Windows machine, take care not to place it overly deep in your file system. +Some of the paths for compilation can push character lengths around 160 characters long, while certain operations on Windows systems may be limited to paths of 260 characters or less. +For example, [`git clean` on Windows with msys](https://stackoverflow.com/questions/22575662/filename-too-long-in-git-for-windows/22575737#22575737) is limited due to dependence on older Windows APIs. \ No newline at end of file diff --git a/VERSION.md b/VERSION.md index bee978e91bf3f8ee26b733c61869d54ee32987be..7450c6cae75b7edfa8797ae12cf7e7aa4f6df36d 100644 --- a/VERSION.md +++ b/VERSION.md @@ -1 +1 @@ -14.0.59 \ No newline at end of file +14.0.144 \ No newline at end of file diff --git a/android/.gitignore b/android/.gitignore index 86142772fef2471971059e4863a2e69008c92944..a502ae727d269966237c9bf27c041489d63b2fe5 100644 --- a/android/.gitignore +++ b/android/.gitignore @@ -34,6 +34,9 @@ gradle_models.ser KMEA/app/src/main/assets/ KMAPro/assets/keyman.js +# KMAPRo default packages +KMAPro/**/assets/*.kmp + # Eclipse files .project .settings/ diff --git a/android/KMAPro/build.gradle b/android/KMAPro/build.gradle index 051f23297c9cd0f2ec15d9f07a1ee76043c62503..afcdfe36c087820ce913203fca2aca653476ae35 100644 --- a/android/KMAPro/build.gradle +++ b/android/KMAPro/build.gradle @@ -7,9 +7,9 @@ buildscript { } dependencies { classpath 'com.android.tools.build:gradle:3.5.2' - classpath 'com.google.gms:google-services:4.3.2' - classpath 'io.sentry:sentry-android-gradle-plugin:1.7.31' + classpath 'io.sentry:sentry-android-gradle-plugin:1.7.35' classpath 'name.remal:gradle-plugins:1.0.157' + classpath 'com.stepstone.stepper:material-stepper:4.3.1' } } diff --git a/android/KMAPro/build.sh b/android/KMAPro/build.sh index 86750207e02705565771ddaa69d1f777d6e1ac9e..18982a7c10664e710fc38facf413a44005a8f1f3 100755 --- a/android/KMAPro/build.sh +++ b/android/KMAPro/build.sh @@ -1,14 +1,21 @@ #!/bin/bash # Build KMAPro -display_usage ( ) { - echo "build.sh [-no-daemon] [-debug]" - echo - echo "Build Keyman for Android" - echo " -no-daemon Don't start the Gradle daemon. Use for CI" - echo " -debug Compile only Debug variant" - exit 1 -} +# Set sensible script defaults: +# set -e: Terminate script if a command returns an error +set -e +# set -u: Terminate script if an unset variable is used +set -u +# set -x: Debugging use, print each statement +# set -x + +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../resources/build/build-utils.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +. "$KEYMAN_ROOT/resources/build/build-download-resources.sh" echo Build KMAPro @@ -17,8 +24,20 @@ echo Build KMAPro # SHLVL=0 +display_usage ( ) { + echo "build.sh [-no-daemon] [-debug] [-download-resources]" + echo + echo "Build Keyman for Android" + echo " -no-daemon Don't start the Gradle daemon. Use for CI" + echo " -debug Compile only Debug variant" + echo " -download-resources Download sil_euro_latin.kmp and nrc.en.mtnt.model.kmp from downloads.keyman.com" + exit 1 +} + NO_DAEMON=false ONLY_DEBUG=false +DO_KEYBOARDS_DOWNLOAD=false +DO_MODELS_DOWNLOAD=false # Parse args while [[ $# -gt 0 ]] ; do @@ -30,6 +49,10 @@ while [[ $# -gt 0 ]] ; do -debug) ONLY_DEBUG=true ;; + -download-resources) + DO_KEYBOARDS_DOWNLOAD=true + DO_MODELS_DOWNLOAD=true + ;; -h|-?) display_usage ;; @@ -37,9 +60,27 @@ while [[ $# -gt 0 ]] ; do shift # past argument done +KEYBOARD_PACKAGE_ID="sil_euro_latin" +KEYBOARDS_TARGET="$KEYMAN_ROOT/android/KMAPro/kMAPro/src/main/assets/${KEYBOARD_PACKAGE_ID}.kmp" +MODEL_PACKAGE_ID="nrc.en.mtnt" +MODELS_TARGET="$KEYMAN_ROOT/android/KMAPro/kMAPro/src/main/assets/${MODEL_PACKAGE_ID}.model.kmp" + +# Verify default keyboard and dictionary exist +if [[ ! -f "$KEYBOARDS_TARGET" ]]; then + echo "$KEYBOARDS_TARGET doesn't exist. Will download the latest version" + DO_KEYBOARDS_DOWNLOAD=true +fi + +if [[ ! -f "$MODELS_TARGET" ]]; then + echo "$MODELS_TARGET doesn't exist. Will download the latest version" + DO_MODELS_DOWNLOAD=true +fi + echo echo "NO_DAEMON: $NO_DAEMON" echo "ONLY_DEBUG: $ONLY_DEBUG" +echo "DO_KEYBOARDS_DOWNLOAD: $DO_KEYBOARDS_DOWNLOAD" +echo "DO_MODELS_DOWNLOAD: $DO_MODELS_DOWNLOAD" echo if [ "$NO_DAEMON" = true ]; then @@ -48,6 +89,16 @@ else DAEMON_FLAG= fi + +# Download default keyboard and dictionary +if [ "$DO_KEYBOARDS_DOWNLOAD" = true ]; then + downloadKeyboardPackage "$KEYBOARD_PACKAGE_ID" "$KEYBOARDS_TARGET" +fi + +if [ "$DO_MODELS_DOWNLOAD" = true ]; then + downloadModelPackage "$MODEL_PACKAGE_ID" "$MODELS_TARGET" +fi + if [ "$ONLY_DEBUG" = true ]; then BUILD_FLAGS="assembleDebug lintDebug" else diff --git a/android/KMAPro/gradle/wrapper/gradle-wrapper.jar b/android/KMAPro/gradle/wrapper/gradle-wrapper.jar index 8c0fb64a8698b08ecc4158d828ca593c4928e9dd..5c2d1cf016b3885f6930543d57b744ea8c220a1a 100644 Binary files a/android/KMAPro/gradle/wrapper/gradle-wrapper.jar and b/android/KMAPro/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/KMAPro/gradle/wrapper/gradle-wrapper.properties b/android/KMAPro/gradle/wrapper/gradle-wrapper.properties index 53d1d37d023c805809fd6b0fb99d8a387f079617..5028f28f8e4755a78a5bf0fef4644577b199c8c4 100644 --- a/android/KMAPro/gradle/wrapper/gradle-wrapper.properties +++ b/android/KMAPro/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Sat Apr 14 11:26:38 ICT 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip diff --git a/android/KMAPro/gradlew b/android/KMAPro/gradlew index 91a7e269e19dfc62e27137a0b57ef3e430cee4fd..84fb57da07e013acc8638c8de2aaab4fef16cdcd 100755 --- a/android/KMAPro/gradlew +++ b/android/KMAPro/gradlew @@ -1,4 +1,20 @@ -#!/usr/bin/env bash +#!/bin/bash + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ############################################################################## ## @@ -6,20 +22,38 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" -warn ( ) { +warn () { echo "$*" } -die ( ) { +die () { echo echo "$*" echo @@ -30,6 +64,7 @@ die ( ) { cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true @@ -40,31 +75,11 @@ case "`uname`" in MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -90,7 +105,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then @@ -110,10 +125,11 @@ if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` @@ -154,11 +170,19 @@ if $cygwin ; then esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +exec "$JAVACMD" "$@" diff --git a/android/KMAPro/gradlew.bat b/android/KMAPro/gradlew.bat index 8a0b282aa6885fb573c106b3551f7275c5f17e8e..9618d8d9607cd91a0efb866bcac4810064ba6fac 100644 --- a/android/KMAPro/gradlew.bat +++ b/android/KMAPro/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -8,14 +24,14 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome @@ -46,10 +62,9 @@ echo location of your Java installation. goto fail :init -@rem Get command-line arguments, handling Windowz variants +@rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. @@ -60,11 +75,6 @@ set _SKIP=2 if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ :execute @rem Setup the command line diff --git a/android/KMAPro/kMAPro/build.gradle b/android/KMAPro/kMAPro/build.gradle index eddcf534d34478c434211990fb6f20571355b065..21256f56b256ce113d6aee097006a93eaf9e340a 100644 --- a/android/KMAPro/kMAPro/build.gradle +++ b/android/KMAPro/kMAPro/build.gradle @@ -30,21 +30,10 @@ android { //dumpProperties(project) // Use this to dump all external properties for debugging TeamCity integration //println "===END DUMP===" - String env_services_json_file = System.getenv('services_json_file') - - if (env_services_json_file != null) { - env_services_json_file = String.valueOf(env_services_json_file) - println "Copying production google-services.json and using at kMAPro/" - copy { - from env_services_json_file - include '*.json' - into './' - } - } - - // VERSION_CODE and VERSION_NAME from version.gradle + // VERSION strings from version.gradle versionCode VERSION_CODE as Integer versionName VERSION_NAME + buildConfigField 'String', 'VERSION_ENVIRONMENT', '"'+VERSION_ENVIRONMENT+'"' } String env_release_store_file = System.getenv("release_store_file") @@ -130,8 +119,9 @@ repositories { dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) - implementation 'androidx.appcompat:appcompat:1.2.0-alpha02' + implementation 'androidx.appcompat:appcompat:1.3.0-alpha02' implementation 'com.google.android.material:material:1.0.0' + implementation 'com.stepstone.stepper:material-stepper:4.3.1' api(name: 'keyman-engine', ext: 'aar') implementation 'io.sentry:sentry-android:2.0.1' implementation 'androidx.preference:preference:1.1.0' @@ -156,5 +146,3 @@ dependencies { println it.properties.entrySet()*.toString() .sort().toString().replaceAll(", ","\n") }*/ - -apply plugin: 'com.google.gms.google-services' diff --git a/android/KMAPro/kMAPro/src/debug/google-services.json b/android/KMAPro/kMAPro/src/debug/google-services.json deleted file mode 100644 index 84a3b5b1dee45df13c9e1f867c975f72282ed234..0000000000000000000000000000000000000000 --- a/android/KMAPro/kMAPro/src/debug/google-services.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "project_info": { - "project_number": "681178123610", - "firebase_url": "https://kmapro-ee779.firebaseio.com", - "project_id": "kmapro-ee779", - "storage_bucket": "kmapro-ee779.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:681178123610:android:df408a26aaaf1c9e", - "android_client_info": { - "package_name": "com.tavultesoft.kmapro.debug" - } - }, - "oauth_client": [ - { - "client_id": "681178123610-6j7phpt5jqh1mf44oup6lt8mooomd1tn.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyDFeaVAFdwkrVfUq01aVoBQQ2g5bOUfUUI" - } - ], - "services": { - "analytics_service": { - "status": 1 - }, - "appinvite_service": { - "status": 1, - "other_platform_oauth_client": [] - }, - "ads_service": { - "status": 2 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/android/KMAPro/kMAPro/src/main/AndroidManifest.xml b/android/KMAPro/kMAPro/src/main/AndroidManifest.xml index 61f982c88a08e00815714082aa13be7a129dd003..a21575924a784c195786008ab3396b5c19eef9c5 100644 --- a/android/KMAPro/kMAPro/src/main/AndroidManifest.xml +++ b/android/KMAPro/kMAPro/src/main/AndroidManifest.xml @@ -29,9 +29,9 @@ - + + android:name="io.sentry.auto-init" android:value="false" /> - + @@ -188,7 +188,49 @@ android:sspPrefix="download" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { + options.setRelease("release-"+com.tavultesoft.kmapro.BuildConfig.VERSION_NAME); + options.setEnvironment(com.tavultesoft.kmapro.BuildConfig.VERSION_ENVIRONMENT); + }); } if (BuildConfig.DEBUG) { KMManager.setDebugMode(true); @@ -136,9 +138,9 @@ public class SystemKeyboard extends InputMethodService implements OnKeyboardEven } else { // Check if predictions needs to be re-enabled per Settings preference Context appContext = getApplicationContext(); - HashMap kbInfo = KMManager.getCurrentKeyboardInfo(appContext); + Keyboard kbInfo = KMManager.getCurrentKeyboardInfo(appContext); if (kbInfo != null) { - String langId = kbInfo.get(KMManager.KMKey_LanguageID); + String langId = kbInfo.getLanguageID(); SharedPreferences prefs = appContext.getSharedPreferences(appContext.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE); boolean mayPredict = prefs.getBoolean(LanguageSettingsActivity.getLanguagePredictionPreferenceKey(langId), true); KMManager.setBannerOptions(mayPredict); @@ -223,9 +225,12 @@ public class SystemKeyboard extends InputMethodService implements OnKeyboardEven if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: - // Dismiss the keyboard - KMManager.hideSystemKeyboard(); - return true; + // Dismiss the keyboard if currently shown + if (isInputViewShown()) { + KMManager.hideSystemKeyboard(); + return true; + } + break; } } diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/BookmarksActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/BookmarksActivity.java index 3203bd48e4af01590c5c10294a7dba596d54bf6b..d0d41a89483c9a4346f148a533e52af29e4277ca 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/BookmarksActivity.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/BookmarksActivity.java @@ -15,7 +15,6 @@ import java.util.ArrayList; import java.util.HashMap; import android.os.Bundle; -import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; @@ -38,8 +37,10 @@ import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -public class BookmarksActivity extends AppCompatActivity { +import com.tavultesoft.kmea.util.KMLog; +public class BookmarksActivity extends AppCompatActivity { + private static final String TAG = "BookmarksActivity"; private static ListView listView; private static ArrayList> list = null; private static String bookmarksFilename = "bookmarks.dat"; @@ -186,7 +187,7 @@ public class BookmarksActivity extends AppCompatActivity { list = (ArrayList>) inputStream.readObject(); inputStream.close(); } catch (Exception e) { - Log.e("KMAPro", "Failed to read bookmarks list: " + e.getMessage()); + KMLog.LogException(TAG, "Failed to read bookmarks list: ", e); list = null; } } else { @@ -206,7 +207,7 @@ public class BookmarksActivity extends AppCompatActivity { outputStream.close(); result = true; } catch (Exception e) { - Log.e("KMAPro", "Failed to save bookmarks list: " + e.getMessage()); + KMLog.LogException(TAG, "Failed to save bookmarks list: ", e); result = false; } diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/GetStartedActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/GetStartedActivity.java index bf09d44a463616c214a8ceeaa186a6106522b23b..52b023f6d0838f495030074ffa463ce1ce471536 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/GetStartedActivity.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/GetStartedActivity.java @@ -10,6 +10,7 @@ import java.util.List; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KMPBrowserActivity; +import com.tavultesoft.kmea.data.Keyboard; import android.os.Bundle; import android.provider.Settings; @@ -114,10 +115,8 @@ public class GetStartedActivity extends AppCompatActivity { public void onItemClick(AdapterView parent, View view, int position, long id) { if (position == 0) { if (KMManager.hasConnection(context)) { - // Scenario 1: Connection to keyman.com catalog - Intent i = new Intent(context, KMPBrowserActivity.class); - i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + // Keyman Settings install activity + Intent i = new Intent(context, KeymanSettingsInstallActivity.class); context.startActivity(i); } } else if (position == 1) { @@ -156,7 +155,7 @@ public class GetStartedActivity extends AppCompatActivity { String checkbox_on = String.valueOf(android.R.drawable.checkbox_on_background); String info = String.valueOf(R.drawable.ic_info_outline); - ArrayList> kbList = KMManager.getKeyboardsList(this); + List kbList = KMManager.getKeyboardsList(this); if (kbList != null && kbList.size() > 1) { list.get(0).put(iconKey, checkbox_on); } else { diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/InfoActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/InfoActivity.java index 529b6b7548f56048e7c7c75e0b70bbc1e71e4d15..a665e48f4a19011d42dd0943adaae4bd84c71691 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/InfoActivity.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/InfoActivity.java @@ -4,8 +4,10 @@ package com.tavultesoft.kmapro; +import com.tavultesoft.kmea.BuildConfig; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KMManager.FormFactor; +import com.tavultesoft.kmea.util.KMLog; import android.content.Context; import android.graphics.Bitmap; @@ -24,9 +26,11 @@ import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; public class InfoActivity extends AppCompatActivity { - + private final static String TAG = "InfoActivity"; private WebView webView; - private final String kmHelpBaseUrl = "https://help.keyman.com/products/android"; + private final String HELP_PRODUCTION_HOST = "help.keyman.com"; + private final String HELP_STAGING_HOST = "help.keyman-staging.com"; + private final String HELP_BASE_FORMAT_STR = "https://%s/products/android/%s/%s?embed=android&formfactor=%s"; private String kmUrl = ""; private final String htmlPath = "file:///android_asset/info/products/android"; private final String htmlPage = "index.php"; @@ -54,18 +58,10 @@ public class InfoActivity extends AppCompatActivity { version.setTextSize(getResources().getDimension(R.dimen.titlebar_label_textsize)); version.setGravity(Gravity.CENTER); - // Parse to create a version title - String versionStr = ""; - PackageInfo pInfo; - try { - pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); - versionStr = pInfo.versionName; - } catch (NameNotFoundException e) { - // Fallback to a "current" version. This does not need to be maintained - versionStr = "12.0.0.0"; - } + // Parse app version string to create a version title (Not using KMManager.getVersion() because that's for KMEA) + String versionStr = BuildConfig.VERSION_NAME; - String versionTitle = String.format("%s: %s", getString(R.string.title_version), versionStr); + String versionTitle = String.format(getString(R.string.title_version), versionStr); version.setText(versionTitle); getSupportActionBar().setCustomView(version); @@ -83,7 +79,17 @@ public class InfoActivity extends AppCompatActivity { formFactor = "tablet"; } - kmUrl = String.format("%s/%s/%s?embed=android&formfactor=%s", kmHelpBaseUrl, majorMinorVersion, htmlPage, formFactor); + String helpHost = ""; + switch (KMManager.getTier(BuildConfig.VERSION_NAME)) { + case ALPHA: + case BETA: + helpHost = HELP_STAGING_HOST; + break; + default: + helpHost = HELP_PRODUCTION_HOST; + } + + kmUrl = String.format(HELP_BASE_FORMAT_STR, helpHost, majorMinorVersion, htmlPage, formFactor); // The offline mirroring process (currently) adds .html to the end of the whole string. kmOfflineUrl = String.format("%s/%s/%s.html", htmlPath, formFactor, htmlPage); webView = (WebView) findViewById(R.id.infoWebView); diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsActivity.java index c86d88373e48421e5bbd41faf383dc8053b55cc0..e7d45430597100d0e0740ec5d7e487ac7ebeafef 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsActivity.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsActivity.java @@ -7,6 +7,7 @@ import androidx.appcompat.widget.Toolbar; public class KeymanSettingsActivity extends AppCompatActivity { protected static final String installedLanguagesKey = "InstalledLanguages"; + protected static final String installKeyboardOrDictionaryKey = "InstallKeyboardOrDictionary"; protected static final String showBannerKey = "ShowBanner"; protected KeymanSettingsFragment innerFragment; diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsFragment.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsFragment.java index 1b3da0cd13dd0a7666f8d88a19cc66be6a01be11..dfcdf94eb1b58532f3aa4dabe5d4c91e7a565457 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsFragment.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsFragment.java @@ -2,7 +2,6 @@ package com.tavultesoft.kmapro; import android.content.Context; import android.content.Intent; -import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.view.inputmethod.InputMethodManager; @@ -20,7 +19,7 @@ public class KeymanSettingsFragment extends PreferenceFragmentCompat { private static final String TAG = "SettingsFragment"; private static Context context; - private Preference languagesPreference, addKeyboardFromDevice; + private Preference languagesPreference, installKeyboardOrDictionary; private CheckBoxPreference setSystemKeyboardPreference; private CheckBoxPreference setDefaultKeyboardPreference; @@ -41,23 +40,12 @@ public class KeymanSettingsFragment extends PreferenceFragmentCompat { languagesIntent.putExtra(KMManager.KMKey_DisplayKeyboardSwitcher, false); languagesPreference.setIntent(languagesIntent); - // Launch System file browser for user to navigate to local .kmp files - // Using generic "Add keyboard" title even though this can also install lexical model .kmp's. - addKeyboardFromDevice = new Preference(context); - addKeyboardFromDevice.setTitle(getString(R.string.title_add_keyboard_from_device)); - addKeyboardFromDevice.setWidgetLayoutResource(R.layout.preference_file_browser_layout); - addKeyboardFromDevice.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); - intent.addCategory(Intent.CATEGORY_OPENABLE); - intent.putExtra("android.content.extra.SHOW_ADVANCED", false); - // Unfortunately, we can't filter for a "kmp" mime type - intent.setType("*/*"); - startActivityForResult(intent, MainActivity.READ_REQUEST_CODE); - return false; - } - }); + installKeyboardOrDictionary = new Preference(context); + installKeyboardOrDictionary.setKey(KeymanSettingsActivity.installKeyboardOrDictionaryKey); + installKeyboardOrDictionary.setTitle(getString(R.string.install_keyboard_or_dictionary)); + installKeyboardOrDictionary.setWidgetLayoutResource(R.layout.preference_add_icon_layout); + Intent installIntent = new Intent(context, KeymanSettingsInstallActivity.class); + installKeyboardOrDictionary.setIntent(installIntent); /* Automatically does the following: @@ -112,7 +100,7 @@ public class KeymanSettingsFragment extends PreferenceFragmentCompat { setDefaultKeyboardPreference.setOnPreferenceChangeListener(checkBlocker); screen.addPreference(languagesPreference); - screen.addPreference(addKeyboardFromDevice); + screen.addPreference(installKeyboardOrDictionary); screen.addPreference(setSystemKeyboardPreference); screen.addPreference(setDefaultKeyboardPreference); @@ -149,16 +137,6 @@ public class KeymanSettingsFragment extends PreferenceFragmentCompat { // .update() on our behalf. } - - public void onActivityResult(int requestCode, int resultCode, Intent returnIntent) { - // Handle kmp file selected from file browser - if ((requestCode == MainActivity.READ_REQUEST_CODE) && (returnIntent != null)) { - String kmpFilename = returnIntent.getDataString(); - Uri data = Uri.parse(kmpFilename); - MainActivity.useLocalKMP(this.getContext(), data); - } - } - public void update() { setSystemKeyboardPreference.setChecked(SystemIMESettings.isEnabledAsSystemKB(context)); setDefaultKeyboardPreference.setChecked(SystemIMESettings.isDefaultKB(context)); diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsInstallActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsInstallActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..dc3f459ae996aa3e1711f290e397ae45c3695f79 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/KeymanSettingsInstallActivity.java @@ -0,0 +1,184 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ +package com.tavultesoft.kmapro; + +import java.util.ArrayList; +import java.util.HashMap; + +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import android.content.Context; +import android.content.Intent; +import android.graphics.Typeface; +import android.net.Uri; +import android.os.Bundle; +import android.view.View; +import android.view.Window; +import android.widget.AdapterView; +import android.widget.ListAdapter; +import android.widget.ListView; +import android.os.Bundle; +import android.widget.SimpleAdapter; +import android.widget.TextView; + +import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.KMPBrowserActivity; +import com.tavultesoft.kmea.data.KeyboardController; +import com.tavultesoft.kmea.util.MapCompat; + +public class KeymanSettingsInstallActivity extends AppCompatActivity { + private static final String TAG = "SettingsInstallActivity"; + private static ArrayList> installOptionList = null; + private static Typeface titleFont = null; + private static final String titleKey = "title"; + private static final String subtitleKey = "subtitle"; + private static final String iconKey = "icon"; + private final String isEnabledKey = "isEnabled"; + private static Context context; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + supportRequestWindowFeature(Window.FEATURE_NO_TITLE); + context = this; + + setContentView(R.layout.activity_list_layout); + final Toolbar toolbar = findViewById(R.id.list_toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setDisplayShowHomeEnabled(true); + getSupportActionBar().setDisplayShowTitleEnabled(false); + + final ListView listView = findViewById(com.tavultesoft.kmea.R.id.listView); + + Bundle bundle = getIntent().getExtras(); + + final TextView textView = findViewById(R.id.bar_title); + textView.setText(getString(R.string.install_keyboard_or_dictionary)); + if (titleFont != null) { + textView.setTypeface(titleFont, Typeface.BOLD); + } + + installOptionList = new ArrayList<>(); + + final String noIcon = "0"; + HashMap hashMap = new HashMap<>(); + hashMap.put(titleKey, getString(R.string.install_from_keyman_dot_com)); + String icon = String.valueOf(R.drawable.ic_content_add); + hashMap.put(iconKey, icon); + installOptionList.add(hashMap); + + hashMap = new HashMap<>(); + hashMap.put(titleKey, getString(R.string.install_from_local_file)); + icon = String.valueOf(R.drawable.ic_folder_open); + hashMap.put(iconKey, icon); + hashMap.put(isEnabledKey, "true"); + installOptionList.add(hashMap); + + // TODO: Install by scanning QR code + /* + hashMap = new HashMap<>(); + hashMap.put(titleKey, getString(R.string.install_from_other_device)); + icon = String.valueOf(R.drawable.ic_content_add); + hashMap.put(iconKey, icon); + hashMap.put(isEnabledKey, "false"); + installOptionList.add(hashMap); + */ + + hashMap = new HashMap<>(); + hashMap.put(titleKey, getString(R.string.add_languages_to_installed_keyboard)); + hashMap.put(subtitleKey, getString(R.string.add_language_subtext)); + icon = String.valueOf(R.drawable.ic_content_add); + hashMap.put(iconKey, icon); + hashMap.put(isEnabledKey, "true"); + installOptionList.add(hashMap); + + String[] from = new String[]{titleKey, subtitleKey, iconKey}; + int[] to = new int[]{com.tavultesoft.kmea.R.id.text1, com.tavultesoft.kmea.R.id.text2, com.tavultesoft.kmea.R.id.image1}; + + ListAdapter adapter = new SimpleAdapter(context, installOptionList, com.tavultesoft.kmea.R.layout.list_row_layout2, from, to) { + @Override + public boolean isEnabled(int position) { + HashMap hashMap = installOptionList.get(position); + String itemTitle = MapCompat.getOrDefault(hashMap, titleKey, ""); + String icon = MapCompat.getOrDefault(hashMap, iconKey, noIcon); + if (itemTitle.equals(getString(R.string.install_from_other_device))) { + // Scan QR code not implemented yet + return false; + } else if (itemTitle.equals(getString(R.string.add_languages_to_installed_keyboard))) { + if (KeyboardController.getInstance().getInstalledPackagesList() == null) { + // Disable if no keyboard packages installed + return false; + } + } + + return super.isEnabled(position); + } + }; + listView.setAdapter(adapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + HashMap hashMap = (HashMap) parent.getItemAtPosition(position); + String itemTitle = MapCompat.getOrDefault(hashMap, titleKey, ""); + + // Install from keyman.com + if (itemTitle.equals(getString(R.string.install_from_keyman_dot_com))) { + if (KMManager.hasConnection(context)) { + Intent i = new Intent(context, KMPBrowserActivity.class); + i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + context.startActivity(i); + } else { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); + dialogBuilder.setTitle(getString(R.string.title_add_keyboard)); + dialogBuilder.setMessage(getString(R.string.cannot_connect)); + dialogBuilder.setPositiveButton(getString(R.string.label_ok), null); + AlertDialog dialog = dialogBuilder.create(); + dialog.show(); + } + // Install from local file + } else if (itemTitle.equals(getString(R.string.install_from_local_file))) { + Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.putExtra("android.content.extra.SHOW_ADVANCED", false); + // Unfortunately, we can't filter for a "kmp" mime type + intent.setType("*/*"); + startActivityForResult(intent, MainActivity.READ_REQUEST_CODE); + + // Install by scanning QR code + } else if (itemTitle.equals(getString(R.string.install_from_other_device))) { + // TODO + + // Add language from keyboard package already installed + } else if (itemTitle.equals(getString(R.string.add_languages_to_installed_keyboard))) { + Intent intent = new Intent(context, SelectPackageActivity.class); + context.startActivity(intent); + } + } + }); + } + + @Override + public boolean onSupportNavigateUp() { + super.onBackPressed(); + return true; + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent returnIntent) { + super.onActivityResult(requestCode, resultCode, returnIntent); + + // Handle kmp file selected from file browser + if ((requestCode == MainActivity.READ_REQUEST_CODE) && (returnIntent != null)) { + String kmpFilename = returnIntent.getDataString(); + Uri data = Uri.parse(kmpFilename); + MainActivity.useLocalKMP(context, data); + } + } + +} diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/MainActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/MainActivity.java index ff4f3c69de69641240b667431c532d6d09fedb1d..b7e657a0de124de02e62fe63da42221446b3abc8 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/MainActivity.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/MainActivity.java @@ -25,17 +25,19 @@ import com.tavultesoft.kmea.KMTextView; import com.tavultesoft.kmea.KeyboardEventHandler.OnKeyboardDownloadEventListener; import com.tavultesoft.kmea.KeyboardEventHandler.OnKeyboardEventListener; import com.tavultesoft.kmea.cloud.CloudApiTypes; -import com.tavultesoft.kmea.packages.PackageProcessor; +import com.tavultesoft.kmea.data.CloudRepository; +import com.tavultesoft.kmea.data.Dataset; +import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.LexicalModel; import com.tavultesoft.kmea.util.FileUtils; -import com.tavultesoft.kmea.util.FileProviderUtils; import com.tavultesoft.kmea.util.DownloadIntentService; +import com.tavultesoft.kmea.util.KMLog; +import com.tavultesoft.kmea.util.KMPLink; import android.Manifest; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.pm.PackageManager; -import android.content.res.AssetManager; -import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; @@ -71,7 +73,6 @@ import android.os.ResultReceiver; import android.provider.OpenableColumns; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; -import androidx.core.content.FileProvider; import androidx.appcompat.widget.PopupMenu; import android.text.Html; @@ -92,8 +93,6 @@ import android.widget.Toast; import io.sentry.android.core.SentryAndroid; import io.sentry.core.Sentry; -import static com.tavultesoft.kmea.KMKeyboardDownloaderActivity.kKeymanApiModelURL; - public class MainActivity extends AppCompatActivity implements OnKeyboardEventListener, OnKeyboardDownloadEventListener, ActivityCompat.OnRequestPermissionsResultCallback { public static Context context; @@ -110,15 +109,15 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi private int textSize = minTextSize; private static final String defaultKeyboardInstalled = "DefaultKeyboardInstalled"; private static final String defaultDictionaryInstalled = "DefaultDictionaryInstalled"; - private static final String defaultKeyboardPath = "sil_euro_latin.kmp"; - private static final String defaultDictionaryPath = "nrc.en.mtnt.model.kmp"; private static final String userTextKey = "UserText"; private static final String userTextSizeKey = "UserTextSize"; - protected static final String didCheckUserDataKey = "DidCheckUserData"; private Toolbar toolbar; private Menu menu; private Uri data; + private static Dataset repo; + private boolean didExecuteParser = false; + DownloadResultReceiver resultReceiver; private ProgressDialog progressDialog; @@ -150,18 +149,28 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi packageIntent.putExtras(bundle); startActivity(packageIntent); - // Determine if associated lexical model should be downloaded + // Determine if associated lexical model for languageID should be downloaded if (FileUtils.hasKeymanPackageExtension(kmpFilename) && !FileUtils.hasLexicalModelPackageExtension(kmpFilename) && (languageID != null) && !languageID.isEmpty()) { - String keyboardID = kmpFilename.substring(0, kmpFilename.lastIndexOf(FileUtils.KEYMANPACKAGE)); - ArrayList cloudQueries = new ArrayList<>(); - String _remoteLexicalModelUrl = String.format("%s?q=bcp47:%s", kKeymanApiModelURL, languageID); - cloudQueries.add(new CloudApiTypes.CloudApiParam( - CloudApiTypes.ApiTarget.KeyboardLexicalModels, _remoteLexicalModelUrl) - .setType(CloudApiTypes.JSONType.Array)); - // Keyboard package already downloaded, so this will just download associated lexical model. - // Can't call downloadLexicalModel() because it needs to already know the model ID - KMKeyboardDownloaderActivity.downloadKeyboard(context, languageID, keyboardID, cloudQueries); + + // Force the cloud catalog to update + if (!didExecuteParser) { + didExecuteParser = true; + repo = CloudRepository.shared.fetchDataset(context); + } + + // Check if associated model is available in the cloud, and that it's not already installed + LexicalModel modelInfo = CloudRepository.shared.getAssociatedLexicalModel(context, languageID); + if ((modelInfo != null) && (KMManager.getAssociatedLexicalModel(languageID) == null)) { + String modelID = modelInfo.getLexicalModelID(); + String url = modelInfo.getUpdateKMP(); + if (url != null) { + ArrayList _params = new ArrayList<>(); + _params.add(new CloudApiTypes.CloudApiParam( + CloudApiTypes.ApiTarget.LexicalModelPackage, url)); + KMKeyboardDownloaderActivity.downloadLexicalModel(context, modelID, _params); + } + } } break; @@ -176,7 +185,10 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi super.onCreate(savedInstanceState); context = this; - SentryAndroid.init(context); + SentryAndroid.init(context, options -> { + options.setRelease("release-"+com.tavultesoft.kmapro.BuildConfig.VERSION_NAME); + options.setEnvironment(com.tavultesoft.kmapro.BuildConfig.VERSION_ENVIRONMENT); + }); checkStoragePermission(null); resultReceiver = new DownloadResultReceiver(new Handler()); @@ -192,19 +204,10 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi // Add default keyboard boolean installDefaultKeyboard = prefs.getBoolean(defaultKeyboardInstalled, false); if (!installDefaultKeyboard) { - HashMap kbInfo = new HashMap(); - kbInfo.put(KMManager.KMKey_PackageID, KMManager.KMDefault_PackageID); - kbInfo.put(KMManager.KMKey_KeyboardID, KMManager.KMDefault_KeyboardID); - kbInfo.put(KMManager.KMKey_LanguageID, KMManager.KMDefault_LanguageID); - kbInfo.put(KMManager.KMKey_KeyboardName, KMManager.KMDefault_KeyboardName); - kbInfo.put(KMManager.KMKey_LanguageName, KMManager.KMDefault_LanguageName); - kbInfo.put(KMManager.KMKey_KeyboardVersion, - KMManager.getLatestKeyboardFileVersion(context, KMManager.KMDefault_PackageID, KMManager.KMDefault_KeyboardID)); - kbInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont); - File welcomeFile = new File(KMManager.getPackagesDir(), KMManager.KMDefault_PackageID + File.separator + FileUtils.WELCOME_HTM); - kbInfo.put(KMManager.KMKey_CustomHelpLink, welcomeFile.getPath()); - KMManager.addKeyboard(this, kbInfo); - + if (!KMManager.keyboardExists(context, KMManager.KMDefault_PackageID, KMManager.KMDefault_KeyboardID, + KMManager.KMDefault_LanguageID)) { + KMManager.addKeyboard(this, KMManager.getDefaultKeyboard(getApplicationContext())); + } SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(defaultKeyboardInstalled, true); editor.commit(); @@ -213,13 +216,13 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi // Add default dictionary boolean installDefaultDictionary = prefs.getBoolean(defaultDictionaryInstalled, false); if (!installDefaultDictionary) { + LexicalModel defaultLexicalModel = LexicalModel.getDefaultLexicalModel(context); HashMap lexicalModelInfo = new HashMap(); - lexicalModelInfo.put(KMManager.KMKey_PackageID, KMManager.KMDefault_DictionaryPackageID); - lexicalModelInfo.put(KMManager.KMKey_LanguageID, KMManager.KMDefault_LanguageID); - lexicalModelInfo.put(KMManager.KMKey_LexicalModelID, KMManager.KMDefault_DictionaryModelID); - lexicalModelInfo.put(KMManager.KMKey_LexicalModelName, KMManager.KMDefault_DictionaryModelName); - lexicalModelInfo.put(KMManager.KMKey_LexicalModelVersion, - KMManager.getLexicalModelPackageVersion(context, KMManager.KMDefault_DictionaryPackageID)); + lexicalModelInfo.put(KMManager.KMKey_PackageID, defaultLexicalModel.getPackageID()); + lexicalModelInfo.put(KMManager.KMKey_LanguageID, defaultLexicalModel.getLanguageID()); + lexicalModelInfo.put(KMManager.KMKey_LexicalModelID, defaultLexicalModel.getLexicalModelID()); + lexicalModelInfo.put(KMManager.KMKey_LexicalModelName, defaultLexicalModel.getLexicalModelName()); + lexicalModelInfo.put(KMManager.KMKey_LexicalModelVersion, defaultLexicalModel.getVersion()); /* // If welcome.htm exists, add custom help link welcomeFile = new File(KMManager.getLexicalModelsDir(), KMManager.KMDefault_DictionaryPackageID + File.separator + FileUtils.WELCOME_HTM); @@ -250,20 +253,7 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi textView.setTextSize((float) textSize); textView.setSelection(textView.getText().length()); - boolean didCheckUserData = prefs.getBoolean(MainActivity.didCheckUserDataKey, false); - if (!didCheckUserData && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)) { - try { - Intent getUserdataIntent = new Intent("keyman.ACTION_GET_USERDATA"); - startActivityForResult(getUserdataIntent, 0); - } catch (Exception e) { - SharedPreferences.Editor editor = prefs.edit(); - editor.putBoolean(MainActivity.didCheckUserDataKey, true); - editor.commit(); - checkGetStarted(); - } - } else { - checkGetStarted(); - } + checkGetStarted(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @@ -275,7 +265,6 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi checkGetStarted(); return; } else { - boolean didFail = false; ClipData userdata = returnIntent.getClipData(); int len = userdata.getItemCount(); for (int i = 0; i < len; i++) { @@ -306,19 +295,10 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi inputStream.close(); } } catch (Exception e) { - didFail = true; - Log.e(TAG, e.getMessage()); + KMLog.LogException(TAG, "", e); } } - if (!didFail) { - KMManager.updateOldKeyboardsList(this); - SharedPreferences prefs = getSharedPreferences(getString(R.string.kma_prefs_name), Context.MODE_PRIVATE); - SharedPreferences.Editor editor = prefs.edit(); - editor.putBoolean(MainActivity.didCheckUserDataKey, true); - editor.commit(); - } - checkGetStarted(); } } @@ -354,11 +334,16 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi break; case "http" : case "https" : + // Might need to modify link like KMPBrowserActivity + String link = data.toString(); + if (KMPLink.isKeymanInstallLink(link)) { + data = KMPLink.getKeyboardDownloadLink(link); + } downloadKMP(scheme); break; case "keyman" : // Only accept download links from Keyman browser activities - if (FileUtils.isKeymanLink(data.toString()) && caller != null && + if (KMPLink.isKeymanDownloadLink(data.toString()) && caller != null && (caller.equalsIgnoreCase("com.tavultesoft.kmea.KMPBrowserActivity") || caller.equalsIgnoreCase("com.tavultesoft.kmapro.WebBrowserActivity"))) { @@ -371,11 +356,13 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi data = Uri.parse(builder.build().toString()); downloadKMP(scheme); } else { - Log.e(TAG, "Unrecognized scheme: " + scheme); + String msg = "Unrecognized scheme: " + scheme; + KMLog.LogError(TAG, msg); } break; default : - Log.e(TAG, "Unrecognized scheme: " + scheme); + String msg = "Unrecognized scheme: " + scheme; + KMLog.LogError(TAG, msg); } } intent.setData(null); @@ -411,92 +398,54 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi invalidateOptionsMenu(); } - + @SuppressLint("RestrictedApi") @Override public boolean onPrepareOptionsMenu(final Menu menu) { final MenuItem _overflowMenuItem = menu.findItem(R.id.action_overflow); - - if(_overflowMenuItem!=null) { - final ViewGroup _rootView = (ViewGroup) _overflowMenuItem.getActionView(); - - _rootView.findViewById(R.id.counterBackground).setBackground( - this.getResources().getDrawable(R.drawable.ic_light_action_overflow)); - - _rootView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - PopupMenu _popup = new PopupMenu(context, _rootView); - getMenuInflater().inflate(R.menu.overflow_menu, _popup.getMenu()); - - updateUpdateCountIndicator( - _popup.getMenu().findItem(R.id.action_update_keyboards), - KMManager.getUpdateTool().getOpenUpdateCount(),true); - - _popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem theItem) { - return onOptionsItemSelected(theItem); - } - }); - - MenuPopupHelper _menuHelper = new MenuPopupHelper(context, (MenuBuilder) _popup.getMenu(), _rootView); - _menuHelper.setForceShowIcon(true); - _menuHelper.show(); - } - }); - return super.onPrepareOptionsMenu(menu); + if (_overflowMenuItem != null) { + MenuItem updateKeyboards = this.menu.findItem(R.id.action_update_keyboards); + updateUpdateCountIndicator(updateKeyboards, + KMManager.getUpdateTool().getOpenUpdateCount(), true); } - - final MenuItem _keyboardupdate = menu.findItem(R.id.action_update_keyboards); - if(_keyboardupdate==null) - return super.onPrepareOptionsMenu(menu); - - final ViewGroup _rootView = (ViewGroup) _keyboardupdate.getActionView(); - - _rootView.findViewById(R.id.counterBackground).setBackground( - this.getResources().getDrawable(R.drawable.ic_cloud_download)); - - _rootView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - onOptionsItemSelected(_keyboardupdate); - } - }); return super.onPrepareOptionsMenu(menu); } private void updateUpdateCountIndicator(int anUpdateCount) { - if (menu == null) + if (menu == null) { return; + } final MenuItem _overflowMenuItem = menu.findItem(R.id.action_overflow); - if (_overflowMenuItem != null) - updateUpdateCountIndicator(_overflowMenuItem,anUpdateCount,false); + if (_overflowMenuItem != null) { + updateUpdateCountIndicator(_overflowMenuItem, anUpdateCount, false); + } final MenuItem _keyboardupdate = menu.findItem(R.id.action_update_keyboards); - if (_keyboardupdate != null) - updateUpdateCountIndicator(_keyboardupdate,anUpdateCount,true); - + if (_keyboardupdate != null) { + updateUpdateCountIndicator(_keyboardupdate, anUpdateCount, true); + } } private void updateUpdateCountIndicator(MenuItem theItem, int anUpdateCount, boolean aHideMenuitem) { final ViewGroup _rootView = (ViewGroup) theItem.getActionView(); - if(anUpdateCount==0) - { - if(aHideMenuitem) + if(anUpdateCount==0) { + if (aHideMenuitem) { theItem.setVisible(false); - else if(_rootView!=null) + } else if (_rootView != null) { _rootView.findViewById(R.id.update_count_indicator).setVisibility(View.GONE); - } - else { - if(aHideMenuitem) + } + } else { + if(aHideMenuitem) { theItem.setVisible(true); - else if(_rootView!=null) - _rootView.findViewById(R.id.update_count_indicator).setVisibility(View.VISIBLE); + } else if(_rootView!=null) { + _rootView.findViewById(R.id.update_count_indicator).setVisibility(View.VISIBLE); + } } - if(_rootView==null) + if(_rootView==null) { return; + } TextView _t = _rootView.findViewById(R.id.update_count_indicator); _t.setText(String.valueOf(anUpdateCount)); @@ -600,61 +549,61 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi return; } try { + // Initial try with Keyman 13.0 download link String url = data.getQueryParameter(KMKeyboardDownloaderActivity.KMKey_URL); if (url == null) { url = data.toString(); } if (url != null) { - // URL contains KMP to download in background. - boolean isCustom = FileUtils.isCustomKeyboard(url); - - String filename = data.getQueryParameter(KMKeyboardDownloaderActivity.KMKey_Filename); + // Create filename by extracting packageID from query or urlNoQuery + String filename = data.getQueryParameter("id"); if (filename == null) { - FileUtils.getFilename(url); + String urlNoQuery = data.getPath(); + filename = FileUtils.getFilename(urlNoQuery); + } + if (!filename.endsWith(FileUtils.KEYMANPACKAGE)) { + filename += FileUtils.KEYMANPACKAGE; } - // Parse the url for the BCP 47 language ID - Uri uri = Uri.parse(url); - String languageID = uri.getQueryParameter(KMKeyboardDownloaderActivity.KMKey_BCP47); + // Parse query for the BCP 47 language ID + String languageID = data.getQueryParameter(KMKeyboardDownloaderActivity.KMKey_BCP47); + // TODO: Using "tag" for now, but production will be KMKeyboardDownloaderActivity.KMKey_BCP47 + if (languageID == null) { + languageID = data.getQueryParameter("tag"); + } - // Keyboard download endpoint: - // download.php?id=&platform=[&mode=][&cid=xxxx] url = url.toLowerCase(); - - // Only handle ad-hoc kmp packages or from keyman.com - if (FileUtils.hasKeymanPackageExtension(url) || scheme.equals("keyman")) { - try { - // Download the KMP to app cache - Intent downloadIntent = new Intent(MainActivity.this, DownloadIntentService.class); - downloadIntent.putExtra("url", url); - downloadIntent.putExtra("filename", filename); - downloadIntent.putExtra("language", languageID); - downloadIntent.putExtra("destination", MainActivity.this.getCacheDir().toString()); - downloadIntent.putExtra("receiver", resultReceiver); - - progressDialog = new ProgressDialog(MainActivity.this); - String ellipsisStr = "\u2026"; - progressDialog.setMessage(String.format("%s\n%s%s", - getString(R.string.downloading_keyboard_package), filename, ellipsisStr)); - progressDialog.setCancelable(false); - progressDialog.show(); - - startService(downloadIntent); - } catch (Exception e) { - if (progressDialog != null && progressDialog.isShowing()) { - progressDialog.dismiss(); - } - progressDialog = null; - return;//break; + try { + // Download the KMP to app cache + Intent downloadIntent = new Intent(MainActivity.this, DownloadIntentService.class); + downloadIntent.putExtra("url", url); + downloadIntent.putExtra("filename", filename); + downloadIntent.putExtra("language", languageID); + downloadIntent.putExtra("destination", MainActivity.this.getCacheDir().toString()); + downloadIntent.putExtra("receiver", resultReceiver); + + progressDialog = new ProgressDialog(MainActivity.this); + progressDialog.setMessage(String.format(getString(R.string.downloading_keyboard_package), filename)); + progressDialog.setCancelable(false); + progressDialog.show(); + + startService(downloadIntent); + } catch (Exception e) { + KMLog.LogException(TAG, "", e); + if (progressDialog != null && progressDialog.isShowing()) { + progressDialog.dismiss(); } - } else { - String message = "Download failed. Not a .kmp keyboard package."; - Toast.makeText(getApplicationContext(), message, - Toast.LENGTH_SHORT).show(); + progressDialog = null; + return;//break; } + } else { + String message = "Download failed. Not a .kmp keyboard package."; + Toast.makeText(getApplicationContext(), message, + Toast.LENGTH_SHORT).show(); } } catch (UnsupportedOperationException e) { String message = "Download failed. Invalid URL."; + KMLog.LogException(TAG, message, e); Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } @@ -754,7 +703,7 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi final View textSizeController = inflater.inflate(R.layout.text_size_controller, null); final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this); dialogBuilder.setIcon(R.drawable.ic_light_action_textsize); - dialogBuilder.setTitle(String.format("%s: %d", getString(R.string.action_text_size), textSize)); + dialogBuilder.setTitle(String.format(getString(R.string.text_size), textSize)); dialogBuilder.setView(textSizeController); dialogBuilder.setPositiveButton(getString(R.string.label_ok), new DialogInterface.OnClickListener() { @Override @@ -785,7 +734,7 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { textSize = progress + minTextSize; textView.setTextSize((float) textSize); - dialog.setTitle(String.format("%s: %d", getString(R.string.action_text_size), textSize)); + dialog.setTitle(String.format(getString(R.string.text_size), textSize)); } }); @@ -814,7 +763,7 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this); dialogBuilder.setIcon(R.drawable.ic_light_action_trash); dialogBuilder.setTitle(getString(R.string.action_clear_text)); - dialogBuilder.setMessage(String.format("\n%s\n", getString(R.string.all_text_will_be_cleared))); + dialogBuilder.setMessage(getString(R.string.all_text_will_be_cleared)); dialogBuilder.setPositiveButton(getString(R.string.label_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { @@ -837,7 +786,7 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi boolean showGetStarted = prefs.getBoolean(GetStartedActivity.showGetStartedKey, true); if (showGetStarted) { boolean shouldShowGetStarted = false; - ArrayList> kbList = KMManager.getKeyboardsList(this); + List kbList = KMManager.getKeyboardsList(this); if (kbList != null && kbList.size() < 2) shouldShowGetStarted = true; @@ -854,6 +803,7 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_REQUEST_STORAGE) { // Request for storage permission if (grantResults.length ==2 && @@ -965,8 +915,8 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi } catch (Exception e) { String message = "Access denied to " + filename + ".\nCheck Android Settings --> Apps --> Keyman to grant storage permissions"; + KMLog.LogException(TAG, "Unable to copy " + filename + " to app cache ", e); Toast.makeText(context, message, Toast.LENGTH_LONG).show(); - Log.e(TAG, "Unable to copy " + filename + " to app cache"); return; } @@ -1074,17 +1024,23 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi @Override public void onPackageInstalled(List> keyboardsInstalled) { for(int i=0; i < keyboardsInstalled.size(); i++) { - HashMap keyboardInfo = new HashMap<>(keyboardsInstalled.get(i)); + HashMap hashMap = new HashMap<>(keyboardsInstalled.get(i)); + Keyboard keyboardInfo = new Keyboard( + hashMap.get(KMManager.KMKey_PackageID), + hashMap.get(KMManager.KMKey_KeyboardID), + hashMap.get(KMManager.KMKey_KeyboardName), + hashMap.get(KMManager.KMKey_LanguageID), + hashMap.get(KMManager.KMKey_LanguageName), + hashMap.get(KMManager.KMKey_Version), + hashMap.get(KMManager.KMKey_CustomHelpLink), + hashMap.get(KMManager.KMKey_KMPLink), + true, + hashMap.get(KMManager.KMKey_Font), + hashMap.get(KMManager.KMKey_OskFont)); + if (i == 0) { if (KMManager.addKeyboard(this, keyboardInfo)) { - String packageID = keyboardInfo.get(KMManager.KMKey_PackageID); - String keyboardID = keyboardInfo.get(KMManager.KMKey_KeyboardID); - String languageID = keyboardInfo.get(KMManager.KMKey_LanguageID); - String keyboardName = keyboardInfo.get(KMManager.KMKey_KeyboardName); - String languageName = keyboardInfo.get(KMManager.KMKey_LanguageName); - String kFont = keyboardInfo.get(KMManager.KMKey_Font); - String kOskFont = keyboardInfo.get(KMManager.KMKey_OskFont); - KMManager.setKeyboard(packageID, keyboardID, languageID, keyboardName, languageName, kFont, kOskFont); + KMManager.setKeyboard(keyboardInfo); } } else { KMManager.addKeyboard(this, keyboardInfo); @@ -1095,7 +1051,7 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi @Override public void onLexicalModelInstalled(List> lexicalModelsInstalled) { String langId = (KMManager.getCurrentKeyboardInfo(this) != null) ? - KMManager.getCurrentKeyboardInfo(this).get(KMManager.KMKey_LanguageID) : + KMManager.getCurrentKeyboardInfo(this).getLanguageID() : KMManager.KMDefault_LanguageID; boolean matchingModel = false; diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/PackageActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/PackageActivity.java index 1c0d28374940b0a85cd9acb329de9404681008de..0cb115a33fad8cf8ea81933fb3559cd0f0d1acbe 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/PackageActivity.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/PackageActivity.java @@ -4,6 +4,8 @@ import android.annotation.SuppressLint; import androidx.appcompat.widget.Toolbar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AlertDialog; +import androidx.fragment.app.Fragment; + import android.content.Context; import android.content.DialogInterface; import android.content.Intent; @@ -12,7 +14,6 @@ import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; -import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; @@ -20,40 +21,50 @@ import android.webkit.WebViewClient; import android.widget.Button; import android.widget.TextView; -import android.util.Log; import android.widget.Toast; +import com.stepstone.stepper.StepperLayout; +import com.stepstone.stepper.VerificationError; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KeyboardEventHandler; +import com.tavultesoft.kmea.data.Keyboard; import com.tavultesoft.kmea.packages.PackageProcessor; import com.tavultesoft.kmea.packages.LexicalModelPackageProcessor; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; import org.json.JSONObject; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; -public class PackageActivity extends AppCompatActivity { - - private Toolbar toolbar; - private WebView webView; +public class PackageActivity extends AppCompatActivity implements + StepperLayout.StepperListener, WebViewFragment.OnInstallClickedListener, + SelectLanguageFragment.OnLanguagesSelectedListener { + private final static String TAG = "PackageActivity"; private AlertDialog alertDialog; private File kmpFile; private File tempPackagePath; private static ArrayList kbDownloadEventListeners = null; private PackageProcessor kmpProcessor; + private String pkgName; + private boolean hasWelcome; + private StepperLayout mStepperLayout; + private StepperAdapter mStepperAdapter; @SuppressLint({"SetJavaScriptEnabled", "InflateParams"}) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_package_installer); + boolean silentInstall = false; String languageID = null; + ArrayList languageList = new ArrayList(); final Context context = this; Bundle bundle = getIntent().getExtras(); @@ -61,6 +72,9 @@ public class PackageActivity extends AppCompatActivity { kmpFile = new File(bundle.getString("kmpFile")); silentInstall = bundle.getBoolean("silentInstall", false); languageID = bundle.getString("language", null); + if (languageID != null && !languageID.isEmpty()) { + languageList.add(languageID); + } } File resourceRoot = new File(context.getDir("data", Context.MODE_PRIVATE).toString() + File.separator); @@ -78,6 +92,7 @@ public class PackageActivity extends AppCompatActivity { tempPackagePath = kmpProcessor.unzipKMP(kmpFile); } catch (Exception e) { + KMLog.LogException(TAG, "", e); showErrorToast(context, getString(R.string.failed_to_extract)); return; } @@ -88,135 +103,38 @@ public class PackageActivity extends AppCompatActivity { return; } + pkgName = kmpProcessor.getPackageName(pkgInfo); + hasWelcome = kmpProcessor.hasWelcome(pkgInfo); + final int keyboardCount = kmpProcessor.getKeyboardCount(pkgInfo); + + // Number of languages associated with the first keyboard in a keyboard package. + // lexical-model packages will be 0 + final int languageCount = kmpProcessor.getLanguageCount(pkgInfo, PackageProcessor.PP_KEYBOARDS_KEY, 0); + // Silent installation (skip displaying welcome.htm and user confirmation) if (silentInstall) { - installPackage(context, pkgTarget, pkgId, languageID, true); + installPackage(context, pkgTarget, pkgId, languageList, true); return; } - String pkgVersion = kmpProcessor.getPackageVersion(pkgInfo); - String pkgName = kmpProcessor.getPackageName(pkgInfo); - - toolbar = (Toolbar) findViewById(R.id.titlebar); - setSupportActionBar(toolbar); - getSupportActionBar().setTitle(null); - getSupportActionBar().setDisplayUseLogoEnabled(false); - getSupportActionBar().setDisplayShowHomeEnabled(false); - getSupportActionBar().setDisplayShowTitleEnabled(false); - getSupportActionBar().setDisplayShowCustomEnabled(true); - getSupportActionBar().setBackgroundDrawable(MainActivity.getActionBarDrawable(this)); - - TextView packageActivityTitle = new TextView(this); - packageActivityTitle.setWidth((int) getResources().getDimension(R.dimen.package_label_width)); - packageActivityTitle.setTextSize(getResources().getDimension(R.dimen.titlebar_label_textsize)); - packageActivityTitle.setGravity(Gravity.CENTER); - - String pkgTargetTitle = pkgTarget.equals(PackageProcessor.PP_TARGET_KEYBOARDS) ? - getString(R.string.install_keyboard_package) : getString(R.string.install_predictive_text_package); - String titleStr = String.format("%s %s", pkgTargetTitle, pkgVersion); - packageActivityTitle.setText(titleStr); - getSupportActionBar().setCustomView(packageActivityTitle); - - webView = (WebView) findViewById(R.id.packageWebView); - webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); - webView.getSettings().setJavaScriptEnabled(true); - webView.getSettings().setUseWideViewPort(true); - webView.getSettings().setLoadWithOverviewMode(true); - webView.getSettings().setBuiltInZoomControls(true); - webView.getSettings().setSupportZoom(true); - webView.getSettings().setTextZoom(200); - webView.setVerticalScrollBarEnabled(true); - webView.setHorizontalScrollBarEnabled(true); - webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); - - webView.setWebChromeClient(new WebChromeClient() { - }); - webView.setWebViewClient(new WebViewClient() { - @Override - public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { - } - - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - if (url != null && !url.toLowerCase().equals("about:blank")) - view.loadUrl(url); - - return true; - } - - @Override - public void onPageStarted(WebView view, String url, Bitmap favicon) { - } - - @Override - public void onPageFinished(WebView view, String url) { - } - }); - - // Determine if ad-hoc distributed KMP contains readme.htm (case-insensitive) to display - FileFilter _readmeFilter = new FileFilter() { - @Override - public boolean accept(File pathname) { - if (pathname.isFile() && FileUtils.isReadmeFile(pathname.getName())) { - return true; - } - return false; - } - }; - - File[] files = tempPackagePath.listFiles(_readmeFilter); - if (files.length > 0 && files[0].exists() && files[0].length() > 0) { - webView.loadUrl("file:///" + files[0].getAbsolutePath()); - } else { - // No readme.htm so display minimal package information - String targetString = ""; - if (pkgTarget.equals(PackageProcessor.PP_TARGET_KEYBOARDS)) { - targetString = pkgName != null && pkgName.toLowerCase().endsWith("keyboard") - ? "" : String.format(" %s", getResources().getQuantityString(R.plurals.title_keyboards, 1)); - } else if (pkgTarget.equals(PackageProcessor.PP_TARGET_LEXICAL_MODELS)) { - targetString = pkgName != null && pkgName.toLowerCase().endsWith("model") - ? "" :String.format(" %s", "model"); - } - String htmlString = String.format( - "

The %s%s Package

", - pkgName, targetString); - webView.loadData(htmlString, "text/html; charset=utf-8", "UTF-8"); - } - - initializeButtons(context, pkgId, languageID, pkgTarget); + boolean isInstallingPackage = true; + mStepperLayout = (StepperLayout) findViewById(R.id.stepperLayout); + mStepperAdapter = new StepperAdapter(getSupportFragmentManager(), this, + isInstallingPackage, tempPackagePath, pkgTarget, pkgId, pkgName, null, hasWelcome, languageID, languageCount); + mStepperLayout.setAdapter(mStepperAdapter); + mStepperLayout.setListener(this); } - /** - * Initialize buttons of package installer. - * @param context the context - * @param pkgId the keyman package id - * @param languageID the optional language id - * @param pkgTarget String: PackageProcessor.PP_TARGET_KEYBOARDS or PP_TARGET_LEXICAL_MODELS - */ - private void initializeButtons(final Context context, final String pkgId, final String languageID, final String pkgTarget) { - final Button installButton = (Button) findViewById(R.id.installButton); - final Button cancelButton = (Button) findViewById(R.id.cancelButton); - final Button finishButton = (Button) findViewById(R.id.finishButton); - - installButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - - - installPackage(context, pkgTarget, pkgId, languageID, false); - } - }); - - OnClickListener _cleanup_action = new OnClickListener() { - @Override - public void onClick(View v) { - cleanup(); - } - }; - cancelButton.setOnClickListener(_cleanup_action); - finishButton.setOnClickListener(_cleanup_action); - - updateButtonState(true); + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + // Use the result of SelectLanguageActivity and install the package + if (resultCode == 2 && data != null) { + String pkgTarget = data.getStringExtra("pkgTarget"); + String pkgId = data.getStringExtra("packageID"); + ArrayList languageList = (ArrayList)data.getSerializableExtra("languageList"); + installPackage(this, pkgTarget, pkgId, languageList, false); + } } @Override @@ -236,9 +154,9 @@ public class PackageActivity extends AppCompatActivity { FileUtils.deleteDirectory(tempPackagePath); } } catch (Exception e) { - Log.e("PackageActivity", "cleanup() failed with error " + e); + KMLog.LogException(TAG, "cleanup() failed with error ", e); } finally { - finish(); + // Don't finish() because we still need to display welcome.htm } } @@ -253,87 +171,97 @@ public class PackageActivity extends AppCompatActivity { overridePendingTransition(0, android.R.anim.fade_out); } - private void showErrorToast(Context context, String message) { - Toast.makeText(context, message, Toast.LENGTH_LONG).show(); - // Setting result to 1 so calling activity will finish too - setResult(1); - cleanup(); + @Override + public void onCompleted(View completedButton) { + Toast.makeText(this, "onCompleted", Toast.LENGTH_SHORT).show(); } - /** - * switch button visibility for package installer. - * before installation show Install and Cancel - * after installation show OK button - * @param anIsStartInstaller if true - before installation, false - after installation - */ - private void updateButtonState(boolean anIsStartInstaller) - { - final Button installButton = (Button) findViewById(R.id.installButton); - final Button cancelButton = (Button) findViewById(R.id.cancelButton); - final Button closeButton = (Button) findViewById(R.id.finishButton); - if(anIsStartInstaller) - { - installButton.setVisibility(View.VISIBLE); - cancelButton.setVisibility(View.VISIBLE); - closeButton.setVisibility(View.GONE); - } - else - { - installButton.setVisibility(View.GONE); - cancelButton.setVisibility(View.GONE); - closeButton.setVisibility(View.VISIBLE); + @Override + public void onError(VerificationError verificationError) { + Toast.makeText(this, verificationError.getErrorMessage(), Toast.LENGTH_SHORT).show(); + } + + @Override + public void onStepSelected(int newStepPosition) { + + + } + + @Override + public void onReturn() { + finish(); + } + + @Override + public void onAttachFragment(Fragment fragment) { + if (fragment instanceof WebViewFragment) { + WebViewFragment webViewFragment = (WebViewFragment) fragment; + webViewFragment.setOnInstallClickedListener(this); + } else if (fragment instanceof SelectLanguageFragment) { + SelectLanguageFragment selectLanguageFragment = (SelectLanguageFragment) fragment; + selectLanguageFragment.setOnLanguagesSelectedListener(this); } - findViewById(R.id.buttonBar).requestLayout(); } - /** - * show welcome page from installed keyboard. - * @param theInstalledPackages the installed keyboards or lexical models - * @return true if a welcomepage is available - */ - private boolean loadWelcomePage(List> theInstalledPackages) - { - boolean _found=false; - for(Map _keyboard:theInstalledPackages) { - String _customlink = _keyboard.get(KMManager.KMKey_CustomHelpLink); - if (_customlink != null) { - webView.loadUrl("file:///" + _customlink); - _found=true; - break; - } - } - if(!_found) - return false; - - updateButtonState(false); - - return true; + @Override + public void onInstallClicked(String pkgTarget, String packageID) { + // Ignore language list and install the package + installPackage(this, pkgTarget, packageID, null, false); + } + @Override + public void onLanguagesSelected(String pkgTarget, String packageID, ArrayList languageList) { + // Use the result of SelectLanguageActivity and install the package + installPackage(this, pkgTarget, packageID, languageList, false); + } + + @Override + public void onLanguagesSelected(ArrayList addKeyboardsList) { + } + + private void showErrorToast(Context context, String message) { + Toast.makeText(context, message, Toast.LENGTH_LONG).show(); + // Setting result to 1 so calling activity will finish too + setResult(1); + cleanup(); } + /** * Installs the keyboard or lexical model package, and then notifies the corresponding listeners * @param context Context The activity context * @param pkgTarget String: PackageProcessor.PP_TARGET_KEYBOARDS or PP_TARGET_LEXICAL_MODELS * @param pkgId String The Keyman package ID - * @param languageID String The optional language ID + * @param preferredLanguages ArrayList The optional array of language ID's to use * @param anSilentInstall boolean If true, don't display readme.htm/welcome.htm content during installation */ - private void installPackage(Context context, String pkgTarget, String pkgId, String languageID, boolean anSilentInstall) { + private void installPackage(Context context, String pkgTarget, String pkgId, + ArrayList preferredLanguages, boolean anSilentInstall) { try { if (pkgTarget.equals(PackageProcessor.PP_TARGET_KEYBOARDS)) { // processKMP will remove currently installed package and install + ArrayList languageList; + if (preferredLanguages != null && !preferredLanguages.isEmpty()) { + languageList = preferredLanguages; + } else { + languageList = new ArrayList(); + } //Dataset kmpDataset = new Dataset(context); //kmpDataset.keyboards.addAll(kbdsList); List> installedPackageKeyboards = - kmpProcessor.processKMP(kmpFile, tempPackagePath, PackageProcessor.PP_KEYBOARDS_KEY, languageID); + kmpProcessor.processKMP(kmpFile, tempPackagePath, PackageProcessor.PP_KEYBOARDS_KEY, languageList); // Do the notifications! boolean success = installedPackageKeyboards.size() != 0; boolean _cleanup = true; if (success) { - if(!anSilentInstall) - _cleanup = !loadWelcomePage(installedPackageKeyboards); + if(!anSilentInstall) { + String keyboardName = installedPackageKeyboards.get(0).get(KMManager.KMKey_KeyboardName); + Toast.makeText(context, + String.format(context.getString(R.string.keyboard_install_toast), keyboardName), + Toast.LENGTH_SHORT).show(); + } + _cleanup = true; notifyPackageInstallListeners(KeyboardEventHandler.EventType.PACKAGE_INSTALLED, installedPackageKeyboards, 1); if (installedPackageKeyboards != null) { @@ -353,7 +281,11 @@ public class PackageActivity extends AppCompatActivity { boolean _cleanup = true; if (success) { if(!anSilentInstall) - _cleanup = !loadWelcomePage(installedLexicalModels); + Toast.makeText(context, + context.getString(R.string.model_install_toast), + Toast.LENGTH_SHORT).show(); + + _cleanup = true; notifyLexicalModelInstallListeners(KeyboardEventHandler.EventType.LEXICAL_MODEL_INSTALLED, installedLexicalModels, 1); if (installedLexicalModels != null) { @@ -367,7 +299,7 @@ public class PackageActivity extends AppCompatActivity { } } } catch (Exception e) { - Log.e("PackageActivity", "Error " + e); + KMLog.LogException(TAG, "", e); showErrorDialog(context, pkgId, getString(R.string.no_targets_to_install)); } } @@ -375,8 +307,7 @@ public class PackageActivity extends AppCompatActivity { private void showErrorDialog(Context context, String pkgId, String message) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); - alertDialogBuilder.setTitle(String.format("%s %s %s", - getString(R.string.title_package), pkgId, getString(R.string.title_failed_to_install))); + alertDialogBuilder.setTitle(String.format(getString(R.string.title_package_failed_to_install), pkgId)); alertDialogBuilder .setMessage(message) .setCancelable(false) diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectLanguageActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectLanguageActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..804dc43c35faa41f7a35b013ffeeec2998e0ef82 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectLanguageActivity.java @@ -0,0 +1,117 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ +package com.tavultesoft.kmapro; + +import android.content.Context; +import android.os.Bundle; +import android.view.View; +import android.widget.Toast; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.fragment.app.Fragment; + +import com.stepstone.stepper.StepperLayout; +import com.stepstone.stepper.VerificationError; +import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.packages.PackageProcessor; +import com.tavultesoft.kmea.util.KMLog; + +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/** + * Keyman Settings --> KeymanInstallActivity --> SelectPackageActivity --> SelectLanguageActivity + * Also available during keyboard package installation that involves a language choice. + * Displays a list of available language names for the user to add for a given installed packageID/keyboardID. + */ +public class SelectLanguageActivity extends AppCompatActivity implements + StepperLayout.StepperListener, SelectLanguageFragment.OnLanguagesSelectedListener { + private final static String TAG = "SelectLanguageActivity"; + private File packagePath; + private String packageID; + private boolean isInstallingPackage; + private Keyboard keyboard; + private StepperLayout mStepperLayout; + private StepperAdapter mStepperAdapter; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_select_language); + + Bundle bundle = getIntent().getExtras(); + keyboard = (Keyboard)bundle.getSerializable("keyboard"); + packagePath = (File)bundle.getSerializable("packagePath"); + packageID = bundle.getString("packageID"); + isInstallingPackage = bundle.getBoolean("isInstallingPackage"); + String pkgTarget = PackageProcessor.PP_TARGET_KEYBOARDS; + + File resourceRoot = new File(this.getDir("data", Context.MODE_PRIVATE).toString() + File.separator); + PackageProcessor kmpProcessor = new PackageProcessor(resourceRoot); + JSONObject pkgInfo = kmpProcessor.loadPackageInfo(packagePath); + + String pkgName = kmpProcessor.getPackageName(pkgInfo); + boolean hasWelcome = kmpProcessor.hasWelcome(pkgInfo); + + + if (keyboard == null) { + KMLog.LogError(TAG, "Package " + packageID + " has 0 keyboards"); + return; + } + + mStepperLayout = (StepperLayout) findViewById(R.id.stepperLayout); + mStepperAdapter = new StepperAdapter(getSupportFragmentManager(), this, + isInstallingPackage, packagePath, pkgTarget, packageID, pkgName, keyboard, hasWelcome); + mStepperLayout.setAdapter(mStepperAdapter); + mStepperLayout.setListener(this); + + } + + @Override + public void onCompleted(View completedButton) { + Toast.makeText(this, "onCompleted", Toast.LENGTH_SHORT).show(); + } + + @Override + public void onError(VerificationError verificationError) { + Toast.makeText(this, verificationError.getErrorMessage(), Toast.LENGTH_SHORT).show(); + } + + @Override + public void onStepSelected(int newStepPosition) { + + + } + + @Override + public void onReturn() { + finish(); + } + + @Override + public void onAttachFragment(Fragment fragment) { + if (fragment instanceof SelectLanguageFragment) { + SelectLanguageFragment selectLanguageFragment = (SelectLanguageFragment) fragment; + selectLanguageFragment.setOnLanguagesSelectedListener(this); + } + } + + @Override + public void onLanguagesSelected(String pkgTarget, String packageID, ArrayList languageList) { + } + + @Override + public void onLanguagesSelected(ArrayList addKeyboardsList) { + for (Keyboard k : addKeyboardsList) { + KMManager.addKeyboard(this, k); + String confirmation = String.format(getString(R.string.added_language_to_keyboard), + k.getLanguageName(), k.getKeyboardName()); + Toast.makeText(this, confirmation, Toast.LENGTH_LONG).show(); + } + } +} diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectLanguageFragment.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectLanguageFragment.java new file mode 100644 index 0000000000000000000000000000000000000000..0896c054cae488969731d8f49a071d4062af3d4e --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectLanguageFragment.java @@ -0,0 +1,302 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ +package com.tavultesoft.kmapro; + +import android.content.Context; +import android.graphics.Typeface; +import android.os.Bundle; +import android.os.Handler; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ListView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.fragment.app.Fragment; + +import com.stepstone.stepper.BlockingStep; +import com.stepstone.stepper.StepperLayout; +import com.stepstone.stepper.VerificationError; +import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.KeyboardController; +import com.tavultesoft.kmea.packages.PackageProcessor; +import com.tavultesoft.kmea.util.BCP47; +import com.tavultesoft.kmea.util.KMLog; + +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Displays a list of available language names for the user to add for a given installed packageID/keyboardID. + */ +public final class SelectLanguageFragment extends Fragment implements BlockingStep { + private static final String TAG = "SelectLanguageFragment"; + private static ArrayList> list = null; + private static KMListAdapter adapter = null; + private static Typeface titleFont = null; + private static final String titleKey = "title"; + private static final String subtitleKey = "subtitle"; + private static final String iconKey = "icon"; + private static final String isEnabledKey = "isEnabled"; + private static Context context; + private Boolean isInstallingPackage = true; + private static final boolean excludeInstalledLanguages = false; + private static String packageID = null; + private static String languageID = null; + private ArrayList languageList = new ArrayList(); + private ArrayList addKeyboardsList = new ArrayList(); + private String title_no_install = null; + private TextView textView; + private File packagePath; + private OnLanguagesSelectedListener callback; + + public void setOnLanguagesSelectedListener(OnLanguagesSelectedListener callback) { + this.callback = callback; + } + + // This interface to be implemented by calling Activity + public interface OnLanguagesSelectedListener { + public void onLanguagesSelected(String pkgTarget, String packageID, ArrayList languageList); + public void onLanguagesSelected(ArrayList addKeyboardsList); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + + View v = inflater.inflate(R.layout.fragment_select_language, container, false); + + super.onCreate(savedInstanceState); + context = getActivity(); + + + final ListView listView = v.findViewById(R.id.listView); + listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); + listView.setItemsCanFocus(false); + listView.setFastScrollEnabled(true); + + Bundle bundle = getArguments(); + if (bundle == null) { + KMLog.LogError(TAG, "No bundle parameters"); + return v; + } + + isInstallingPackage = bundle.getBoolean("tempPath"); + File resourceRoot = new File(getActivity().getDir("data", Context.MODE_PRIVATE).toString() + File.separator); + PackageProcessor kmpProcessor = new PackageProcessor(resourceRoot); + // Get the list of available Keyboards from the keyboard package kmp.json (could be temp path or installed path) + packagePath = (File)bundle.getSerializable("packagePath"); + packageID = bundle.getString("packageID"); + languageID = bundle.getString("languageID"); + + JSONObject pkgInfo = kmpProcessor.loadPackageInfo(packagePath); + Keyboard keyboard = bundle.containsKey("keyboard") ? (Keyboard)bundle.getSerializable("keyboard") : + kmpProcessor.getKeyboard(pkgInfo, packageID, 0); + if (keyboard == null) { + KMLog.LogError(TAG, "Package " + packageID + " has 0 keyboards"); + return v; + } + final String keyboardID = keyboard.getKeyboardID(); + final String keyboardName = keyboard.getKeyboardName(); + String title_install = String.format(getString(R.string.title_select_languages_for_package), keyboardName); + title_no_install = getString(R.string.all_languages_installed); + + final Toolbar toolbar = v.findViewById(R.id.list_toolbar); + ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar); + ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar(); + if (actionBar != null) { + actionBar.setTitle(null); + actionBar.setDisplayUseLogoEnabled(false); + actionBar.setDisplayShowHomeEnabled(false); + actionBar.setDisplayShowTitleEnabled(false); + actionBar.setDisplayShowCustomEnabled(true); + + // When installing packages, use the Keyman theme for the accent + if (isInstallingPackage) { + actionBar.setBackgroundDrawable(MainActivity.getActionBarDrawable(getContext())); + + // Hide the optional accent that's used in Settings menus + View accent = v.findViewById(R.id.bar_accent); + accent.setVisibility(View.GONE); + } + } + + textView = v.findViewById(R.id.bar_title); + textView.setText(title_no_install); + if (titleFont != null) { + textView.setTypeface(titleFont, Typeface.BOLD); + } + + List availableKeyboardsList = kmpProcessor.getKeyboardList( + pkgInfo, packageID, keyboardID, isInstallingPackage, excludeInstalledLanguages); + int position = KeyboardController.INDEX_NOT_FOUND; + if (languageID != null && !languageID.isEmpty()) { + // Add default languageID to the list of selected languages + languageList.add(languageID); + + // Determine position of matching language ID (if it exists) + for (int i=0; i>(); + for (Keyboard k : availableKeyboardsList) { + HashMap hashMap = new HashMap<>(); + hashMap.put(titleKey, k.getLanguageName()); + // No need to display subtitleKey - k.getLanguageID() + hashMap.put("packageID", packageID); + String enable = "true"; + String icon = noIcon; + if (!excludeInstalledLanguages && !isInstallingPackage && KeyboardController.getInstance().keyboardExists( + k.getPackageID(), k.getKeyboardID(), k.getLanguageID())) { + // If Activity is listing an installed keyboard package, mark installed keyboards with a check + icon = String.valueOf(R.drawable.ic_check); + enable = "false"; + } else { + // Update title + textView.setText(title_install); + } + hashMap.put(iconKey, icon); + hashMap.put(isEnabledKey, enable); + list.add(hashMap); + } + + String[] from = new String[]{titleKey, subtitleKey, iconKey}; + int[] to = new int[]{R.id.text1, R.id.text2, com.tavultesoft.kmea.R.id.image1}; + + adapter = new KMListAdapter(context, list, R.layout.list_row_layout2, from, to); + listView.setAdapter(adapter); + + // If languageID exists, pre-select adapter with the language + if (position != KeyboardController.INDEX_NOT_FOUND) { + listView.setItemChecked(position, true); + } + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + Keyboard k = availableKeyboardsList.get(position); + if (isInstallingPackage) { + // Add/Remove the selected language from languageList + if (languageList == null) { + languageList = new ArrayList(); + } + String selectedLanguageID = k.getLanguageID(); + if (languageList.contains(selectedLanguageID)) { + languageList.remove(selectedLanguageID); + } else { + languageList.add(selectedLanguageID); + } + } else { + // Otherwise, add the language association + if (addKeyboardsList == null) { + addKeyboardsList = new ArrayList(); + } + if (addKeyboardsList.contains(k)) { + addKeyboardsList.remove(k); + } else { + addKeyboardsList.add(k); + } + } + + // Disable install button if no languages selected or all languages already installed + checkLanguages(); + } + }); + + return v; + } + + /** + * Validates a language has been selected in the "Select Language" step. + * Also enables/disables "NEXT" button accordingly. + * @return VerificationError + */ + public VerificationError checkLanguages() { + StepperLayout mStepperLayout = (StepperLayout) getActivity().findViewById(R.id.stepperLayout); + + // Only applies if stepper is in "Select Language" step + if ((isInstallingPackage && mStepperLayout.getCurrentStepPosition() == 1) || + (!isInstallingPackage && mStepperLayout.getCurrentStepPosition() == 0)) { + // Two scenarios to disable "NEXT" button + if (title_no_install != null && textView.getText().equals(title_no_install)) { + mStepperLayout.setNextButtonVerificationFailed(true); + return new VerificationError("All languages already installed"); + } else if (languageList.size() == 0 && addKeyboardsList.size() == 0) { + mStepperLayout.setNextButtonVerificationFailed(true); + return new VerificationError("No languages selected"); + } else { + mStepperLayout.setNextButtonVerificationFailed(false); + } + } else { + mStepperLayout.setNextButtonVerificationFailed(false); + } + + return null; + } + + @Override + public void onNextClicked(final StepperLayout.OnNextClickedCallback callback) { + // Send data to calling Activity + if (!isInstallingPackage) { + this.callback.onLanguagesSelected(addKeyboardsList); + } else { + this.callback.onLanguagesSelected(PackageProcessor.PP_TARGET_KEYBOARDS, packageID, languageList); + } + + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + //you can do anythings you want + callback.goToNextStep(); + } + }, 1000L);// delay open another fragment, + } + @Override + public void onCompleteClicked(StepperLayout.OnCompleteClickedCallback callback) { + if (!isInstallingPackage) { + this.callback.onLanguagesSelected(addKeyboardsList); + } + getActivity().finish(); + } + @Override + public void onBackClicked(StepperLayout.OnBackClickedCallback callback) { + callback.goToPrevStep(); + + // Re-enable "NEXT" button + StepperLayout mStepperLayout = (StepperLayout) getActivity().findViewById(R.id.stepperLayout); + mStepperLayout.setNextButtonVerificationFailed(false); + } + @Override + public VerificationError verifyStep() { + return checkLanguages(); + } + + @Override + public void onSelected() { + checkLanguages(); + } + + @Override + public void onError(@NonNull VerificationError error) { + // do nothing + } + +} diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectPackageActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectPackageActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..bd298a42ad21d225dfa63a81faaa1f726d93e3a5 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SelectPackageActivity.java @@ -0,0 +1,119 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ + +package com.tavultesoft.kmapro; + +import android.content.Context; +import android.content.Intent; +import android.graphics.Typeface; +import android.os.Bundle; +import android.view.View; +import android.view.Window; +import android.widget.AdapterView; +import android.widget.ListAdapter; +import android.widget.ListView; +import android.widget.SimpleAdapter; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.KeyboardController; +import com.tavultesoft.kmea.util.KMLog; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Keyman Settings --> KeymanInstallActivity --> SelectPackageActivity + * Displays a list of installed package ID / keyboard IDs so the user can select a language from the kmp.json + */ +public final class SelectPackageActivity extends AppCompatActivity { + private static final String TAG = "SelectPackageActivity"; + private static ArrayList> list = null; + private static Typeface titleFont = null; + private static final String titleKey = "title"; + private static final String subtitleKey = "subtitle"; + private static final String iconKey = "icon"; + private static Context context; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + supportRequestWindowFeature(Window.FEATURE_NO_TITLE); + context = this; + + setContentView(R.layout.activity_list_layout); + final Toolbar toolbar = findViewById(R.id.list_toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setDisplayShowHomeEnabled(true); + getSupportActionBar().setDisplayShowTitleEnabled(false); + + final ListView listView = findViewById(R.id.listView); + listView.setFastScrollEnabled(true); + + Bundle bundle = getIntent().getExtras(); + + final TextView textView = findViewById(R.id.bar_title); + textView.setText(getString(R.string.title_select_keyboard_package_list)); + if (titleFont != null) { + textView.setTypeface(titleFont, Typeface.BOLD); + } + + List packagesList = KeyboardController.getInstance().getInstalledPackagesList(); + if (packagesList == null) { + // Should never actually happen + KMLog.LogError(TAG, "Installed keyboard package list is empty"); + finish(); + } + + list = new ArrayList>(); + for (Keyboard k : packagesList) { + String keyboardName = k.getKeyboardName(); + String pkgID = k.getPackageID(); + final String noIcon = "0"; + HashMap hashMap = new HashMap<>(); + hashMap.put(titleKey, keyboardName); + hashMap.put(subtitleKey, pkgID); + String icon = String.valueOf(R.drawable.ic_arrow_forward); + hashMap.put(iconKey, icon); + list.add(hashMap); + } + + String[] from = new String[]{titleKey, subtitleKey, iconKey}; + int[] to = new int[]{com.tavultesoft.kmea.R.id.text1, com.tavultesoft.kmea.R.id.text2, com.tavultesoft.kmea.R.id.image1}; + + ListAdapter adapter = new SimpleAdapter(context, list, com.tavultesoft.kmea.R.layout.list_row_layout2, from, to) { + }; + listView.setAdapter(adapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + HashMap hashMap = (HashMap) parent.getItemAtPosition(position); + Bundle bundle = new Bundle(); + bundle.putSerializable("keyboard", packagesList.get(position)); + String pkgID = hashMap.get(subtitleKey); + File packagePath = new File(KMManager.getPackagesDir(), pkgID); + bundle.putSerializable("packagePath", packagePath); + bundle.putString("packageID", pkgID); + bundle.putBoolean("isInstallingPackage", false); + Intent intent = new Intent(context, SelectLanguageActivity.class); + intent.putExtras(bundle); + context.startActivity(intent); + } + }); + } + + @Override + public boolean onSupportNavigateUp() { + super.onBackPressed(); + return true; + } +} diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SplashScreenActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SplashScreenActivity.java index 543124668f29fd323ea5f226334b4da9919ea5cb..7dda328be94f92cd090f714c50f97160d957ba3e 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SplashScreenActivity.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/SplashScreenActivity.java @@ -8,9 +8,12 @@ import android.app.Activity; import android.content.Intent; import android.widget.TextView; +import com.tavultesoft.kmea.util.KMLog; + import java.util.Calendar; public class SplashScreenActivity extends Activity { + private final static String TAG = "Splash"; // For now, disable this Activity so app is not delayed showing version/copyright text private static int SPLASH_TIME_OUT = 0; // msec @@ -27,6 +30,7 @@ public class SplashScreenActivity extends Activity { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); ver = String.format("%s: %s", version.getText(), pInfo.versionName); } catch (PackageManager.NameNotFoundException e) { + KMLog.LogException(TAG, "", e); // Could not get version number } // TODO: Add version and copyright info when Android supports TextViews in the splash screen diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/StepperAdapter.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/StepperAdapter.java new file mode 100644 index 0000000000000000000000000000000000000000..d6993ef35bff34de16a3a3fb5b2ebd3bd492049b --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/StepperAdapter.java @@ -0,0 +1,238 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ +package com.tavultesoft.kmapro; + +import android.content.Context; +import android.os.Bundle; + +import androidx.annotation.IntRange; +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentManager; + +import com.stepstone.stepper.Step; +import com.stepstone.stepper.adapter.AbstractFragmentStepAdapter; +import com.stepstone.stepper.viewmodel.StepViewModel; +import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.packages.PackageProcessor; +import com.tavultesoft.kmea.util.FileUtils; + +import java.io.File; + +/** + * This adapter manages the Stepper that helps the user know how many steps they will encounter while + * installing a package. + */ +public class StepperAdapter extends AbstractFragmentStepAdapter { + private static final String CURRENT_STEP_POSITION_KEY = "messageResourceId"; + private boolean isInstallingPackage; + private File tempPackagePath; + private String pkgTarget; + private String pkgName; + + private String packageID; + private Keyboard keyboard; + + private String languageID; + private int languageCount; + private boolean hasWelcome; + + + /** + * Constructor where languageID and languageCount are empty + * @param fm + * @param context + * @param isInstallingPackage + * @param tempPackagePath + * @param pkgTarget + * @param packageID + * @param pkgName + * @param keyboard + * @param hasWelcome + */ + public StepperAdapter(FragmentManager fm, Context context, + boolean isInstallingPackage, File tempPackagePath, + String pkgTarget, String packageID, String pkgName, + Keyboard keyboard, + boolean hasWelcome) { + super(fm, context); + this.isInstallingPackage = isInstallingPackage; + this.tempPackagePath = tempPackagePath; + this.pkgTarget = pkgTarget; + this.packageID = packageID; + this.pkgName = pkgName; + this.keyboard = keyboard; + this.hasWelcome = hasWelcome; + this.languageID = null; // not filled + this.languageCount = 0; + } + + public StepperAdapter(FragmentManager fm, Context context, + boolean isInstallingPackage, File tempPackagePath, + String pkgTarget, String packageID, String pkgName, + Keyboard keyboard, + boolean hasWelcome, + String languageID, int languageCount) { + super(fm, context); + this.isInstallingPackage = isInstallingPackage; + this.tempPackagePath = tempPackagePath; + this.pkgTarget = pkgTarget; + this.packageID = packageID; + this.pkgName = pkgName; + this.keyboard = keyboard; + this.hasWelcome = hasWelcome; + this.languageID = languageID; + this.languageCount = languageCount; + } + + @Override + public Step createStep(int position) { + switch (position){ + case 0: + if (isInstallingPackage) { + final WebViewFragment step1 = CreateWebView(position, FileUtils.README_HTM); + return step1; + } else { + final SelectLanguageFragment step1 = new SelectLanguageFragment(); + Bundle b1 = new Bundle(); + b1.putInt(CURRENT_STEP_POSITION_KEY, position); + b1.putBoolean("tempPath", isInstallingPackage); + b1.putSerializable("packagePath", tempPackagePath); + b1.putString("packageID", packageID); + b1.putString("languageID", languageID); + if (keyboard != null) { + b1.putSerializable("keyboard", keyboard); + } + step1.setArguments(b1); + return step1; + } + case 1: + if (getCount() > 2) { + final SelectLanguageFragment step2 = new SelectLanguageFragment(); + Bundle b2 = new Bundle(); + b2.putInt(CURRENT_STEP_POSITION_KEY, position); + b2.putBoolean("tempPath", true); + b2.putSerializable("packagePath", tempPackagePath); + b2.putString("packageID", packageID); + b2.putString("languageID", languageID); + if (keyboard != null) { + b2.putSerializable("keyboard", keyboard); + } + step2.setArguments(b2); + return step2; + } else { + final WebViewFragment step2 = CreateWebView(position, FileUtils.WELCOME_HTM); + return step2; + } + case 2: + final WebViewFragment step3 = CreateWebView(position, FileUtils.WELCOME_HTM); + return step3; + } + return null; + } + + /** + * Determine the number of states for the StepperAdapter + * !isInstallingPackage: + * 1 dot: keyboard package already installed, so just use SelectLanguageFragment + * + * Keyboard package: + * 1 dot: package has one language, no welcome.htm. + * 2 dots: package has one language, has welcome.htm. + * 2 dots: package has multiple languages but no welcome.htm. + * 3 dots: package has multiple languages and welcome.htm. + * + * Lexical Model package: + * 2 dots + * @return int + */ + @Override + public int getCount() { + int count = 3; + if (pkgTarget != null) { + if (pkgTarget.equals(PackageProcessor.PP_LEXICAL_MODELS_KEY)) { + count = 2; + } else if (pkgTarget.equals(PackageProcessor.PP_KEYBOARDS_KEY)) { + if (!isInstallingPackage) { + count = 1; + } + else if (languageCount <= 1) { + // One or less language + count = (!hasWelcome) ? 1 : 2; + } else { + // Multiple languages + count = (!hasWelcome) ? 2 : 3; + } + } + } + return count; + } + + @NonNull + @Override + public StepViewModel getViewModel(@IntRange(from = 0) int position) { + //Override this method to customize the steps + switch (position){ + case 0: + // readme.htm EndButton uses "NEXT" button + String buttonLabel = context.getString(R.string.label_next); + if (getCount() <= 2) { + // If only 1-2 steps, use "INSTALL" + buttonLabel = context.getString(R.string.label_install); + } + return new StepViewModel.Builder(context) + .setEndButtonLabel(buttonLabel) + .create(); + case 1: + // Language picker EndButton uses "INSTALL" button + buttonLabel = context.getString(R.string.label_install); + boolean backButtonVisible = true; + if (getCount() == 2) { + // If only two steps, use "OK" and hide back button + buttonLabel = context.getString(R.string.label_ok); + backButtonVisible = false; + } + return new StepViewModel.Builder(context) + .setEndButtonLabel(buttonLabel) + .setBackButtonVisible(backButtonVisible) + .create(); + case 2: + // Adapter style defaults last step EndButton to "OK". Hide back button + return new StepViewModel.Builder(context) + .setBackButtonVisible(false) + .create(); + } + return null; + } + + /** + * Utility to create WebViewFragment + * @param position int position in the adapter + * @param fileName FileUtils.README_HTM or FileUtils.WELCOME_HTM + * @return WebViewFragment + */ + private WebViewFragment CreateWebView(int position, String fileName) { + boolean isInstallButton = false; + if (FileUtils.isReadmeFile(fileName)) { + if (pkgTarget.equals(PackageProcessor.PP_TARGET_LEXICAL_MODELS)) { + isInstallButton = true; + } else if (pkgTarget.equals(PackageProcessor.PP_TARGET_KEYBOARDS)) { + if (languageCount <= 1) { + isInstallButton = true; + } + } + } + + WebViewFragment step = new WebViewFragment(); + Bundle bundle = new Bundle(); + bundle.putInt(CURRENT_STEP_POSITION_KEY, position); + bundle.putSerializable("tempPackagePath", tempPackagePath); + bundle.putString("packageID", packageID); + bundle.putString("pkgTarget", pkgTarget); + bundle.putString("pkgName", pkgName); + bundle.putString("fileName", fileName); + bundle.putBoolean("isInstallButton", isInstallButton); + step.setArguments(bundle); + return step; + } +} \ No newline at end of file diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/WebBrowserActivity.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/WebBrowserActivity.java index 022234f7be1282f3d83dc1248318975d6fef76fe..d1df00daa92290829c896114215934b7bb48f0a9 100644 --- a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/WebBrowserActivity.java +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/WebBrowserActivity.java @@ -8,7 +8,7 @@ import java.net.MalformedURLException; import java.net.URL; import com.tavultesoft.kmea.KMManager; -import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMPLink; import android.annotation.SuppressLint; import android.content.Context; @@ -43,6 +43,8 @@ import android.webkit.WebViewClient; import androidx.appcompat.widget.Toolbar; import androidx.appcompat.app.AppCompatActivity; +import com.tavultesoft.kmea.util.KMLog; + public class WebBrowserActivity extends AppCompatActivity { private static final String TAG = "WebBrowserActivity"; private WebView webView; @@ -263,7 +265,7 @@ public class WebBrowserActivity extends AppCompatActivity { if (lowerURL.equals("about:blank")) { return true; // never load a blank page, e.g. when the component initializes } - if (FileUtils.isKeymanLink(lowerURL)) { + if (KMPLink.isKeymanDownloadLink(lowerURL)) { // KMAPro main activity will handle this intent // Pass original url because path and query are case-sensitive Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); @@ -321,6 +323,8 @@ public class WebBrowserActivity extends AppCompatActivity { try { new URL(urlStr); } catch (MalformedURLException e) { + KMLog.LogException(TAG, "", e); + if (Patterns.WEB_URL.matcher(String.format("%s%s", "http://", urlStr)).matches()) { urlStr = String.format("%s%s", "http://", urlStr); } else { diff --git a/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/WebViewFragment.java b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/WebViewFragment.java new file mode 100644 index 0000000000000000000000000000000000000000..5f7903777aaed971e460d2cd65c6549a9de800c5 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/WebViewFragment.java @@ -0,0 +1,231 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ +package com.tavultesoft.kmapro; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.fragment.app.Fragment; + +import com.stepstone.stepper.BlockingStep; +import com.stepstone.stepper.StepperLayout; +import com.stepstone.stepper.VerificationError; +import com.tavultesoft.kmea.packages.PackageProcessor; +import com.tavultesoft.kmea.util.FileUtils; + +import android.graphics.Bitmap; +import android.os.Bundle; +import android.os.Handler; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.WebChromeClient; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.TextView; + +import java.io.File; +import java.io.FileFilter; + +/** + * Fragment to display either readme.htm or welcome.htm in a WebView + * If button is "INSTALL", callback to PackageActivity will install the package + */ +public class WebViewFragment extends Fragment implements BlockingStep { + private File tempPackagePath; + private String packageID; + private String pkgTarget; + private String pkgName; + private String fileName; + private boolean isInstallButton = false; + private OnInstallClickedListener callback; + + public void setOnInstallClickedListener(OnInstallClickedListener callback) { + this.callback = callback; + } + + // This interface to be implemented by calling Activity + public interface OnInstallClickedListener { + public void onInstallClicked(String pkgTarget, String packageID); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View v = inflater.inflate(R.layout.fragment_webview_layout, container, false); + Bundle bundle = getArguments(); + + if (bundle != null) { + if (bundle.containsKey("tempPackagePath")) { + tempPackagePath = (File)bundle.getSerializable("tempPackagePath"); + } + if (bundle.containsKey("packageID")) { + packageID = bundle.getString("packageID"); + } + if (bundle.containsKey("pkgTarget")) { + pkgTarget = bundle.getString("pkgTarget"); + } + if (bundle.containsKey("pkgName")) { + pkgName = bundle.getString("pkgName"); + } + if (bundle.containsKey("fileName")) { + fileName = bundle.getString("fileName"); + } + if (bundle.containsKey("isInstallButton")) { + isInstallButton = bundle.getBoolean("isInstallButton"); + } + } + + Toolbar toolbar = (Toolbar) v.findViewById(R.id.titlebar); + ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar); + ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar(); + if (actionBar != null) { + actionBar.setTitle(null); + actionBar.setDisplayUseLogoEnabled(false); + actionBar.setDisplayShowHomeEnabled(false); + actionBar.setDisplayShowTitleEnabled(false); + actionBar.setDisplayShowCustomEnabled(true); + actionBar.setBackgroundDrawable(MainActivity.getActionBarDrawable(getContext())); + } + + TextView packageActivityTitle = (TextView) v.findViewById(R.id.bar_title); + packageActivityTitle.setWidth((int) getResources().getDimension(R.dimen.package_label_width)); + + String titleStr = pkgTarget.equals(PackageProcessor.PP_TARGET_KEYBOARDS) ? + getString(R.string.install_keyboard_package) : + getString(R.string.install_predictive_text_package); + if (FileUtils.isWelcomeFile(fileName)) { + titleStr = String.format(getString(R.string.welcome_package), pkgName); + } + packageActivityTitle.setText(titleStr); + + WebView webView = (WebView) v.findViewById(R.id.packageWebView); + webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); + webView.getSettings().setJavaScriptEnabled(true); + webView.getSettings().setUseWideViewPort(true); + webView.getSettings().setLoadWithOverviewMode(true); + webView.getSettings().setBuiltInZoomControls(true); + webView.getSettings().setSupportZoom(true); + webView.setVerticalScrollBarEnabled(true); + webView.setHorizontalScrollBarEnabled(true); + webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); + + webView.setWebChromeClient(new WebChromeClient() { + }); + webView.setWebViewClient(new WebViewClient() { + @Override + public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { + } + + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + if (url != null && !url.toLowerCase().equals("about:blank")) + view.loadUrl(url); + + return true; + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + } + + @Override + public void onPageFinished(WebView view, String url) { + // Inject a meta viewport tag into the head of the file if it doesn't exist + webView.loadUrl( + "javascript:(function() {" + + "if(!document.querySelectorAll('meta[name=viewport]').length) {"+ + "let meta=document.createElement('meta');"+ + "meta.name='viewport';"+ + "meta.content='width=device-width, initial-scale=1';"+ + "document.head.appendChild(meta);"+ + "}"+ + "})()" + ); + } + }); + + // Determine if ad-hoc distributed KMP contains readme.htm/welcome.htm (case-insensitive) to display + FileFilter _readmeFilter = new FileFilter() { + @Override + public boolean accept(File pathname) { + if (pathname.isFile() && FileUtils.isReadmeFile(pathname.getName())) { + return true; + } + return false; + } + }; + FileFilter _welcomeFilter = new FileFilter() { + @Override + public boolean accept(File pathname) { + if (pathname.isFile() && FileUtils.isWelcomeFile(pathname.getName())) { + return true; + } + return false; + } + }; + + File[] files = (FileUtils.isReadmeFile(fileName)) ? tempPackagePath.listFiles(_readmeFilter) : + tempPackagePath.listFiles(_welcomeFilter); + if (files.length > 0 && files[0].exists() && files[0].length() > 0) { + webView.loadUrl("file:///" + files[0].getAbsolutePath()); + } else { + // No readme.htm so display minimal package information + String targetString = ""; + if (pkgTarget.equals(PackageProcessor.PP_TARGET_KEYBOARDS)) { + targetString = pkgName != null && pkgName.toLowerCase().endsWith("keyboard") + ? "" : String.format(" %s", getResources().getQuantityString(R.plurals.title_keyboards, 1)); + } else if (pkgTarget.equals(PackageProcessor.PP_TARGET_LEXICAL_MODELS)) { + targetString = pkgName != null && pkgName.toLowerCase().endsWith("model") + ? "" :String.format(" %s", "model"); + } + String htmlString = String.format( + "

The %s%s Package

", + pkgName, targetString); + // If welcome missing, don't load anything + if (FileUtils.isReadmeFile(fileName)) { + webView.loadData(htmlString, "text/html; charset=utf-8", "UTF-8"); + } + } + + return v; + + } + @Override + public void onNextClicked(final StepperLayout.OnNextClickedCallback callback) { + // Send data to calling Activity + if (isInstallButton) { + this.callback.onInstallClicked(pkgTarget, packageID); + } + + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + //you can do anythings you want + callback.goToNextStep(); + } + }, 1000L);// delay open another fragment, + } + + @Override + public void onCompleteClicked(StepperLayout.OnCompleteClickedCallback callback) { + getActivity().finish(); + } + @Override + public void onBackClicked(StepperLayout.OnBackClickedCallback callback) { + callback.goToPrevStep(); + } + @Override + public VerificationError verifyStep() { + return null; + } + @Override + public void onSelected() { + } + @Override + public void onError(@NonNull VerificationError error) { + } +} \ No newline at end of file diff --git a/android/KMAPro/kMAPro/src/main/res/color/ms_custom_button_text_color.xml b/android/KMAPro/kMAPro/src/main/res/color/ms_custom_button_text_color.xml new file mode 100644 index 0000000000000000000000000000000000000000..b11bc35da0ce48df433820103eebd2f305d35e88 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/res/color/ms_custom_button_text_color.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/android/KMAPro/kMAPro/src/main/res/drawable-mdpi/ic_content_add.png b/android/KMAPro/kMAPro/src/main/res/drawable-mdpi/ic_content_add.png index 23bf119211e02b139ad2e0961bc71662ce1caf1e..1c18967490678e7250b137450b68da2a9342aef0 100644 Binary files a/android/KMAPro/kMAPro/src/main/res/drawable-mdpi/ic_content_add.png and b/android/KMAPro/kMAPro/src/main/res/drawable-mdpi/ic_content_add.png differ diff --git a/android/KMAPro/kMAPro/src/main/res/drawable-xxhdpi/ic_folder_open.png b/android/KMAPro/kMAPro/src/main/res/drawable-xxhdpi/ic_folder_open.png index 1eb3365e090b4bdc3c2837b4815d93b0e68706ad..8136a770e5275f48ec672467d5beaea6c8f264b1 100644 Binary files a/android/KMAPro/kMAPro/src/main/res/drawable-xxhdpi/ic_folder_open.png and b/android/KMAPro/kMAPro/src/main/res/drawable-xxhdpi/ic_folder_open.png differ diff --git a/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_content_add.png b/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_content_add.png new file mode 100644 index 0000000000000000000000000000000000000000..60cbd9cb632c9f58fc7dd3379dda609390ca5f04 Binary files /dev/null and b/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_content_add.png differ diff --git a/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_folder_open.png b/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_folder_open.png index e6faa991f402255879a2c6dbabfcbc852095eda8..3bd21a35294683bd41e28277af3b425d64755be5 100644 Binary files a/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_folder_open.png and b/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_folder_open.png differ diff --git a/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_light_action_overflow.png b/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_light_action_overflow.png new file mode 100644 index 0000000000000000000000000000000000000000..c32d61b388a4b401eb4c9432681feb1dd40c4c9e Binary files /dev/null and b/android/KMAPro/kMAPro/src/main/res/drawable-xxxhdpi/ic_light_action_overflow.png differ diff --git a/android/KMAPro/kMAPro/src/main/res/drawable/ic_action_back.xml b/android/KMAPro/kMAPro/src/main/res/drawable/ic_action_back.xml new file mode 100644 index 0000000000000000000000000000000000000000..165d535d3d04aabb03c98fdc7076788b415fed28 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/res/drawable/ic_action_back.xml @@ -0,0 +1,4 @@ + + diff --git a/android/KMAPro/kMAPro/src/main/res/drawable/ic_action_forward.xml b/android/KMAPro/kMAPro/src/main/res/drawable/ic_action_forward.xml new file mode 100644 index 0000000000000000000000000000000000000000..15efecf5575e17ac1d0100b43debcbba32b5bc04 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/res/drawable/ic_action_forward.xml @@ -0,0 +1,4 @@ + + diff --git a/android/KMAPro/kMAPro/src/main/res/layout/activity_package_installer.xml b/android/KMAPro/kMAPro/src/main/res/layout/activity_package_installer.xml index 88846dcc8c8d2d8abefa09c2613c962dd249afc7..a46115c1ccc84fec6ebc542b28bf664597a18495 100644 --- a/android/KMAPro/kMAPro/src/main/res/layout/activity_package_installer.xml +++ b/android/KMAPro/kMAPro/src/main/res/layout/activity_package_installer.xml @@ -8,65 +8,21 @@ tools:context=".PackageActivity" > - - + - - - - - - - - - + android:layout_alignParentBottom="true" + app:ms_showBackButtonOnFirstStep="true" + app:ms_backButtonColor="@color/keyman_blue" + app:ms_backButtonText="@string/label_back" + app:ms_nextButtonColor="@color/ms_custom_button_text_color" + app:ms_nextButtonText="@string/label_next" + app:ms_completeButtonColor="@color/keyman_blue" + app:ms_completeButtonText="@string/label_ok" + app:ms_stepperType="dots" /> diff --git a/android/KMAPro/kMAPro/src/main/res/layout/activity_select_language.xml b/android/KMAPro/kMAPro/src/main/res/layout/activity_select_language.xml new file mode 100644 index 0000000000000000000000000000000000000000..b3ef26852d8d091ab2bbf3a701cd0246237ba126 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/res/layout/activity_select_language.xml @@ -0,0 +1,28 @@ + + + + + + + + + diff --git a/android/KMAPro/kMAPro/src/main/res/layout/fragment_select_language.xml b/android/KMAPro/kMAPro/src/main/res/layout/fragment_select_language.xml new file mode 100644 index 0000000000000000000000000000000000000000..df9b471d207ce4286b01d670ed4d30df330147c8 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/res/layout/fragment_select_language.xml @@ -0,0 +1,14 @@ + + + + + + diff --git a/android/KMAPro/kMAPro/src/main/res/layout/fragment_webview_layout.xml b/android/KMAPro/kMAPro/src/main/res/layout/fragment_webview_layout.xml new file mode 100644 index 0000000000000000000000000000000000000000..a7ff2a5a4a7bc14b557b71a0c06347316c2d6c27 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/res/layout/fragment_webview_layout.xml @@ -0,0 +1,16 @@ + + + + + + + + \ No newline at end of file diff --git a/android/KMAPro/kMAPro/src/main/res/layout/preference_add_icon_layout.xml b/android/KMAPro/kMAPro/src/main/res/layout/preference_add_icon_layout.xml new file mode 100644 index 0000000000000000000000000000000000000000..1a8b8af5ad4a7bc3e76afb32974bef85642456e1 --- /dev/null +++ b/android/KMAPro/kMAPro/src/main/res/layout/preference_add_icon_layout.xml @@ -0,0 +1,5 @@ + + diff --git a/android/KMAPro/kMAPro/src/main/res/layout/titlebar.xml b/android/KMAPro/kMAPro/src/main/res/layout/titlebar.xml index e76d908e9fd606aa2474ec96d258c4fc0cd7de0a..64b91a0fee77b4bba475079de1f595be460ca400 100644 --- a/android/KMAPro/kMAPro/src/main/res/layout/titlebar.xml +++ b/android/KMAPro/kMAPro/src/main/res/layout/titlebar.xml @@ -5,4 +5,18 @@ android:id="@+id/titlebar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" - android:layout_alignParentTop="true" /> + android:layout_alignParentTop="true" + app:popupTheme="@style/ThemeOverlay.AppCompat.Light"> + + + + diff --git a/android/KMAPro/kMAPro/src/main/res/menu/main.xml b/android/KMAPro/kMAPro/src/main/res/menu/main.xml index cc407ea789b9092955d7a4ff1be8b52feaeea7fb..a8c587ece67c1653d1f619a64ed4982e9c667e02 100644 --- a/android/KMAPro/kMAPro/src/main/res/menu/main.xml +++ b/android/KMAPro/kMAPro/src/main/res/menu/main.xml @@ -20,6 +20,47 @@ android:id="@+id/action_overflow" app:showAsAction="ifRoom" android:title="@string/action_overflow" - app:actionLayout="@layout/update_count_view" /> + android:icon="@drawable/ic_light_action_overflow" > + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/KMAPro/kMAPro/src/main/res/menu/overflow_menu.xml b/android/KMAPro/kMAPro/src/main/res/menu/overflow_menu.xml deleted file mode 100644 index e53eec98acb3abba5d6ca3fe64bedb8e3baaf009..0000000000000000000000000000000000000000 --- a/android/KMAPro/kMAPro/src/main/res/menu/overflow_menu.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/android/KMAPro/kMAPro/src/main/res/values/dimens.xml b/android/KMAPro/kMAPro/src/main/res/values/dimens.xml index b4c7fcd9708099fb50d75eb86e637e942a695c41..7523fc64609d88c531efbb4272d3c0b065a1685c 100644 --- a/android/KMAPro/kMAPro/src/main/res/values/dimens.xml +++ b/android/KMAPro/kMAPro/src/main/res/values/dimens.xml @@ -7,8 +7,9 @@ 16dp 16dp 200dp - 6sp - 250dp + 16sp + 24dp + 350dp 8dp 8dp 15dp diff --git a/android/KMAPro/kMAPro/src/main/res/values/strings.xml b/android/KMAPro/kMAPro/src/main/res/values/strings.xml index 407ef61072a1656d0569e2e37387e73bb6774b61..46b498507089f591c43645ca05e0dfde8a555914 100644 --- a/android/KMAPro/kMAPro/src/main/res/values/strings.xml +++ b/android/KMAPro/kMAPro/src/main/res/values/strings.xml @@ -3,73 +3,175 @@ Keyman - Share - Web Browser - Text Size - More - Clear Text - Info - Settings - Install Updates + + Share - Version + + Web Browser - - Start typing here… + + Text Size - - - Copyright © 1992- + + More - + + Clear Text + + + Info + + + Settings + + + Install Updates + + + + Version: %1$s + + + + Start typing here… + + + + + + Copyright © 1992- + + + + Text Size: %1$d + + Text size up + + Text size down - - All text will be cleared - + + \nAll text will be cleared\n - - Get Started - Add a keyboard for your language - Enable Keyman as system-wide keyboard - Set Keyman as default keyboard - More info - Show \"%1$s\" on startup + + Get Started - - Settings + + Add a keyboard for your language + + + Enable Keyman as system-wide keyboard + + + Set Keyman as default keyboard + + + More info + + + Show \"%1$s\" on startup + + + + Settings + + Installed languages Installed languages (%1$d) + + + Install Keyboard or Dictionary + + Always show banner + + To be implemented + + When off, only shown when predictive text is enabled - - - - Search or type URL - Bookmarks - No Bookmarks - Add Bookmark - Title - Url - - - Package - failed to install - Downloading keyboard package - Failed to extract - Install Keyboard Package - Install Predictive Text Package - No new touch-optimized keyboards to install - No new predictive text to install - No valid touch-optimized keyboards to install - No keyboards or predictive text to install - kmp.json does not exist - Invalid metadata in package + + + + Install from keyman.com + + + Install from local file + + + Install from other device + + + Add languages to installed keyboard + + + (from keyboard package) + + + + Select Keyboard Package + + + Select languages for %1$s + + + Added language %1$s to %2$s + + + All languages already installed + + + + Search or type URL + + + Bookmarks + + + No Bookmarks + + + Add Bookmark + + + Title + + + Url + + + Package %1$s failed to install + + + Downloading keyboard package\n%1$s… + + + Failed to extract + + + Install Keyboard + + + Welcome to %1$s + + + Install Dictionary + + + No new touch-optimized keyboards to install + + + No new predictive text to install + + + No keyboards or predictive text to install + + + Invalid/Missing metadata in package diff --git a/android/KMEA/app/build.gradle b/android/KMEA/app/build.gradle index cdd05fbc7da5320ab361eb6320a3fae3e408c08b..424cb25375ff5bacfb7a609110f61797c423da41 100644 --- a/android/KMEA/app/build.gradle +++ b/android/KMEA/app/build.gradle @@ -17,6 +17,7 @@ android { // VERSION_CODE and VERSION_NAME from version.gradle versionCode VERSION_CODE as Integer versionName VERSION_NAME + buildConfigField "String", "VERSION_ENVIRONMENT", "\""+VERSION_ENVIRONMENT+"\"" } buildTypes { @@ -61,7 +62,7 @@ android { } dependencies { - implementation 'androidx.appcompat:appcompat:1.2.0-alpha02' + implementation 'androidx.appcompat:appcompat:1.3.0-alpha02' implementation 'com.google.android.material:material:1.0.0' implementation 'commons-io:commons-io:2.6' implementation 'io.sentry:sentry-android:2.0.1' diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ConfirmDialogFragment.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ConfirmDialogFragment.java index 38bc4a036430c9f188d54f145b5a060a3e5791e9..17b8d3fee8f4b1d20ebf42838d4e2737960fb0df 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ConfirmDialogFragment.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ConfirmDialogFragment.java @@ -8,6 +8,7 @@ import android.os.Bundle; import android.widget.Toast; import com.tavultesoft.kmea.cloud.CloudApiTypes; +import com.tavultesoft.kmea.data.KeyboardController; import java.util.ArrayList; @@ -110,7 +111,7 @@ public class ConfirmDialogFragment extends DialogFragment { break; case DIALOG_TYPE_DELETE_KEYBOARD : // Confirmation to delete keyboard - int keyboardIndex = KeyboardPickerActivity.getKeyboardIndex(getActivity(), itemKey); + int keyboardIndex = KeyboardController.getInstance().getKeyboardIndex(itemKey); KeyboardPickerActivity.deleteKeyboard(getActivity(), keyboardIndex); dismissOnSelect = true; break; diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/JSONParser.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/JSONParser.java index db27ee7f905654944d48c39e9e706ef39bdbcbd7..aff24562df6ca06408165269e33e88abc7d25f68 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/JSONParser.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/JSONParser.java @@ -22,8 +22,7 @@ import org.json.JSONException; import org.json.JSONObject; import com.tavultesoft.kmea.util.Connection; - -import android.util.Log; +import com.tavultesoft.kmea.util.KMLog; public final class JSONParser { private final String TAG = "JSONParser"; @@ -49,23 +48,23 @@ public final class JSONParser { obj = (T) new JSONArray(jsonStr); } } catch (UnsupportedEncodingException e) { - Log.e(logTag, (e.getMessage() == null) ? "UnsupportedEncodingException" : e.getMessage()); + KMLog.LogException(logTag, "", e); obj = null; System.err.println(e); } catch (InterruptedIOException e) { // Disregard from cancelling action - Log.e(logTag, (e.getMessage() == null) ? "InterruptedIOException" : e.getMessage()); + KMLog.LogException(logTag, "", e); obj = null; } catch (IOException e) { - Log.e(logTag, (e.getMessage() == null) ? "IOException" : e.getMessage()); + KMLog.LogException(logTag, "", e); obj = null; System.err.println(e); } catch (JSONException e) { - Log.e(logTag, (e.getMessage() == null) ? "JSONException" : e.getMessage()); + KMLog.LogException(logTag, "", e); obj = null; System.err.println(e); } catch (Exception e) { - Log.e(logTag, (e.getMessage() == null) ? "Exception" : e.getMessage()); + KMLog.LogException(logTag, "", e); obj = null; System.err.println(e); } @@ -90,7 +89,7 @@ public final class JSONParser { jsonObj = getJSONObjectFromReader(reader, type); } catch (FileNotFoundException e) { String errorString = (e.getMessage() == null) ? "FileNotFoundException" : e.getMessage(); - Log.e(TAG, "JSONObjectFromFile error " + errorString); + KMLog.LogException(TAG, "JSONObjectFromFile error ", e); jsonObj = null; System.err.println(e); } finally { @@ -98,7 +97,7 @@ public final class JSONParser { try { reader.close(); } catch (IOException e) { - Log.e(TAG, "getJSONObjectFromFile error: " + e); + KMLog.LogException(TAG, "getJSONObjectFromFile error: ", e); // Ignore. } } @@ -145,11 +144,11 @@ public final class JSONParser { obj = (T) getJSONObjectFromReader(reader, type); } } catch (UnsupportedEncodingException e) { - Log.e(logTag, (e.getMessage() == null) ? "UnsupportedEncodingException" : e.getMessage()); + KMLog.LogException(logTag, "", e); obj = null; System.err.println(e); } catch (Exception e) { - Log.e(logTag, (e.getMessage() == null) ? "Exception" : e.getMessage()); + KMLog.LogException(logTag, "", e); obj = null; System.err.println(e); } finally { @@ -159,6 +158,7 @@ public final class JSONParser { try { reader.close(); } catch (IOException e) { + KMLog.LogException(logTag, "", e); // Ignore. } } @@ -179,6 +179,7 @@ public final class JSONParser { try { return getJSONObjectFromString(java.net.URLDecoder.decode(str, "UTF-8")); } catch (UnsupportedEncodingException e) { + KMLog.LogException(TAG, "", e); return null; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboard.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboard.java index a7a28ff2d2c1e4ca3716352c8d888cdf0518c7a3..cc46ea0437b2a6f0d417d372e2b8031c4e852c08 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboard.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboard.java @@ -7,15 +7,19 @@ 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.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 android.annotation.SuppressLint; import android.content.Context; @@ -54,6 +58,7 @@ import io.sentry.core.Sentry; import io.sentry.core.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; @@ -132,10 +137,10 @@ final class KMKeyboard extends WebView { setWebChromeClient(new WebChromeClient() { public boolean onConsoleMessage(ConsoleMessage cm) { + String msg = String.format("KMW JS Log: Line %d, %s:%s", cm.lineNumber(), cm.sourceId(), cm.message()); if (KMManager.isDebugMode()) { - Log.d("KMEA", "Keyman JS Log: Line " + cm.lineNumber() + ", " + cm.sourceId() + ":" + cm.message()); if (cm.messageLevel() == ConsoleMessage.MessageLevel.ERROR) { - Log.e("KMEA", "Keyman JS Log: ERROR"); + Log.d(TAG, msg); } } @@ -149,9 +154,14 @@ final class KMKeyboard extends WebView { Toast.makeText(context, "Fatal Error with " + currentKeyboard + ". Loading default keyboard", Toast.LENGTH_LONG).show(); - setKeyboard(KMManager.KMDefault_PackageID, KMManager.KMDefault_KeyboardID, - KMManager.KMDefault_LanguageID, KMManager.KMDefault_KeyboardName, - KMManager.KMDefault_LanguageName, KMManager.KMDefault_KeyboardFont, null); + Keyboard firstKeyboard = KeyboardController.getInstance().getKeyboardInfo(0); + if (firstKeyboard != null) { + // Revert to first keyboard in the list + setKeyboard(firstKeyboard); + } else { + // Fallback to sil_euro_latin (though 3rd party keyboards wont have it) + setKeyboard(KMManager.getDefaultKeyboard(context)); + } } return true; @@ -321,6 +331,7 @@ final class KMKeyboard extends WebView { if (subKeysWindow != null && subKeysWindow.isShowing()) subKeysWindow.dismiss(); } catch (Exception e) { + KMLog.LogException(TAG, "", e); } } @@ -330,6 +341,7 @@ final class KMKeyboard extends WebView { suggestionMenuWindow.dismiss(); } } catch (Exception e) { + KMLog.LogException(TAG, "", e); } } @@ -367,96 +379,42 @@ final class KMKeyboard extends WebView { 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()); + } + + return retVal; + } + public boolean setKeyboard(String packageID, String keyboardID, String languageID) { if (packageID == null || keyboardID == null || languageID == null) return false; boolean retVal = true; - String keyboardVersion = KMManager.getLatestKeyboardFileVersion(getContext(), packageID, keyboardID); - if (!KMManager.shouldAllowSetKeyboard() || keyboardVersion == null) { - Toast.makeText(context, "Can't set " + packageID + "::" + keyboardID + " for " + - languageID + " language. Loading default keyboard", Toast.LENGTH_LONG).show(); - packageID = KMManager.KMDefault_PackageID; - keyboardID = KMManager.KMDefault_KeyboardID; - languageID = KMManager.KMDefault_LanguageID; - retVal = false; - } - - String kbKey = String.format("%s_%s", languageID, keyboardID); - //if (kbKey.equals(currentKeyboard)) - // return false; - - String keyboardName = ""; - String languageName = ""; - keyboardVersion = KMManager.getLatestKeyboardFileVersion(getContext(), packageID, keyboardID); - - setKeyboardRoot(packageID); - String keyboardPath = makeKeyboardPath(packageID, keyboardID, keyboardVersion); - - String tFont = "''"; - String oFont = null; - HashMap> kbsInfo = LanguageListUtil.getKeyboardsInfo(context); - if (kbsInfo != null) { - HashMap kbInfo = kbsInfo.get(kbKey); - if (kbInfo != null) { - keyboardName = kbInfo.get(KMManager.KMKey_KeyboardName).replace("'", "\\'"); - languageName = kbInfo.get(KMManager.KMKey_LanguageName).replace("'", "\\'"); - txtFont = getFontFilename(kbInfo.get(KMManager.KMKey_Font)); - oskFont = getFontFilename(kbInfo.get(KMManager.KMKey_OskFont)); - - if (!txtFont.isEmpty()) { - tFont = makeFontPaths(kbInfo.get(KMManager.KMKey_Font)); - } - - if (!oskFont.isEmpty()) { - oFont = makeFontPaths(kbInfo.get(KMManager.KMKey_Font)); - } else { - oskFont = null; - } - - if (oFont == null) { - oFont = tFont; - } - } else { - return false; - } - } else { - return false; - } - if (tFont.equals("''")) { - tFont = fontUndefined; + int index = KeyboardController.getInstance().getKeyboardIndex(packageID, languageID, keyboardID); + Keyboard kbInfo = null; + if (index != KeyboardController.INDEX_NOT_FOUND) { + kbInfo = KeyboardController.getInstance().getKeyboardInfo(index); } - if (oFont.equals("''")) { - oFont = fontUndefined; - } - - // Escape single-quoted names for javascript call - keyboardName = keyboardName.replaceAll("\'", "\\\\'"); // Double-escaped-backslash b/c regex. - languageName = languageName.replaceAll("\'", "\\\\'"); - String jsFormat = "setKeymanLanguage('%s','%s','%s','%s','%s', %s, %s, '%s')"; - String jsString = String.format(jsFormat, keyboardName, keyboardID, languageName, languageID, keyboardPath, tFont, oFont, packageID); - 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); + if (!KMManager.shouldAllowSetKeyboard() || kbInfo == null) { + sendError(packageID, keyboardID, languageID); + kbInfo = KeyboardController.getInstance().getKeyboardInfo(0); + retVal = false; + } else { + retVal = setKeyboard(kbInfo); } - KeyboardEventHandler.notifyListeners(kbEventListeners, keyboardType, EventType.KEYBOARD_CHANGED, currentKeyboard); return retVal; } @@ -476,11 +434,11 @@ final class KMKeyboard extends WebView { boolean retVal = true; String keyboardVersion = KMManager.getLatestKeyboardFileVersion(getContext(), packageID, keyboardID); if (!KMManager.shouldAllowSetKeyboard() || keyboardVersion == null) { - Toast.makeText(context, "Can't set " + packageID + "::" + keyboardID + " for " + - languageID + " language. Loading default keyboard", Toast.LENGTH_LONG).show(); - packageID = KMManager.KMDefault_PackageID; - keyboardID = KMManager.KMDefault_KeyboardID; - languageID = KMManager.KMDefault_LanguageID; + sendError(packageID, keyboardID, languageID); + Keyboard kbInfo = KeyboardController.getInstance().getKeyboardInfo(0); + packageID = kbInfo.getPackageID(); + keyboardID = kbInfo.getKeyboardID(); + languageID = kbInfo.getLanguageID(); retVal = false; } String kbKey = String.format("%s_%s", languageID, keyboardID); @@ -510,15 +468,15 @@ final class KMKeyboard extends WebView { boolean retVal = true; String keyboardVersion = KMManager.getLatestKeyboardFileVersion(getContext(), packageID, keyboardID); if (!KMManager.shouldAllowSetKeyboard() || keyboardVersion == null) { - Toast.makeText(context, "Can't set " + packageID + "::" + keyboardID + " for " + - languageID + " language. Loading default keyboard", Toast.LENGTH_LONG).show(); - packageID = KMManager.KMDefault_PackageID; - keyboardID = KMManager.KMDefault_KeyboardID; - languageID = KMManager.KMDefault_LanguageID; - keyboardName = KMManager.KMDefault_KeyboardName; - languageName = KMManager.KMDefault_LanguageName; - kFont = KMManager.KMDefault_KeyboardFont; - kOskFont = kFont; + sendError(packageID, keyboardID, languageID); + 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; } @@ -614,6 +572,14 @@ final class KMKeyboard extends WebView { } + // Display Toast notification that keyboard selection failed, so loading default keyboard. + // Also sends a message to Sentry + private void sendError(String packageID, String keyboardID, String languageID) { + String msg = String.format("Can't set %s::%s for %s language. Loading default keyboard", packageID, keyboardID, languageID); + Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); + 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)) { @@ -708,6 +674,9 @@ final class KMKeyboard extends WebView { */ private String getFontFilename(String jsonString) { String font = ""; + if (jsonString == null || jsonString.isEmpty()) { + return font; + } try { JSONObject fontObj = new JSONObject(jsonString); JSONArray sourceArray = fontObj.optJSONArray(KMManager.KMKey_FontSource); @@ -730,6 +699,7 @@ final class KMKeyboard extends WebView { } } } catch (JSONException e) { + KMLog.LogException(TAG, "", e); font = ""; } @@ -1091,6 +1061,7 @@ final class KMKeyboard extends WebView { } } } catch (JSONException e) { + KMLog.LogException(TAG, "", e); return "''"; } @@ -1195,6 +1166,7 @@ final class KMKeyboard extends WebView { if (keyPreviewWindow != null && keyPreviewWindow.isShowing()) keyPreviewWindow.dismiss(); } catch (Exception e) { + KMLog.LogException(TAG, "", e); } } }, delay); @@ -1212,7 +1184,7 @@ final class KMKeyboard extends WebView { if (KMManager.getGlobeKeyAction(keyboardType) == KMManager.GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD) { // Help bubble is disabled if next keyboard is not available for this action - ArrayList> keyboardsList = KMManager.getKeyboardsList(context); + List keyboardsList = KMManager.getKeyboardsList(context); if (keyboardsList == null) { return; } @@ -1307,6 +1279,7 @@ final class KMKeyboard extends WebView { return false; } } catch (Exception e) { + KMLog.LogException(TAG, "", e); return true; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboardDownloaderActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboardDownloaderActivity.java index b8033dc3c253e296741482da0ccb9da181246dc4..d27c559969413874f194e8a902028acbbafccd42 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboardDownloaderActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboardDownloaderActivity.java @@ -10,11 +10,15 @@ import androidx.appcompat.app.AppCompatActivity; import com.tavultesoft.kmea.cloud.CloudApiTypes; import com.tavultesoft.kmea.cloud.CloudDataJsonUtil; import com.tavultesoft.kmea.cloud.CloudDownloadMgr; +import com.tavultesoft.kmea.cloud.impl.CloudKeyboardPackageDownloadCallback; +import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.KeyboardController; import com.tavultesoft.kmea.cloud.impl.CloudKeyboardDataDownloadCallback; import com.tavultesoft.kmea.cloud.impl.CloudKeyboardMetaDataDownloadCallback; import com.tavultesoft.kmea.cloud.impl.CloudLexicalPackageDownloadCallback; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import static com.tavultesoft.kmea.ConfirmDialogFragment.DialogType.DIALOG_TYPE_DOWNLOAD_KEYBOARD; @@ -29,32 +33,24 @@ public class KMKeyboardDownloaderActivity extends AppCompatActivity { public static final String ARG_LANG_ID = "KMKeyboardActivity.langID"; public static final String ARG_KB_NAME = "KMKeyboardActivity.kbName"; public static final String ARG_LANG_NAME = "KMKeyboardActivity.langName"; - public static final String ARG_IS_CUSTOM = "KMKeyboardActivity.isCustom"; public static final String ARG_MODEL_ID = "KMKeyboardActivity.modelID"; public static final String ARG_MODEL_NAME = "KMKeyboardActivity.modelName"; - public static final String ARG_MODEL_URL = "KMKeyboardActivity.modelURL"; public static final String ARG_CUSTOM_HELP_LINK = "KMKeyboardActivity.customHelpLink"; - - // custom keyboard - public static final String ARG_KEYBOARD = "KMKeyboardActivity.keyboard"; - public static final String ARG_LANGUAGE = "KMKeyboardActivity.language"; - public static final String ARG_URL = "KMKeyboardActivity.url"; - public static final String ARG_FILENAME = "KMKeyboardActivity.filename"; - - public static final String kKeymanApiBaseURL = "https://api.keyman.com/cloud/4.0/languages"; - public static final String kKeymanApiModelURL = "https://api.keyman.com/model"; + public static final String ARG_KMP_LINK = "KMKeyboardActivity.kmpLink"; private static final String TAG = "KMKbdDownloaderActivity"; // TAG needs to be less than 28 chars // Keyman public keys - public static final String KMKey_URL = "url"; + public static final String KMKey_BCP47 = "bcp47"; + public static final String KMKey_Filename = "filename"; public static final String KMKey_Keyboard = "keyboard"; public static final String KMKey_LanguageKeyboards = "keyboards"; - public static final String KMKey_BCP47 = "bcp47"; - public static final String KMKey_Options = "options"; public static final String KMKey_Language = "language"; public static final String KMKey_Languages = "languages"; - public static final String KMKey_Filename = "filename"; + public static final String KMKey_Options = "options"; + public static final String KMKey_Platform = "platform"; + public static final String KMKey_Tier = "tier"; + public static final String KMKey_URL = "url"; // Keyman internal keys public static final String KMKey_KeyboardBaseURI = "keyboardBaseUri"; @@ -68,7 +64,6 @@ public class KMKeyboardDownloaderActivity extends AppCompatActivity { private String modelName; private String kbName; private String langName; - private Boolean isCustom; private Boolean downloadOnlyLexicalModel; private String customKeyboard; @@ -95,49 +90,16 @@ public class KMKeyboardDownloaderActivity extends AppCompatActivity { langID = bundle.getString(ARG_LANG_ID); langName = bundle.getString(ARG_LANG_NAME); - downloadOnlyLexicalModel = bundle.containsKey(ARG_MODEL_URL) && - bundle.getString(ARG_MODEL_URL) != null && - !bundle.getString(ARG_MODEL_URL).isEmpty(); - - if (downloadOnlyLexicalModel) { - modelID = bundle.getString(ARG_MODEL_ID); - modelName = bundle.getString(ARG_MODEL_NAME); - isCustom = false; - url = bundle.getString(ARG_MODEL_URL); - } else { - - kbID = bundle.getString(ARG_KB_ID); - kbName = bundle.getString(ARG_KB_NAME); - isCustom = bundle.getBoolean(ARG_IS_CUSTOM); - - // URL parameters for custom keyboard (if they exist) - customKeyboard = bundle.getString(ARG_KEYBOARD); - customLanguage = bundle.getString(ARG_LANGUAGE); - url = bundle.getString(ARG_URL); - filename = bundle.getString(ARG_FILENAME); - if (filename == null || filename.isEmpty()) { - filename = "unknown"; - } - } - - String title; - if (url != null) { - title = String.format("%s: %s", getString(R.string.custom_keyboard), filename); - } else if (customKeyboard != null && customLanguage != null && - !customKeyboard.trim().isEmpty() && !customLanguage.trim().isEmpty()) { - int kbIndex = KMManager.getKeyboardIndex(getApplicationContext(), customKeyboard, customLanguage); + modelID = bundle.getString(ARG_MODEL_ID); + modelName = bundle.getString(ARG_MODEL_NAME); + kbID = bundle.getString(ARG_KB_ID); + kbName = bundle.getString(ARG_KB_NAME); + url = bundle.getString(ARG_KMP_LINK); - if (kbIndex >= 0) { - KMManager.setKeyboard(getApplicationContext(), kbIndex); - // No interaction needed - return; // false - } + downloadOnlyLexicalModel = (modelID != null && !modelID.isEmpty()); - title = String.format("%s_%s", customLanguage, customKeyboard); - } else { - // Download keyboard from cloud server - title = String.format("%s: %s", langName, kbName); - } + // Download keyboard from cloud server + String title = String.format("%s: %s", langName, kbName); DialogFragment dialog; if (downloadOnlyLexicalModel) { @@ -156,6 +118,13 @@ public class KMKeyboardDownloaderActivity extends AppCompatActivity { dialog.show(getFragmentManager(), "dialog"); } + private ArrayList prepareCloudApiParamsForKeyboardPackageDownload() { + ArrayList _params = new ArrayList<>(); + _params.add(new CloudApiTypes.CloudApiParam( + CloudApiTypes.ApiTarget.KeyboardPackage, url)); + return _params; + } + /** * prepare cloud api params for lexical models download. * @return the result @@ -175,14 +144,14 @@ public class KMKeyboardDownloaderActivity extends AppCompatActivity { * @param aPreparedCloudApiParams the prepared api params */ public static void downloadKeyboard(Context context, - String aLangId, String aKbId, - List aPreparedCloudApiParams) + String aLangId, String aKbId, + List aPreparedCloudApiParams) { - String _downloadid= CloudKeyboardMetaDataDownloadCallback.createDownloadId(aLangId , aKbId); + String _downloadid= CloudKeyboardPackageDownloadCallback.createDownloadId(aLangId , aKbId); if( CloudDownloadMgr.getInstance().alreadyDownloadingData(_downloadid) || CloudDownloadMgr.getInstance().alreadyDownloadingData( - CloudKeyboardDataDownloadCallback.createDownloadId(aKbId))) + CloudKeyboardPackageDownloadCallback.createDownloadId(aLangId, aKbId))) { Toast.makeText(context, context.getString(R.string.keyboard_download_is_running_in_background), @@ -190,7 +159,8 @@ public class KMKeyboardDownloaderActivity extends AppCompatActivity { } else { - CloudKeyboardMetaDataDownloadCallback _callback = new CloudKeyboardMetaDataDownloadCallback(); + CloudKeyboardPackageDownloadCallback _callback = new CloudKeyboardPackageDownloadCallback(); + _callback.setLanguageID(aLangId); Toast.makeText(context, context.getString(R.string.keyboard_download_start_in_background), @@ -211,39 +181,16 @@ public class KMKeyboardDownloaderActivity extends AppCompatActivity { private ArrayList prepareCloudApiParamsForKeyboardDownload() { if (pkgID == null || pkgID.trim().isEmpty() || - (!isCustom && (langID == null || langID.trim().isEmpty() || kbID == null || kbID.trim().isEmpty()))) { + langID == null || langID.trim().isEmpty() || + kbID == null || kbID.trim().isEmpty()) { throw new IllegalStateException("Invalid keyboard"); } ArrayList cloudQueries = new ArrayList<>(); + cloudQueries.add( + new CloudApiTypes.CloudApiParam( + CloudApiTypes.ApiTarget.KeyboardPackage, url)); - String deviceType = CloudDataJsonUtil.getDeviceTypeForCloudQuery(this); - - if (isCustom) { - //TODO: will end up in an exception during download??? - cloudQueries.add(new CloudApiTypes.CloudApiParam( - CloudApiTypes.ApiTarget.KeyboardData, url)); - } - else - { - // Keyman cloud - // Sanitize appVersion to #.#.# to match the API spec - String appVersion = KMManager.getVersion(); - String _remoteUrl = String.format("%s/%s/%s?version=%s&device=%s&languageidtype=bcp47", - kKeymanApiBaseURL, langID, kbID, appVersion, deviceType); - cloudQueries.add( - new CloudApiTypes.CloudApiParam( - CloudApiTypes.ApiTarget.Keyboard, _remoteUrl) - .setType(CloudApiTypes.JSONType.Object) - .setAdditionalProperty(CloudKeyboardMetaDataDownloadCallback.PARAM_IS_CUSTOM,isCustom) - .setAdditionalProperty(CloudKeyboardMetaDataDownloadCallback.PARAM_LANG_ID,langID) - .setAdditionalProperty(CloudKeyboardMetaDataDownloadCallback.PARAM_KB_ID,kbID)); - - String _remoteLexicalModelUrl = String.format("%s?q=bcp47:%s", kKeymanApiModelURL, langID); - cloudQueries.add(new CloudApiTypes.CloudApiParam( - CloudApiTypes.ApiTarget.KeyboardLexicalModels, _remoteLexicalModelUrl) - .setType(CloudApiTypes.JSONType.Array)); - } return cloudQueries; } @@ -254,8 +201,8 @@ public class KMKeyboardDownloaderActivity extends AppCompatActivity { * @param aPreparedCloudApiParams the prepared api params */ public static void downloadLexicalModel(Context context, - String aModelId, - List aPreparedCloudApiParams) { + String aModelId, + List aPreparedCloudApiParams) { String _downloadid= CloudLexicalPackageDownloadCallback.createDownloadId(aModelId); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboardPickerAdapter.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboardPickerAdapter.java index 39906677e944ee6e71ee83ae533ebdfd3df23814..ac8b5297a91aac356588fc9fd6c06f45bab2e1ed 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboardPickerAdapter.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMKeyboardPickerAdapter.java @@ -21,6 +21,7 @@ import android.widget.TextView; import com.tavultesoft.kmea.data.Dataset; import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.KeyboardController; import com.tavultesoft.kmea.data.adapters.AdapterFilter; import com.tavultesoft.kmea.data.adapters.NestedAdapter; import com.tavultesoft.kmea.util.FileUtils; @@ -43,35 +44,9 @@ final class KMKeyboardPickerAdapter extends NestedAdapter() { - // Yeah, so this is a MASSIVE hack. Right now, it's either this or refactor up to 60 - // separate references to keyboardList within KeyboardPickerActivity. Yikes. public List selectFrom(Dataset.Keyboards adapter, Void dummy) { - List> kbdMapList = KeyboardPickerActivity.getKeyboardsList(context); - List kbdList = new ArrayList<>(kbdMapList.size()); - - for(HashMap kbdMap: kbdMapList) { - boolean isCustom = kbdMap.containsKey(KMManager.KMKey_CustomKeyboard) && - kbdMap.get(KMManager.KMKey_CustomKeyboard).equals("Y"); - boolean isNewKeyboard = kbdMap.containsKey(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD) && - kbdMap.get(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD).equals(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD); - - Keyboard k = new Keyboard( - kbdMap.get(KMManager.KMKey_PackageID), - kbdMap.get(KMManager.KMKey_KeyboardID), - kbdMap.get(KMManager.KMKey_KeyboardName), - kbdMap.get(KMManager.KMKey_LanguageID), - kbdMap.get(KMManager.KMKey_LanguageName), - isCustom, - isNewKeyboard, - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_Font, null), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_OskFont, null), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_Version, "1.0"), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_CustomHelpLink, "") - ); - kbdList.add(k); - } - - return kbdList; + // Return the keyboards list + return adapter.asList(); } }, null); } @@ -94,9 +69,9 @@ final class KMKeyboardPickerAdapter extends NestedAdapter= 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 VERSION_NAME + * @return String + */ + public static String getMajorVersion() { + // Regex needs to match the entire string + String appVersion = com.tavultesoft.kmea.BuildConfig.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 app version #.#.# from VERSION_NAME + * Extract KMEA version #.#.# from VERSION_NAME * @return String */ public static String getVersion() { @@ -267,7 +338,7 @@ public final class KMManager { copyAssets(appContext); migrateOldKeyboardFiles(appContext); - updateOldKeyboardsList(appContext); + // UpdateOldKeyboardsList() handled with KeyboardController later didCopyAssets = true; } @@ -276,11 +347,15 @@ public final class KMManager { } else if (keyboardType == KeyboardType.KEYBOARD_TYPE_SYSTEM) { initSystemKeyboard(appContext); } else { - Log.e(TAG, "Cannot initialize: Invalid keyboard type"); + 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); } @@ -527,32 +602,54 @@ public final class KMManager { } } - // Copy and install all KMP files (Issue for FV app?) 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 installAsset = FileUtils.hasKeymanPackageExtension(assetFile) || + boolean isPackageFile = FileUtils.hasKeymanPackageExtension(assetFile) || FileUtils.hasLexicalModelPackageExtension(assetFile); - if (installAsset) { + // Copy asset KMP files + if (isPackageFile) { copyAsset(context, assetFile, "", true); kmpFile = new File(getResourceRoot(), assetFile); tempPackagePath = kmpProcessor.unzipKMP(kmpFile); - if (FileUtils.hasLexicalModelPackageExtension(assetFile)) { - lmkmpProcessor.processKMP(kmpFile, tempPackagePath, PackageProcessor.PP_LEXICAL_MODELS_KEY); - } else { - // 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); + // 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) { - Log.e(TAG, "Failed to copy assets. Error: " + e); + KMLog.LogException(TAG, "Failed to copy assets. Error: ", e); } } @@ -584,7 +681,7 @@ public final class KMManager { result = 0; } } catch (Exception e) { - Log.e(TAG, "Failed to copy asset. Error: " + e); + KMLog.LogException(TAG, "Failed to copy asset. Error: ", e); result = -1; } return result; @@ -680,125 +777,163 @@ public final class KMManager { FileUtils.deleteDirectory(legacyFontsDir); } - // TODO: Investigate how to migrate cloud/ keyboards to packages/ ? - // Would need to query what associated files get moved + // cloud/ keyboards migrated to packages/ in migrateCloudKeyboards() // For now, can delete sil_euro_latin because it will be in packages/ - File[] files = migratedDir.listFiles(keyboardFilter); - for (File file: files) { - String filename = file.getName(); - if (filename.startsWith(KMDefault_KeyboardID)) { - file.delete(); - } - } + removeCloudKeyboard(KMDefault_KeyboardID); } catch (IOException e) { - Log.e(TAG, "Failed to migrate assets. Error: " + e); - } - } - - public static void updateOldKeyboardsList(Context context) { - ArrayList> kbList = KeyboardPickerActivity.getKeyboardsList(context); - if (kbList != null && kbList.size() > 0) { - boolean shouldUpdateList = false; - boolean shouldClearCache = false; - HashMap kbInfo = kbList.get(0); - String pkgID = kbInfo.get(KMKey_PackageID); - String kbID = kbInfo.get(KMKey_KeyboardID); - if ( kbID.equals("us") || kbID.equals("european2") || - (pkgID.equals(KMDefault_UndefinedPackageID) && kbID.equals(KMDefault_KeyboardID)) ) { - HashMap newKbInfo = new HashMap(); - newKbInfo.put(KMManager.KMKey_PackageID, KMManager.KMDefault_PackageID); - newKbInfo.put(KMManager.KMKey_KeyboardID, KMManager.KMDefault_KeyboardID); - newKbInfo.put(KMManager.KMKey_LanguageID, KMManager.KMDefault_LanguageID); - newKbInfo.put(KMManager.KMKey_KeyboardName, KMManager.KMDefault_KeyboardName); - newKbInfo.put(KMManager.KMKey_LanguageName, KMManager.KMDefault_LanguageName); - newKbInfo.put(KMManager.KMKey_KeyboardVersion, - getLatestKeyboardFileVersion(context, KMManager.KMDefault_PackageID, - KMManager.KMDefault_KeyboardID)); - newKbInfo.put(KMManager.KMKey_CustomKeyboard, "N"); - newKbInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont); - kbList.set(0, newKbInfo); - shouldUpdateList = true; - shouldClearCache = true; - } + KMLog.LogException(TAG, "Failed to migrate assets. Error: ", e); + } + } - int index2Remove = -1; - int kblCount = kbList.size(); - for (int i = 0; i < kblCount; i++) { - kbInfo = kbList.get(i); - - kbID = kbInfo.get(KMKey_KeyboardID); - pkgID = kbInfo.get(KMKey_PackageID); - if (pkgID == null || pkgID.isEmpty()) { - pkgID = KMDefault_UndefinedPackageID; - kbInfo.put(KMManager.KMKey_PackageID, pkgID); - shouldUpdateList = true; + /** + * Migrate keyboards list from the legacy dat file (HashMap) and returns a list of keyboards. + * 1. These deprecated keyboards: "us", "european", "european2" are also removed + * and replaced with "sil_euro_latin". + * 2. Undefined package ID set to "cloud" + * 3. Undefined version set to the latest file version + * 4. Check sil_euro_latin only added once + * Using the old keyboards list as parameter instead of keyboards file so this can be + * unit test. + * @param context Context + * @param dat_list ArrayList> Old keyboards list + * @return List Migrated keyboards list + */ + public static List updateOldKeyboardsList(Context context, ArrayList> dat_list) { + List list = new ArrayList(); + if (dat_list == null) { + return list; + } + + boolean defaultKeyboardInstalled = false; + for(HashMap kbdMap : dat_list) { + final boolean isNewKeyboard = false; + String packageID = MapCompat.getOrDefault(kbdMap, KMManager.KMKey_PackageID, KMManager.KMDefault_UndefinedPackageID); + String keyboardID = kbdMap.get(KMManager.KMKey_KeyboardID); + if (keyboardID == null) { + KMLog.LogError(TAG, "updateOldKeyboardsList: skipping keyboard with undefined keyboard ID"); + continue; + } + String kbVersion = kbdMap.get(KMManager.KMKey_Version); + if (kbVersion == null) { + String latestKbVersion = getLatestKeyboardFileVersion(context, packageID, keyboardID); + if (latestKbVersion != null) { + kbVersion = latestKbVersion; } - String langID = kbInfo.get(KMKey_LanguageID); - String kbVersion = kbInfo.get(KMManager.KMKey_KeyboardVersion); - String latestKbVersion = getLatestKeyboardFileVersion(context, pkgID, kbID); - if ((latestKbVersion != null) && (kbVersion == null || !kbVersion.equals(latestKbVersion))) { - kbInfo.put(KMManager.KMKey_KeyboardVersion, latestKbVersion); - kbList.set(i, kbInfo); - shouldUpdateList = true; + } + Keyboard k = new Keyboard( + packageID, + keyboardID, + kbdMap.get(KMManager.KMKey_KeyboardName), + kbdMap.get(KMManager.KMKey_LanguageID), + kbdMap.get(KMManager.KMKey_LanguageName), + kbVersion, + MapCompat.getOrDefault(kbdMap, KMManager.KMKey_CustomHelpLink, ""), + MapCompat.getOrDefault(kbdMap, KMManager.KMKey_KMPLink, ""), + isNewKeyboard, + MapCompat.getOrDefault(kbdMap, KMManager.KMKey_Font, null), + MapCompat.getOrDefault(kbdMap, KMManager.KMKey_OskFont, null) + ); + + // Check that sil_euro_latin and its deprecated keyboards only get added once + if (keyboardID.equals("us") || keyboardID.equals("european") || keyboardID.equals("european2") || + keyboardID.equals("sil_euro_latin")) { + if (!defaultKeyboardInstalled) { + list.add(KMManager.getDefaultKeyboard(context)); + defaultKeyboardInstalled = true; } + } else { + // Otherwise add the keyboard + list.add(k); + } + } - String isCustom = kbInfo.get(KMManager.KMKey_CustomKeyboard); - if (isCustom == null || isCustom.equals("U")) { - String kbKey = String.format("%s_%s", langID, kbID); - kbInfo.put(KMManager.KMKey_CustomKeyboard, isCustomKeyboard(context, kbKey)); - kbList.set(i, kbInfo); - shouldUpdateList = true; - } + return list; + } - if (kbID.equals(KMManager.KMDefault_KeyboardID) && langID.equals(KMManager.KMDefault_LanguageID)) { - int defKbIndex = KMManager.getKeyboardIndex(context, KMManager.KMDefault_KeyboardID, KMManager.KMDefault_LanguageID); - if (defKbIndex == 0 && i > 0) - index2Remove = i; + /** + * Loop through the installed keyboards list: + * If the keyboard exists in cloud/ and packages/, migrate keyboard entry to packages/ + * Then remove the keyboard files in cloud/ + * @param context + */ + public static void migrateCloudKeyboards(Context context) { + boolean keyboardMigrated = false; + for(int i=0; i 0) { - kbList.remove(index2Remove); - SharedPreferences prefs = appContext.getSharedPreferences(appContext.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE); - SharedPreferences.Editor editor = prefs.edit(); - int index = prefs.getInt(KMManager.KMKey_UserKeyboardIndex, 0); - if (index == index2Remove) { - index = 0; - } else if (index > index2Remove) { - index--; + // See if there's a matching keyboard of (package ID, keyboardID, ignoring language ID) + int keyboardIndex = KeyboardController.getInstance().getKeyboardIndex( + packageID, keyboardID, ""); + if (keyboardIndex != KeyboardController.INDEX_NOT_FOUND) { + Keyboard keyboardFromPackage = KeyboardController.getInstance().getKeyboardInfo(keyboardIndex); + // Create a copy of keyboardFromPackage, updating the language ID and language Name + Keyboard migratedKeyboard = new Keyboard(keyboardFromPackage); + migratedKeyboard.setLanguage(languageID, languageName); + KeyboardController.getInstance().set(i, migratedKeyboard); + + // Remove the cloud keyboard files + removeCloudKeyboard(keyboardID); + keyboardMigrated = true; } - editor.putInt(KMManager.KMKey_UserKeyboardIndex, index); - editor.commit(); - shouldUpdateList = true; - } - - if (shouldUpdateList) { - KeyboardPickerActivity.updateKeyboardsList(context, kbList); } + } - if (shouldClearCache) { - File cache = CloudDataJsonUtil.getKeyboardCacheFile(appContext); - if (cache.exists()) { - cache.delete(); - } - } + if (keyboardMigrated) { + KeyboardController.getInstance().save(context); } } - private static String isCustomKeyboard(Context context, String keyboardKey) { - String isCustom = "U"; - HashMap> keyboardsInfo = LanguageListUtil.getKeyboardsInfo(context); - if (keyboardsInfo != null) { - HashMap kbInfo = keyboardsInfo.get(keyboardKey); - if (kbInfo != null) { - isCustom = "N"; - } else { - isCustom = "Y"; + /** + * Remove all the keyboard files in the "cloud" directory matching a pattern + * [keyboard ID]-[version].js + * + * @param keyboardID String of the keyboard ID + */ + public static void removeCloudKeyboard(final String keyboardID) { + String path = getCloudDir(); + File dir = new File(path); + + FileFilter keyboardFilter = new FileFilter() { + @Override + /** + * Filter for JS keyboards that match [keyboardID]-[version].js + */ + public boolean accept(File pathname) { + String name = pathname.getName(); + + String patternStr = String.format("^([A-Za-z0-9-_]+)-([0-9.]+)(\\.js)$"); + Pattern pattern = Pattern.compile(patternStr); + Matcher matcher = pattern.matcher(name); + if (matcher.matches() && (matcher.groupCount() == 3) && + (matcher.group(1).equals(keyboardID)) && (matcher.group(2) != null)) { + return true; + } + return false; } + }; + + File[] files = dir.listFiles(keyboardFilter); + if (files.length == 0) { + return; } - return isCustom; + for (File file : files) { + file.delete(); + } } /** @@ -838,12 +973,12 @@ public final class KMManager { } } } catch (Exception e) { - Log.e(TAG, "Failed to create Typeface: " + fontFilename); + KMLog.LogException(TAG, "Failed to create Typeface: " + fontFilename, e); } return font; } - public static ArrayList> getKeyboardsList(Context context) { + public static List getKeyboardsList(Context context) { return KeyboardPickerActivity.getKeyboardsList(context); } @@ -870,7 +1005,7 @@ public final class KMManager { modelObj.put("path", path); modelObj.put("CustomHelpLink", lexicalModelInfo.get(KMKey_CustomHelpLink)); } catch (JSONException e) { - Log.e(TAG, "Invalid lexical model to register"); + KMLog.LogException(TAG, "Invalid lexical model to register", e); return false; } @@ -962,7 +1097,7 @@ public final class KMManager { int length = lexicalModelsList.size(); for (int i = 0; i < length; i++) { HashMap lmInfo = lexicalModelsList.get(i); - if (langId.equalsIgnoreCase(lmInfo.get(KMManager.KMKey_LanguageID))) { + if (BCP47.languageEquals(langId, lmInfo.get(KMManager.KMKey_LanguageID))) { return lmInfo; } } @@ -971,9 +1106,10 @@ public final class KMManager { return null; } - public static boolean addKeyboard(Context context, HashMap keyboardInfo) { - String packageID = keyboardInfo.get(KMManager.KMKey_PackageID); - String keyboardID = keyboardInfo.get(KMManager.KMKey_KeyboardID); + public static boolean addKeyboard(Context context, Keyboard keyboardInfo) { + String packageID = keyboardInfo.getPackageID(); + String keyboardID = keyboardInfo.getKeyboardID(); + keyboardInfo.setNewKeyboard(true); // Log Sentry analytic event, ignoring default keyboard if (Sentry.isEnabled() && !(packageID.equalsIgnoreCase(KMManager.KMDefault_PackageID) && @@ -982,12 +1118,12 @@ public final class KMManager { breadcrumb.setMessage("KMManager.addKeyboard"); breadcrumb.setCategory("addKeyboard"); breadcrumb.setLevel(SentryLevel.INFO); - breadcrumb.setData("packageID", keyboardInfo.get(KMManager.KMKey_PackageID)); - breadcrumb.setData("keyboardID", keyboardInfo.get(KMManager.KMKey_KeyboardID)); - breadcrumb.setData("keyboardName", keyboardInfo.get(KMManager.KMKey_KeyboardName)); - breadcrumb.setData("keyboardVersion", keyboardInfo.get(KMManager.KMKey_KeyboardVersion)); - breadcrumb.setData("languageID", keyboardInfo.get(KMManager.KMKey_LanguageID)); - breadcrumb.setData("languageName", keyboardInfo.get(KMManager.KMKey_LanguageName)); + breadcrumb.setData("packageID", packageID); + breadcrumb.setData("keyboardID", keyboardID); + breadcrumb.setData("keyboardName", keyboardInfo.getKeyboardName()); + breadcrumb.setData("keyboardVersion", keyboardInfo.getVersion()); + breadcrumb.setData("languageID", keyboardInfo.getLanguageID()); + breadcrumb.setData("languageName", keyboardInfo.getLanguageName()); Sentry.addBreadcrumb(breadcrumb); @@ -998,10 +1134,49 @@ public final class KMManager { return KeyboardPickerActivity.addKeyboard(context, keyboardInfo); } + // Intend to deprecate in Keyman 15.0 + public static boolean addKeyboard(Context context, HashMap keyboardInfo) { + String packageID = keyboardInfo.get(KMManager.KMKey_PackageID); + String keyboardID = keyboardInfo.get(KMManager.KMKey_KeyboardID); + String keyboardName = keyboardInfo.get(KMManager.KMKey_KeyboardName); + String languageID = keyboardInfo.get(KMManager.KMKey_LanguageID); + String languageName = keyboardInfo.get(KMManager.KMKey_LanguageName); + String version = keyboardInfo.get(KMManager.KMKey_KeyboardVersion); + String helpLink = keyboardInfo.get(KMManager.KMKey_CustomHelpLink); + String kmpLink = MapCompat.getOrDefault(keyboardInfo, KMManager.KMKey_KMPLink, ""); + String font = keyboardInfo.get(KMManager.KMKey_Font); + String oskFont = keyboardInfo.get(KMManager.KMKey_OskFont); + boolean isNewKeyboard = true; + + Keyboard k = new Keyboard(packageID, keyboardID, keyboardName, + languageID, languageName, version, helpLink, kmpLink, + isNewKeyboard, font, oskFont); + return addKeyboard(context, k); + } + public static boolean removeKeyboard(Context context, int position) { return KeyboardPickerActivity.removeKeyboard(context, position); } + /** + * Some apps have the user select which keyboard to add. To ensure there's always a fallback + * system keyboard when the keyboard list is empty, use this method. + * If setDefaultKeyboard() is never used, this will return default sil_euro_latin. + * @param context Context + * @return Keyboard Default fallback keyboard + */ + public static Keyboard getDefaultKeyboard(Context context) { + return Keyboard.getDefaultKeyboard(context); + } + + /** + * Set a default fallback keyboard. If null, getDefaultKeyboard() will return sil_euro_latin. + * @param k Keyboard info for the fallback keyboard. + */ + public static void setDefaultKeyboard(Keyboard k) { + Keyboard.setDefaultKeyboard(k); + } + public static boolean setKeyboard(String packageID, String keyboardID, String languageID) { boolean result1 = false; boolean result2 = false; @@ -1015,6 +1190,24 @@ public final class KMManager { return (result1 || result2); } + public static boolean setKeyboard(Keyboard keyboardInfo) { + boolean result1 = false; + boolean result2 = false; + + if (InAppKeyboard != null && InAppKeyboardLoaded && keyboardInfo != null) { + result1 = InAppKeyboard.setKeyboard(keyboardInfo); + } + + if (SystemKeyboard != null && SystemKeyboardLoaded && keyboardInfo != null) + result2 = SystemKeyboard.setKeyboard(keyboardInfo); + + if (keyboardInfo != null) { + registerAssociatedLexicalModel(keyboardInfo.getLanguageID()); + } + + return (result1 || result2); + } + /** * Prepare keyboard switch for inapp keyboard and systemkeyboard * @param packageID the package id @@ -1072,42 +1265,28 @@ public final class KMManager { } public static boolean setKeyboard(Context context, int position) { - HashMap keyboardInfo = getKeyboardInfo(context, position); + Keyboard keyboardInfo = getKeyboardInfo(context, position); if (keyboardInfo == null) return false; - String pkgId = keyboardInfo.get(KMManager.KMKey_PackageID); - String kbId = keyboardInfo.get(KMManager.KMKey_KeyboardID); - String langId = keyboardInfo.get(KMManager.KMKey_LanguageID); - String kbName = keyboardInfo.get(KMManager.KMKey_KeyboardName); - String langName = keyboardInfo.get(KMManager.KMKey_LanguageName); - String kFont = keyboardInfo.get(KMManager.KMKey_Font); - String kOskFont = keyboardInfo.get(KMManager.KMKey_OskFont); - return setKeyboard(pkgId, kbId, langId, kbName, langName, kFont, kOskFont); + return setKeyboard(keyboardInfo); } public static void switchToNextKeyboard(Context context) { - int index = KeyboardPickerActivity.getCurrentKeyboardIndex(context); + int index = KeyboardController.getInstance().getKeyboardIndex(KMKeyboard.currentKeyboard()); index++; - HashMap kbInfo = KeyboardPickerActivity.getKeyboardInfo(context, index); + Keyboard kbInfo = KeyboardController.getInstance().getKeyboardInfo(index); if (kbInfo == null) { index = 0; - kbInfo = KeyboardPickerActivity.getKeyboardInfo(context, index); + kbInfo = KeyboardController.getInstance().getKeyboardInfo(index); } - String pkgId = kbInfo.get(KMManager.KMKey_PackageID); - String kbId = kbInfo.get(KMManager.KMKey_KeyboardID); - String langId = kbInfo.get(KMManager.KMKey_LanguageID); - String kbName = kbInfo.get(KMManager.KMKey_KeyboardName); - String langName = kbInfo.get(KMManager.KMKey_LanguageName); - String kFont = kbInfo.get(KMManager.KMKey_Font); - String kOskFont = kbInfo.get(KMManager.KMKey_OskFont); if (InAppKeyboard != null) { - InAppKeyboard.setKeyboard(pkgId, kbId, langId, kbName, langName, kFont, kOskFont); + InAppKeyboard.setKeyboard(kbInfo); } if (SystemKeyboard != null) { - SystemKeyboard.setKeyboard(pkgId, kbId, langId, kbName, langName, kFont, kOskFont); + SystemKeyboard.setKeyboard(kbInfo); } } @@ -1127,11 +1306,14 @@ public final class KMManager { } public static void advanceToNextInputMode() { - InputMethodManager imm = (InputMethodManager) appContext.getSystemService(Context.INPUT_METHOD_SERVICE); - - // TODO: this method is added in API level 16 and deprecated in API level 28 - // Reference: https://developer.android.com/reference/android/view/inputmethod/InputMethodManager.html#switchToNextInputMethod(android.os.IBinder,%20boolean) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + if (IMService != null) { + IMService.switchToNextInputMethod(false); + } + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + // This method is added in API level 16 and deprecated in API level 28 + // Reference: https://developer.android.com/reference/android/view/inputmethod/InputMethodManager.html#switchToNextInputMethod(android.os.IBinder,%20boolean) + InputMethodManager imm = (InputMethodManager) appContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.switchToNextInputMethod(getToken(), false); } } @@ -1144,7 +1326,8 @@ public final class KMManager { return SystemKeyboard; } else { // What should we do if KeyboardType.KEYBOARD_TYPE_UNDEFINED? - Log.e("KMManager", "Invalid keyboard"); + String msg = "Keyboard type undefined"; + KMLog.LogError(TAG, msg); return null; } } @@ -1167,33 +1350,33 @@ public final class KMManager { public static KeyboardState getKeyboardState(Context context, String packageID, String keyboardID, String languageID) { KeyboardState kbState = KeyboardState.KEYBOARD_STATE_UNDEFINED; - if (packageID == null || keyboardID == null || languageID == null) + if (packageID == null || keyboardID == null || languageID == null) { return kbState; + } packageID = packageID.trim(); keyboardID = keyboardID.trim(); languageID = languageID.trim(); - if (keyboardID.isEmpty() || languageID.isEmpty()) + if (keyboardID.isEmpty() || languageID.isEmpty()) { return kbState; + } - String latestVersion = getLatestKeyboardFileVersion(context, packageID, keyboardID); - if (latestVersion == null) { - kbState = KeyboardState.KEYBOARD_STATE_NEEDS_DOWNLOAD; - } else { - kbState = KeyboardState.KEYBOARD_STATE_UP_TO_DATE; - - HashMap> keyboardsInfo = LanguageListUtil.getKeyboardsInfo(context); - if (keyboardsInfo != null) { - // Check version - String kbKey = String.format("%s_%s", languageID, keyboardID); - HashMap kbInfo = keyboardsInfo.get(kbKey); - String kbVersion = "1.0"; - if (kbInfo != null) { - kbVersion = kbInfo.get(KMManager.KMKey_KeyboardVersion); - } - - if (kbVersion != null && (FileUtils.compareVersions(kbVersion, latestVersion) == FileUtils.VERSION_GREATER)) { - kbState = KeyboardState.KEYBOARD_STATE_NEEDS_UPDATE; + // Check latest installed keyboard version + Keyboard kbInfo = null; + String kbVersion = null; + kbState = KeyboardState.KEYBOARD_STATE_NEEDS_DOWNLOAD; + int index = KeyboardController.getInstance().getKeyboardIndex(packageID, languageID, keyboardID); + if (index != KeyboardController.INDEX_NOT_FOUND) { + kbInfo = KeyboardController.getInstance().getKeyboardInfo(index); + if (kbInfo != null) { + kbVersion = kbInfo.getVersion(); + if (kbVersion != null) { + // See if update is available + if (kbInfo.hasUpdateAvailable()) { + kbState = KeyboardState.KEYBOARD_STATE_NEEDS_UPDATE; + } else { + kbState = KeyboardState.KEYBOARD_STATE_UP_TO_DATE; + } } } } @@ -1256,18 +1439,17 @@ public final class KMManager { } else { path = getPackagesDir() + packageID + File.separator + PackageProcessor.PP_DEFAULT_METADATA; - try { - File kmpJSONFile = new File(path); - if (!kmpJSONFile.exists()) { - return null; + File kmpJSONFile = new File(path); + if (!kmpJSONFile.exists()) { + if (!KMManager.isTestMode()) { + KMLog.LogError(TAG, path + " not found. Returning version 1.0"); } - JSONParser jsonParser = new JSONParser(); - JSONObject kmpObject = jsonParser.getJSONObjectFromFile(kmpJSONFile); - - return PackageProcessor.getKeyboardVersion(kmpObject, keyboardID); - } catch (Exception e) { - return null; + return "1.0"; } + JSONParser jsonParser = new JSONParser(); + JSONObject kmpObject = jsonParser.getJSONObjectFromFile(kmpJSONFile); + + return PackageProcessor.getKeyboardVersion(kmpObject, keyboardID); } return kbFileVersion; @@ -1292,6 +1474,7 @@ public final class KMManager { return LexicalModelPackageProcessor.getPackageVersion(kmpObject); } catch (Exception e) { + KMLog.LogException(TAG, "", e); return null; } } @@ -1460,26 +1643,28 @@ public final class KMManager { } public static int getCurrentKeyboardIndex(Context context) { - return KeyboardPickerActivity.getCurrentKeyboardIndex(context); + String key = KMKeyboard.currentKeyboard(); + return KeyboardController.getInstance().getKeyboardIndex(key); } - public static HashMap getCurrentKeyboardInfo(Context context) { - return KeyboardPickerActivity.getCurrentKeyboardInfo(context); + public static Keyboard getCurrentKeyboardInfo(Context context) { + int index = getCurrentKeyboardIndex(context); + return KeyboardController.getInstance().getKeyboardInfo(index); } public static int getKeyboardIndex(Context context, String keyboardID, String languageID) { - int index = -1; + int index = KeyboardController.INDEX_NOT_FOUND; if (keyboardID != null & languageID != null) { String kbKey = String.format("%s_%s", languageID, keyboardID); - index = KeyboardPickerActivity.getKeyboardIndex(context, kbKey); + index = KeyboardController.getInstance().getKeyboardIndex(kbKey); } return index; } - public static HashMap getKeyboardInfo(Context context, int index) { - return KeyboardPickerActivity.getKeyboardInfo(context, index); + public static Keyboard getKeyboardInfo(Context context, int index) { + return KeyboardController.getInstance().getKeyboardInfo(index); } public static HashMap getLexicalModelInfo(Context context, int index) { @@ -1490,8 +1675,9 @@ public final class KMManager { boolean result = false; if (packageID != null && keyboardID != null && languageID != null) { - String kbKey = String.format("%s_%s", languageID, keyboardID); - result = KeyboardPickerActivity.containsKeyboard(context, kbKey); + File keyboardFile = new File(getPackagesDir(), packageID + File.separator + String.format("%s.js", keyboardID)); + result = KeyboardController.getInstance().keyboardExists(packageID, keyboardID, languageID) && + keyboardFile.exists(); } return result; @@ -1508,12 +1694,6 @@ public final class KMManager { return result; } - public static FormFactor getFormFactor() { - String device_type = appContext.getResources().getString(R.string.device_type); - - return device_type.equals("AndroidMobile") ? FormFactor.PHONE : FormFactor.TABLET; - } - public static boolean isHelpBubbleEnabled() { boolean retVal = true; @@ -1571,7 +1751,8 @@ public final class KMManager { } public static void setGlobeKeyAction(KeyboardType kbType, GlobeKeyAction action) { - if (kbType == KeyboardType.KEYBOARD_TYPE_INAPP) { + if (kbType == KeyboardType.KEYBOARD_TYPE_INAPP && + action != GlobeKeyAction.GLOBE_KEY_ACTION_ADVANCE_TO_NEXT_SYSTEM_KEYBOARD) { inappKbGlobeKeyAction = action; } else if (kbType == KeyboardType.KEYBOARD_TYPE_SYSTEM) { sysKbGlobeKeyAction = action; @@ -1596,7 +1777,6 @@ public final class KMManager { } private void pageLoaded(WebView view, String url) { - String langId = KMManager.KMKey_LanguageID; Log.d("KMEA", "pageLoaded: [inapp] " + url); if (url.startsWith("file")) { //endsWith(KMFilename_KeyboardHtml)) { InAppKeyboardLoaded = true; @@ -1607,22 +1787,25 @@ public final class KMManager { if (index < 0) { index = 0; } - HashMap keyboardInfo = KMManager.getKeyboardInfo(context, index); + Keyboard keyboardInfo = KMManager.getKeyboardInfo(context, index); + String langId = null; if (keyboardInfo != null) { - String pkgId = keyboardInfo.get(KMManager.KMKey_PackageID); - String kbId = keyboardInfo.get(KMManager.KMKey_KeyboardID); - langId = keyboardInfo.get(KMManager.KMKey_LanguageID); - String kbName = keyboardInfo.get(KMManager.KMKey_KeyboardName); - String langName = keyboardInfo.get(KMManager.KMKey_LanguageName); - String kFont = keyboardInfo.get(KMManager.KMKey_Font); - String kOskFont = keyboardInfo.get(KMManager.KMKey_OskFont); - InAppKeyboard.setKeyboard(pkgId, kbId, langId, kbName, langName, kFont, kOskFont); + langId = keyboardInfo.getLanguageID(); + InAppKeyboard.setKeyboard(keyboardInfo); } else { - InAppKeyboard.setKeyboard(KMDefault_PackageID, KMDefault_KeyboardID, - KMDefault_LanguageID, KMDefault_KeyboardName, KMDefault_LanguageName, KMDefault_KeyboardFont, null); + // Revert to default (index 0) or fallback keyboard + keyboardInfo = KMManager.getKeyboardInfo(context, 0); + if (keyboardInfo == null) { + KMLog.LogError(TAG, "No keyboards installed. Reverting to fallback"); + keyboardInfo = KMManager.getDefaultKeyboard(context); + } + if (keyboardInfo != null) { + langId = keyboardInfo.getLanguageID(); + InAppKeyboard.setKeyboard(keyboardInfo); + } } - registerAssociatedLexicalModel(langId); + registerAssociatedLexicalModel(langId); } Handler handler = new Handler(); @@ -1784,7 +1967,6 @@ public final class KMManager { double width = Float.parseFloat(urlCommand.getQueryParameter("w")); double height = Float.parseFloat(urlCommand.getQueryParameter("h")); String suggestionJSON = urlCommand.getQueryParameter("suggestion"); - boolean isCustom = Boolean.parseBoolean(urlCommand.getQueryParameter("custom")); JSONParser parser = new JSONParser(); JSONObject obj = parser.getJSONObjectFromURIString(suggestionJSON); @@ -1796,7 +1978,7 @@ public final class KMManager { try { Log.v("KMEA", "Suggestion display: " + obj.getString("displayAs")); Log.v("KMEA", "Suggestion's banner coords: " + x + ", " + y + ", " + width + ", " + height); - Log.v("KMEA", "Is a suggestion: " + isCustom); // likely outdated now that tags exist. + Log.v("KMEA", "Is a suggestion: "); // likely outdated now that tags exist. } catch (JSONException e) { //e.printStackTrace(); Log.v("KMEA", "JSON parsing error: " + e.getMessage()); @@ -1825,7 +2007,6 @@ public final class KMManager { } private void pageLoaded(WebView view, String url) { - String langId = KMManager.KMKey_LanguageID; Log.d("KMEA", "pageLoaded: [system] " + url); if (url.startsWith("file:")) { SystemKeyboardLoaded = true; @@ -1835,23 +2016,27 @@ public final class KMManager { if (index < 0) { index = 0; } - HashMap keyboardInfo = KMManager.getKeyboardInfo(context, index); + Keyboard keyboardInfo = KMManager.getKeyboardInfo(context, index); + String langId = null; if (keyboardInfo != null) { - String pkgId = keyboardInfo.get(KMManager.KMKey_PackageID); - String kbId = keyboardInfo.get(KMManager.KMKey_KeyboardID); - langId = keyboardInfo.get(KMManager.KMKey_LanguageID); - String kbName = keyboardInfo.get(KMManager.KMKey_KeyboardName); - String langName = keyboardInfo.get(KMManager.KMKey_LanguageName); - String kFont = keyboardInfo.get(KMManager.KMKey_Font); - String kOskFont = keyboardInfo.get(KMManager.KMKey_OskFont); - SystemKeyboard.setKeyboard(pkgId, kbId, langId, kbName, langName, kFont, kOskFont); + langId = keyboardInfo.getLanguageID(); + SystemKeyboard.setKeyboard(keyboardInfo); } else { - SystemKeyboard.setKeyboard(KMDefault_UndefinedPackageID, KMDefault_KeyboardID, - KMDefault_LanguageID, KMDefault_KeyboardName, KMDefault_LanguageName, KMDefault_KeyboardFont, null); + // Revert to default (index 0) or fallback keyboard + keyboardInfo = KMManager.getKeyboardInfo(context, 0); + if (keyboardInfo == null) { + KMLog.LogError(TAG, "No keyboards installed. Reverting to fallback"); + keyboardInfo = KMManager.getDefaultKeyboard(context); + } + if (keyboardInfo != null) { + langId = keyboardInfo.getLanguageID(); + SystemKeyboard.setKeyboard(keyboardInfo); + } } + + registerAssociatedLexicalModel(langId); } - registerAssociatedLexicalModel(langId); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @@ -1890,29 +2075,43 @@ public final class KMManager { if (KMManager.shouldAllowSetKeyboard()) { if (SystemKeyboard.keyboardPickerEnabled) { - KeyguardManager km = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE); - if(km.inKeyguardRestrictedInputMode()) { + KeyguardManager keyguardManager = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE); + GlobeKeyAction action = sysKbGlobeKeyAction; + if(keyguardManager.inKeyguardRestrictedInputMode()) { // Override system keyboard 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 (sysKbIndexOnLockScreen == -1) { - sysKbIndexOnLockScreen = getCurrentKeyboardIndex(context); - sysKbGlobeKeyAction = GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD; - } else if (sysKbIndexOnLockScreen == getCurrentKeyboardIndex(context)) { - sysKbGlobeKeyAction = GlobeKeyAction.GLOBE_KEY_ACTION_ADVANCE_TO_NEXT_SYSTEM_KEYBOARD; + if (sysKbStartingIndexOnLockScreen == getCurrentKeyboardIndex(context)) { + // All the Keyman keyboards have been cycled through + action = GlobeKeyAction.GLOBE_KEY_ACTION_ADVANCE_TO_NEXT_SYSTEM_KEYBOARD; + } else { + if (sysKbStartingIndexOnLockScreen == -1) { + // Initialize the system keyboard starting index while the screen is locked + sysKbStartingIndexOnLockScreen = getCurrentKeyboardIndex(context); + } + action = GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD; } } else { - // If screen isn't locked, revert to default system globe key action - sysKbIndexOnLockScreen = -1; - sysKbGlobeKeyAction = GlobeKeyAction.GLOBE_KEY_ACTION_SHOW_MENU; + // If screen isn't locked, reset the starting index + sysKbStartingIndexOnLockScreen = -1; } - if (sysKbGlobeKeyAction == GlobeKeyAction.GLOBE_KEY_ACTION_SHOW_MENU) { - showKeyboardPicker(context, KeyboardType.KEYBOARD_TYPE_SYSTEM); - } else if (sysKbGlobeKeyAction == GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD) { - switchToNextKeyboard(context); - } else if (sysKbGlobeKeyAction == GlobeKeyAction.GLOBE_KEY_ACTION_ADVANCE_TO_NEXT_SYSTEM_KEYBOARD) { - advanceToNextInputMode(); + switch (action) { + case GLOBE_KEY_ACTION_SHOW_MENU: + showKeyboardPicker(context, KeyboardType.KEYBOARD_TYPE_SYSTEM); + break; + case GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD: + switchToNextKeyboard(context); + break; + case GLOBE_KEY_ACTION_ADVANCE_TO_NEXT_SYSTEM_KEYBOARD: + advanceToNextInputMode(); + break; + case GLOBE_KEY_ACTION_SHOW_SYSTEM_KEYBOARDS: + InputMethodManager imm = (InputMethodManager) appContext.getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showInputMethodPicker(); + break; + default: + // Do nothing } } else { switchToNextKeyboard(context); @@ -2026,7 +2225,6 @@ public final class KMManager { double width = Float.parseFloat(urlCommand.getQueryParameter("w")); double height = Float.parseFloat(urlCommand.getQueryParameter("h")); String suggestionJSON = urlCommand.getQueryParameter("suggestion"); - boolean isCustom = Boolean.parseBoolean(urlCommand.getQueryParameter("custom")); JSONParser parser = new JSONParser(); JSONObject obj = parser.getJSONObjectFromURIString(suggestionJSON); @@ -2038,7 +2236,7 @@ public final class KMManager { try { Log.v("KMEA", "Suggestion display: " + obj.getString("displayAs")); Log.v("KMEA", "Suggestion's banner coords: " + x + ", " + y + ", " + width + ", " + height); - Log.v("KMEA", "Is a suggestion: " + isCustom); // likely outdated now that tags exist. + Log.v("KMEA", "Is a suggestion: "); // likely outdated now that tags exist. } catch (JSONException e) { //e.printStackTrace(); Log.v("KMEA", "JSON parsing error: " + e.getMessage()); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMPBrowserActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMPBrowserActivity.java index 53095176db87f0e75d2db52c71993af1a409f7ce..17a0fb70b8b4dd5376fdfbee1b73a25fb28919ec 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMPBrowserActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMPBrowserActivity.java @@ -24,12 +24,33 @@ import android.webkit.WebViewClient; import androidx.appcompat.app.AppCompatActivity; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.KMManager.Tier; +import com.tavultesoft.kmea.util.KMPLink; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.tavultesoft.kmea.util.KMPLink.KMP_PRODUCTION_HOST; +import static com.tavultesoft.kmea.util.KMPLink.KMP_STAGING_HOST; public class KMPBrowserActivity extends AppCompatActivity { private static final String TAG = "KMPBrowserActivity"; + + // URL for keyboard search web page presented to user when they add a keyboard in the app. + private static final String KMP_SEARCH_KEYBOARDS_FORMATSTR = "https://%s/go/android/%s/download-keyboards%s"; + private static final String KMP_SEARCH_KEYBOARDS_LANGUAGES = "/languages/%s"; + + // Patterns for determining if a link should be opened in external browser + // 1. Host isn't keyman.com (production/staging) + // 2. Host is keyman.com but not /keyboards/ + private static final String INTERNAL_KEYBOARDS_LINK_FORMATSTR = "^http(s)?://(%s|%s)/keyboards([/?].*)?$"; + private static final String keyboardPatternFormatStr = String.format(INTERNAL_KEYBOARDS_LINK_FORMATSTR, + KMPLink.KMP_PRODUCTION_HOST, + KMPLink.KMP_STAGING_HOST); + private static final Pattern keyboardPattern = Pattern.compile(keyboardPatternFormatStr); + private WebView webView; - private static final String KMP_SEARCH_URL_FORMATSTR = "https://keyman.com/keyboards%s?embed=linux&version=%s"; // TODO: Update to Android - private static final String KMP_LANGUAGE_FORMATSTR = "/languages/%s"; private boolean isLoading = false; private boolean didFinishLoading = false; @@ -67,14 +88,23 @@ public class KMPBrowserActivity extends AppCompatActivity { if (lowerURL.equals("about:blank")) { return true; // never load a blank page, e.g. when the component initializes } - if (FileUtils.isKeymanLink(lowerURL)) { - // KMAPro main activity will handle this intent - // Pass original url because path and query are case-sensitive - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); + + if (KMPLink.isKeymanInstallLink(url)) { + Uri downloadURI = KMPLink.getKeyboardDownloadLink(url); + + // Create intent with keyboard download link for KMAPro main activity to handle + Intent intent = new Intent(Intent.ACTION_VIEW, downloadURI); startActivityForResult(intent, 1); // Finish activity finish(); + } else if (!isKeymanKeyboardsLink(url)) { + Uri uri = Uri.parse(url); + + // All links that aren't internal Keyman keyboard links open in user's browser + Intent intent = new Intent(Intent.ACTION_VIEW, uri); + startActivity(intent); + return true; } if (lowerURL.startsWith("keyman:")) { // Warn for unsupported keyman schemes @@ -99,11 +129,13 @@ public class KMPBrowserActivity extends AppCompatActivity { } }); + // Tier determines the keyboard search host + String host = KMPLink.getHost(); // If language ID is provided, include it in the keyboard search String languageID = getIntent().getStringExtra("languageCode"); - String languageStr = (languageID != null) ? String.format(KMP_LANGUAGE_FORMATSTR, languageID) : ""; - String appVersion = KMManager.getVersion(); - String kmpSearchUrl = String.format(KMP_SEARCH_URL_FORMATSTR, languageStr, appVersion); + String languageStr = (languageID != null) ? String.format(KMP_SEARCH_KEYBOARDS_LANGUAGES, languageID) : ""; + String appMajorVersion = KMManager.getMajorVersion(); + String kmpSearchUrl = String.format(KMP_SEARCH_KEYBOARDS_FORMATSTR, host, appMajorVersion, languageStr); webView.loadUrl(kmpSearchUrl); } @@ -153,4 +185,21 @@ public class KMPBrowserActivity extends AppCompatActivity { } } + /** + * Check if a URL is a valid internal Keyman keyboard link + * @param url String of the URL to parse + * @return boolean + */ + public boolean isKeymanKeyboardsLink(String url) { + boolean status = false; + if (url == null || url.isEmpty()) { + return status; + } + Matcher matcher = keyboardPattern.matcher(url); + if (matcher.matches()) { + status = true; + } + + return status; + } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMTextView.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMTextView.java index 80b11ea2c6e0d742398cfabd9e2767f943cb2428..88a0b9cc8da8a5433a3d73e0d0345fc1d584ca2b 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMTextView.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KMTextView.java @@ -9,6 +9,7 @@ import java.util.ArrayList; import com.tavultesoft.kmea.KMManager.KeyboardType; import com.tavultesoft.kmea.KeyboardEventHandler.EventType; import com.tavultesoft.kmea.KeyboardEventHandler.OnKeyboardEventListener; +import com.tavultesoft.kmea.util.KMLog; import android.view.ContextThemeWrapper; import androidx.appcompat.app.AppCompatActivity; @@ -16,7 +17,6 @@ import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.util.AttributeSet; -import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; @@ -29,6 +29,7 @@ import android.widget.FrameLayout; import android.widget.RelativeLayout; public final class KMTextView extends AppCompatEditText { + private static final String TAG = "KMTextView"; private Context context; protected KMHardwareKeyboardInterpreter hardwareKeyboardInterpreter; @@ -154,6 +155,7 @@ public final class KMTextView extends AppCompatEditText { @Override protected void onSelectionChanged(int selStart, int selEnd) { + super.onSelectionChanged(selStart, selEnd); if (activeView != null && activeView.equals(this)) { KMManager.updateSelectionRange(KMManager.KeyboardType.KEYBOARD_TYPE_INAPP, selStart, selEnd); } @@ -198,7 +200,7 @@ public final class KMTextView extends AppCompatEditText { dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode)); dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEventCode)); } catch (Exception e) { - Log.e("KMEA Error:", e.toString()); + KMLog.LogException(TAG, "", e); } finally { _blockEventProcessing = false; } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardInfoActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardInfoActivity.java index e154d9f0900cd7df62f04cf9d026a640ac12e7bc..63f95182abd2de80f4dffe11b7118611dd87a076 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardInfoActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardInfoActivity.java @@ -63,8 +63,8 @@ public final class KeyboardInfoActivity extends AppCompatActivity { listView = (ListView) findViewById(R.id.listView); final Keyboard kbd = (Keyboard)getIntent().getSerializableExtra(KMManager.KMKey_Keyboard); final String packageID = kbd.getPackageID(); - final String kbID = kbd.getResourceId(); - final String kbName = kbd.getResourceName(); + final String kbID = kbd.getKeyboardID(); + final String kbName = kbd.getKeyboardName(); final String kbVersion = kbd.getVersion(); final TextView textView = (TextView) findViewById(R.id.bar_title); @@ -83,7 +83,7 @@ public final class KeyboardInfoActivity extends AppCompatActivity { // Display keyboard help link hashMap = new HashMap(); - final String customHelpLink = kbd.getCustomHelpLink(); + final String customHelpLink = kbd.getHelpLink(); // Check if app declared FileProvider String icon = String.valueOf(R.drawable.ic_arrow_forward); // Don't show help link arrow if File Provider unavailable, or custom help doesn't exist @@ -146,7 +146,7 @@ public final class KeyboardInfoActivity extends AppCompatActivity { LinearLayout qrLayout = (LinearLayout) view.findViewById(R.id.qrLayout); listView.addFooterView(qrLayout); - String url = String.format(QRCodeUtil.QR_BASE, kbID); + String url = String.format(QRCodeUtil.QR_CODE_URL_FORMATSTR, kbID); Bitmap myBitmap = QRCodeUtil.toBitmap(url); ImageView imageView = (ImageView) findViewById(R.id.qrCode); imageView.setImageBitmap(myBitmap); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardPickerActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardPickerActivity.java index c05e1392ff1cb5b589d240df4ac4086975b315cd..64d5562869df542909ea0ea2b66cf692104dbfe9 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardPickerActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardPickerActivity.java @@ -18,7 +18,9 @@ import com.tavultesoft.kmea.cloud.CloudDataJsonUtil; import com.tavultesoft.kmea.data.CloudRepository; import com.tavultesoft.kmea.data.Dataset; import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.KeyboardController; import com.tavultesoft.kmea.data.LexicalModel; +import com.tavultesoft.kmea.util.KMLog; import com.tavultesoft.kmea.util.MapCompat; import androidx.appcompat.app.AppCompatActivity; @@ -26,6 +28,7 @@ import androidx.appcompat.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; +//import android.inputmethodservice.Keyboard; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; @@ -52,9 +55,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { public static final String KMKEY_INTERNAL_NEW_KEYBOARD = "_internal_new_keyboard_"; - // TODO: Refactoring to remove keyboard selection into own keyboard manager class (MVC) - // Lists of installed keyboards and installed lexical models - private static ArrayList> keyboardsList = null; + // List of installed lexical models private static ArrayList> lexicalModelsList = null; private static Dataset storageDataset = null; @@ -62,7 +63,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { private static int selectedIndex = 0; private static final String TAG = "KeyboardPickerActivity"; - protected static int selectedIndex() { + public static int selectedIndex() { return selectedIndex; } @@ -105,30 +106,6 @@ public final class KeyboardPickerActivity extends AppCompatActivity { listView = (ListView) findViewById(R.id.listView); - //TODO: put into a logic class - keyboardsList = getKeyboardsList(context); - if (keyboardsList == null) { - keyboardsList = new ArrayList>(); - HashMap kbInfo = new HashMap(); - kbInfo.put(KMManager.KMKey_PackageID, KMManager.KMDefault_PackageID); - kbInfo.put(KMManager.KMKey_KeyboardID, KMManager.KMDefault_KeyboardID); - kbInfo.put(KMManager.KMKey_LanguageID, KMManager.KMDefault_LanguageID); - kbInfo.put(KMManager.KMKey_KeyboardName, KMManager.KMDefault_KeyboardName); - kbInfo.put(KMManager.KMKey_LanguageName, KMManager.KMDefault_LanguageName); - kbInfo.put(KMManager.KMKey_KeyboardVersion, KMManager.getLatestKeyboardFileVersion( - context, KMManager.KMDefault_PackageID, KMManager.KMDefault_KeyboardID)); - kbInfo.put(KMManager.KMKey_CustomKeyboard, "N"); - kbInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont); - keyboardsList.add(kbInfo); - - // We'd prefer not to overwrite a file if it exists - File file = new File(context.getDir("userdata", Context.MODE_PRIVATE), - KMManager.KMFilename_KeyboardsList); - if (!file.exists()) { - saveList(context, KMManager.KMFilename_KeyboardsList); - } - } - lexicalModelsList = getLexicalModelsList(context); if (lexicalModelsList == null) { lexicalModelsList = new ArrayList>(); @@ -158,6 +135,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { listView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView parent, View view, final int position, long id) { + // Prevent the default keyboard from being removed if (position > 0 && canRemoveKeyboard) { PopupMenu popup = new PopupMenu(context, view); popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu()); @@ -179,7 +157,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { } }); - int curKbPos = getCurrentKeyboardIndex(); + int curKbPos = KeyboardController.getInstance().getKeyboardIndex(KMKeyboard.currentKeyboard()); setSelection(curKbPos); KMKeyboard.addOnKeyboardEventListener(new KeyboardEventHandler.OnKeyboardEventListener() { @@ -190,16 +168,23 @@ public final class KeyboardPickerActivity extends AppCompatActivity { @Override public void onKeyboardChanged(String newKeyboard) { - int _index = getKeyboardIndex(context,newKeyboard); + int _index = KeyboardController.getInstance().getKeyboardIndex(newKeyboard); if(_index>=0) { - Map _keyboard = keyboardsList.get(_index); - if(_keyboard==null) + Keyboard _keyboard = KeyboardController.getInstance().getKeyboardInfo(_index); + if(_keyboard==null) { return; - if(_keyboard.get(KMKEY_INTERNAL_NEW_KEYBOARD)==null) + } + if(!_keyboard.getNewKeyboard()) { return; - _keyboard.remove(KMKEY_INTERNAL_NEW_KEYBOARD); - saveList(context, KMManager.KMFilename_KeyboardsList); + } + + if (_keyboard.getNewKeyboard()) { + _keyboard.setNewKeyboard(false); + // Update entry + KeyboardController.getInstance().add(_keyboard); + KeyboardController.getInstance().save(context); + } notifyKeyboardsUpdate(context); } } @@ -224,7 +209,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { adapter.notifyDataSetChanged(); } - int curKbPos = getCurrentKeyboardIndex(); + int curKbPos = KeyboardController.getInstance().getKeyboardIndex(KMKeyboard.currentKeyboard()); setSelection(curKbPos); if (!shouldCheckKeyboardUpdates) return; @@ -253,41 +238,9 @@ public final class KeyboardPickerActivity extends AppCompatActivity { finish(); } - private static int getCurrentKeyboardIndex() { - int pos = 0; - - if (keyboardsList != null) { - int length = keyboardsList.size(); - for (int i = 0; i < length; i++) { - HashMap kbInfo = keyboardsList.get(i); - String langId = kbInfo.get(KMManager.KMKey_LanguageID); - String kbId = kbInfo.get(KMManager.KMKey_KeyboardID); - String kbKey = String.format("%s_%s", langId, kbId); - if (kbKey.equals(KMKeyboard.currentKeyboard())) { - pos = i; - break; - } - } - } - - return pos; - } - - // Previously, keyboard from package = custom keyboard - // Now, keyboard from package has a package ID != "cloud" - protected static boolean hasKeyboardFromPackage() { - for(HashMap kbInfo: keyboardsList) { - String pkgID = MapCompat.getOrDefault(kbInfo, KMManager.KMKey_PackageID, KMManager.KMDefault_UndefinedPackageID); - if (!pkgID.equalsIgnoreCase(KMManager.KMDefault_UndefinedPackageID)) { - return true; - } - } - - return false; - } - private static boolean saveList(Context context, String listName) { boolean result; + List keyboardsList = KeyboardController.getInstance().get(); try { File file = new File(context.getDir("userdata", Context.MODE_PRIVATE), listName); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file)); @@ -300,27 +253,13 @@ public final class KeyboardPickerActivity extends AppCompatActivity { outputStream.close(); result = true; } catch (Exception e) { - Log.e(TAG, "Failed to save " + listName + ". Error: " + e); + KMLog.LogException(TAG, "Failed to save " + listName + ". Error: ", e); result = false; } return result; } - /** - * Save the list of installed keyboards - * @param context - * @param list - * @return boolean - Status if the keyboard list was successfully saved - */ - protected static boolean updateKeyboardsList(Context context, ArrayList> list) { - boolean result; - keyboardsList = list; - result = saveList(context, KMManager.KMFilename_KeyboardsList); - notifyKeyboardsUpdate(context); - return result; - } - /** * Save the list of installed lexical models * @param context @@ -348,71 +287,43 @@ public final class KeyboardPickerActivity extends AppCompatActivity { */ private static void switchKeyboard(int position, boolean aPrepareOnly) { setSelection(position); - int listPosition = (position >= keyboardsList.size()) ? keyboardsList.size()-1 : position; - HashMap kbInfo = keyboardsList.get(listPosition); - String pkgId = kbInfo.get(KMManager.KMKey_PackageID); - if (pkgId == null || pkgId.isEmpty()) { - pkgId = KMManager.KMDefault_UndefinedPackageID; - } - String kbId = kbInfo.get(KMManager.KMKey_KeyboardID); - String langId = kbInfo.get(KMManager.KMKey_LanguageID); - String kbName = kbInfo.get(KMManager.KMKey_KeyboardName); - String langName = kbInfo.get(KMManager.KMKey_LanguageName); - String kFont = kbInfo.get(KMManager.KMKey_Font); - String kOskFont = kbInfo.get(KMManager.KMKey_OskFont); + int size = KeyboardController.getInstance().get().size(); + int listPosition = (position >= size) ? size-1 : position; + Keyboard kbInfo = KeyboardController.getInstance().getKeyboardInfo(listPosition); + String pkgId = kbInfo.getPackageID(); + String kbId = kbInfo.getKeyboardID(); + String langId = kbInfo.getLanguageID(); + String kbName = kbInfo.getKeyboardName(); if(aPrepareOnly) KMManager.prepareKeyboardSwitch(pkgId, kbId, langId, kbName); else - KMManager.setKeyboard(pkgId, kbId, langId, kbName, langName, kFont, kOskFont); + KMManager.setKeyboard(kbInfo); } - protected static boolean addKeyboard(Context context, HashMap keyboardInfo) { + protected static boolean addKeyboard(Context context, Keyboard keyboardInfo) { boolean result = false; - - if (keyboardsList == null) { - keyboardsList = getKeyboardsList(context); - } - - if (keyboardsList == null) { - keyboardsList = new ArrayList>(); - } + List keyboardsList = KeyboardController.getInstance().get(); if (keyboardInfo != null) { - String pkgID = keyboardInfo.get(KMManager.KMKey_PackageID); - String kbID = keyboardInfo.get(KMManager.KMKey_KeyboardID); - String langID = keyboardInfo.get(KMManager.KMKey_LanguageID); - - // TODO: Possible optimization - do we have anything with this language code already? - // Only invalidate the lexical cache if not. - CloudRepository.shared.invalidateLexicalModelCache(context); - - if (pkgID != null && kbID != null && langID != null) { - String kbKey = String.format("%s_%s", langID, kbID); - if (kbKey.length() >= 3) { - int x = getKeyboardIndex(context, kbKey); - if (x >= 0) { - if(keyboardsList.get(x).get(KMKEY_INTERNAL_NEW_KEYBOARD)!=null) - keyboardInfo.put(KMKEY_INTERNAL_NEW_KEYBOARD,KMKEY_INTERNAL_NEW_KEYBOARD); - keyboardsList.set(x, keyboardInfo); - result = saveList(context, KMManager.KMFilename_KeyboardsList); - } else { - keyboardInfo.put(KMKEY_INTERNAL_NEW_KEYBOARD,KMKEY_INTERNAL_NEW_KEYBOARD); - keyboardsList.add(keyboardInfo); - result = saveList(context, KMManager.KMFilename_KeyboardsList); - if (!result) { - keyboardsList.remove(keyboardsList.size() - 1); - } - } - } + String languageID = keyboardInfo.getLanguageID(); + if (CloudRepository.shared.getAssociatedLexicalModel(context, languageID) == null) { + // Only invalidate the lexical cache if there's no associated lexical model + CloudRepository.shared.invalidateLexicalModelCache(context); } - } + keyboardInfo.setNewKeyboard(true); + KeyboardController.getInstance().add(keyboardInfo); + result = KeyboardController.getInstance().save(context); + if (!result) { + KMLog.LogError(TAG, "addKeyboard failed to save"); + } + } notifyKeyboardsUpdate(context); return result; } - protected static boolean addLexicalModel(Context context, HashMap lexicalModelInfo) { + public static boolean addLexicalModel(Context context, HashMap lexicalModelInfo) { boolean result = false; if (lexicalModelsList == null) { @@ -443,6 +354,9 @@ public final class KeyboardPickerActivity extends AppCompatActivity { lexicalModelsList.remove(lexicalModelsList.size() - 1); } } + + // Invalidate cache to rebuild the list + CloudRepository.shared.invalidateLexicalModelCache(context); } } } @@ -454,13 +368,11 @@ public final class KeyboardPickerActivity extends AppCompatActivity { protected static boolean removeKeyboard(Context context, int position) { boolean result = false; - if (keyboardsList == null) { - keyboardsList = getKeyboardsList(context); - } - if (keyboardsList != null && position >= 0 && position < keyboardsList.size()) { - keyboardsList.remove(position); - result = saveList(context, KMManager.KMFilename_KeyboardsList); + // Prevent the first keyboard (index 0) from being removed + if (position > 0) { + KeyboardController.getInstance().remove(position); + result = KeyboardController.getInstance().save(context); } notifyKeyboardsUpdate(context); @@ -469,7 +381,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { } protected static void deleteKeyboard(Context context, int position) { - int curKbPos = getCurrentKeyboardIndex(); + int curKbPos = KeyboardController.getInstance().getKeyboardIndex(KMKeyboard.currentKeyboard()); boolean result = removeKeyboard(context, position); if (result) { @@ -481,7 +393,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { if (position == curKbPos && listView != null) { switchKeyboard(0,false); } else if(listView != null) { // A bit of a hack, since LanguageSettingsActivity calls this method too. - curKbPos = getCurrentKeyboardIndex(); + curKbPos = KeyboardController.getInstance().getKeyboardIndex(KMKeyboard.currentKeyboard()); setSelection(curKbPos); } } @@ -565,7 +477,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { list = (ArrayList>) inputStream.readObject(); inputStream.close(); } catch (Exception e) { - Log.e(TAG, "Failed to read " + filename + ". Error: " + e); + KMLog.LogException(TAG, "Failed to read " + filename + ". Error: ", e); list = null; } } @@ -578,42 +490,24 @@ public final class KeyboardPickerActivity extends AppCompatActivity { return storageDataset; } - List> kbdMapList = getKeyboardsList(context); - if (kbdMapList == null) { - kbdMapList = new ArrayList<>(0); - } - List kbdsList = new ArrayList<>(kbdMapList.size()); - - for(HashMap kbdMap: kbdMapList) { - boolean isCustom = kbdMap.containsKey(KMManager.KMKey_CustomKeyboard) && - kbdMap.get(KMManager.KMKey_CustomKeyboard).equals("Y"); - boolean isNewKeyboard = kbdMap.containsKey(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD) && - kbdMap.get(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD).equals(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD); - - Keyboard k = new Keyboard( - kbdMap.get(KMManager.KMKey_PackageID), - kbdMap.get(KMManager.KMKey_KeyboardID), - kbdMap.get(KMManager.KMKey_KeyboardName), - kbdMap.get(KMManager.KMKey_LanguageID), - kbdMap.get(KMManager.KMKey_LanguageName), - isCustom, - isNewKeyboard, - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_Font, null), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_OskFont, null), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_Version, "1.0"), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_CustomHelpLink, "") - ); - kbdsList.add(k); - } - - List> lexMapList = getLexicalModelsList(context); + List kbdsList = getKeyboardsList(context); + List> lexMapList = getLexicalModelsList(context); if(lexMapList == null) { lexMapList = new ArrayList<>(0); } List lexList = new ArrayList<>(lexMapList.size()); - for(Map map: lexMapList) { - lexList.add(new LexicalModel(map)); + for(HashMap lmMap: lexMapList) { + LexicalModel m = new LexicalModel( + lmMap.get(KMManager.KMKey_PackageID), + lmMap.get(KMManager.KMKey_LexicalModelID), + lmMap.get(KMManager.KMKey_LexicalModelName), + lmMap.get(KMManager.KMKey_LanguageID), + lmMap.get(KMManager.KMKey_LanguageName), + MapCompat.getOrDefault(lmMap, KMManager.KMKey_LexicalModelVersion, "1.0"), + MapCompat.getOrDefault(lmMap, KMManager.KMKey_CustomHelpLink, ""), + MapCompat.getOrDefault(lmMap, KMManager.KMKey_KMPLink, "")); + lexList.add(m); } storageDataset = new Dataset(context); @@ -630,29 +524,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { storage.keyboards.setNotifyOnChange(false); storage.keyboards.clear(); - List> mapList = getKeyboardsList(context); - List kbdList = new ArrayList<>(mapList.size()); - for(HashMap kbdMap: mapList) { - boolean isCustom = kbdMap.containsKey(KMManager.KMKey_CustomKeyboard) && - kbdMap.get(KMManager.KMKey_CustomKeyboard).equals("Y"); - boolean isNewKeyboard = kbdMap.containsKey(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD) && - kbdMap.get(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD).equals(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD); - - Keyboard k = new Keyboard( - kbdMap.get(KMManager.KMKey_PackageID), - kbdMap.get(KMManager.KMKey_KeyboardID), - kbdMap.get(KMManager.KMKey_KeyboardName), - kbdMap.get(KMManager.KMKey_LanguageID), - kbdMap.get(KMManager.KMKey_LanguageName), - isCustom, - isNewKeyboard, - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_Font, null), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_OskFont, null), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_Version, "1.0"), - MapCompat.getOrDefault(kbdMap, KMManager.KMKey_CustomHelpLink, "") - ); - kbdList.add(k); - } + List kbdList = KeyboardController.getInstance().get(); storage.keyboards.addAll(kbdList); storage.keyboards.notifyDataSetChanged(); } @@ -662,43 +534,32 @@ public final class KeyboardPickerActivity extends AppCompatActivity { storage.lexicalModels.setNotifyOnChange(false); storage.lexicalModels.clear(); - List> mapList = getLexicalModelsList(context); + List> mapList = getLexicalModelsList(context); List lexList = new ArrayList<>(mapList.size()); - for(Map map: mapList) { - lexList.add(new LexicalModel(map)); + for(HashMap lmMap: mapList) { + LexicalModel m = new LexicalModel( + lmMap.get(KMManager.KMKey_PackageID), + lmMap.get(KMManager.KMKey_LexicalModelID), + lmMap.get(KMManager.KMKey_LexicalModelName), + lmMap.get(KMManager.KMKey_LanguageID), + lmMap.get(KMManager.KMKey_LanguageName), + MapCompat.getOrDefault(lmMap, KMManager.KMKey_LexicalModelVersion, "1.0"), + MapCompat.getOrDefault(lmMap, KMManager.KMKey_CustomHelpLink, ""), + MapCompat.getOrDefault(lmMap, KMManager.KMKey_KMPLink, "")); + lexList.add(m); } storage.lexicalModels.addAll(lexList); - storage.lexicalModels.notifyDataSetChanged(); } - protected static ArrayList> getKeyboardsList(Context context) { - return getList(context, KMManager.KMFilename_KeyboardsList); + protected static List getKeyboardsList(Context context) { + return KeyboardController.getInstance().get(); } protected static ArrayList> getLexicalModelsList(Context context) { return getList(context, KMManager.KMFilename_LexicalModelsList); } - protected static boolean containsKeyboard(Context context, String keyboardKey) { - if (keyboardsList == null) { - keyboardsList = getKeyboardsList(context); - } - - String kbKeys = ""; - if (keyboardsList != null) { - int length = keyboardsList.size(); - for (int i = 0; i < length; i++) { - kbKeys += String.format("%s_%s", keyboardsList.get(i).get(KMManager.KMKey_LanguageID), keyboardsList.get(i).get(KMManager.KMKey_KeyboardID)); - if (i < length - 1) { - kbKeys += ","; - } - } - } - - return kbKeys.contains(keyboardKey); - } - public static boolean containsLexicalModel(Context context, String lexicalModelKey) { if (lexicalModelsList == null) { lexicalModelsList = getLexicalModelsList(context); @@ -719,91 +580,13 @@ public final class KeyboardPickerActivity extends AppCompatActivity { return false; } - protected static int getCurrentKeyboardIndex(Context context) { - int index = -1; - - if (keyboardsList == null) { - keyboardsList = getKeyboardsList(context); - } - - if (keyboardsList != null) { - int length = keyboardsList.size(); - for (int i = 0; i < length; i++) { - HashMap kbInfo = keyboardsList.get(i); - String langId = kbInfo.get(KMManager.KMKey_LanguageID); - String kbId = kbInfo.get(KMManager.KMKey_KeyboardID); - String kbKey = String.format("%s_%s", langId, kbId); - if (kbKey.equals(KMKeyboard.currentKeyboard())) { - index = i; - break; - } - } - } - - return index; - } - - protected static HashMap getCurrentKeyboardInfo(Context context) { - int index = getCurrentKeyboardIndex(context); - if (index >= 0) { - return keyboardsList.get(index); - } else { - return null; - } - } - - protected static int getKeyboardIndex(Context context, String keyboardKey) { - int index = -1; - - if (keyboardsList == null) { - keyboardsList = getKeyboardsList(context); - } - - if (keyboardsList != null) { - int length = keyboardsList.size(); - for (int i = 0; i < length; i++) { - HashMap kbInfo = keyboardsList.get(i); - String langId = kbInfo.get(KMManager.KMKey_LanguageID); - String kbId = kbInfo.get(KMManager.KMKey_KeyboardID); - String kbKey = String.format("%s_%s", langId, kbId); - if (kbKey.equals(keyboardKey)) { - index = i; - break; - } - } - } - - return index; - } - - /** - * Get the list of associated keyboards for a given language ID - * @param langId - * @return ArrayList of keyboard - */ - public static ArrayList> getAssociatedKeyboards(String langId) { - if (keyboardsList != null) { - ArrayList> associatedKeyboards = new ArrayList>(); - for (HashMap keyboardInfo: keyboardsList) { - if (keyboardInfo.get(KMManager.KMKey_LanguageID).equalsIgnoreCase(langId)) { - keyboardInfo.put(KMManager.KMKey_Icon, String.valueOf(R.drawable.ic_arrow_forward)); - keyboardInfo.put("isEnabled", "true"); - associatedKeyboards.add(keyboardInfo); - } - } - return associatedKeyboards; - } - - return null; - } - /** * Get the index of a lexical model key in the list of installed lexical models. * @param context * @param lexicalModelKey - key of "{package ID}_{language ID}_{lexical model ID}" * @return Index >= 0 if the lexical model key exists. Otherwise -1 */ - protected static int getLexicalModelIndex(Context context, String lexicalModelKey) { + public static int getLexicalModelIndex(Context context, String lexicalModelKey) { int index = -1; if (lexicalModelsList == null) { @@ -828,28 +611,7 @@ public final class KeyboardPickerActivity extends AppCompatActivity { return index; } - protected static HashMap getKeyboardInfo(Context context, int index) { - if (index < 0) { - return null; - } - - if (keyboardsList == null) { - keyboardsList = getKeyboardsList(context); - } - - if (keyboardsList != null && index < keyboardsList.size()) { - HashMap kbInfo = keyboardsList.get(index); - String pkgID = kbInfo.get(KMManager.KMKey_PackageID); - if (pkgID == null || pkgID.isEmpty()) { - kbInfo.put(KMManager.KMKey_PackageID, KMManager.KMDefault_UndefinedPackageID); - } - return kbInfo; - } - - return null; - } - - protected static HashMap getLexicalModelInfo(Context context,int index) { + public static HashMap getLexicalModelInfo(Context context,int index) { if (index < 0) { return null; } @@ -872,16 +634,20 @@ public final class KeyboardPickerActivity extends AppCompatActivity { } public static void handleDownloadedKeyboard(Context context, HashMap keyboardInfo) { - String keyboardID = keyboardInfo.get(KMManager.KMKey_KeyboardID); - String languageID = keyboardInfo.get(KMManager.KMKey_LanguageID); - String kbKey = String.format("%s_%s", languageID, keyboardID); - int index = getKeyboardIndex(context, kbKey); - if (index == -1) { - // Add the downloaded keyboard if not found - addKeyboard(context, keyboardInfo); - index = getKeyboardIndex(context, kbKey); - } - keyboardsList.set(index, keyboardInfo); - saveList(context, KMManager.KMFilename_KeyboardsList); + boolean isNewKeyboard = true; + Keyboard k = new Keyboard( + keyboardInfo.get(KMManager.KMKey_PackageID), + keyboardInfo.get(KMManager.KMKey_KeyboardID), + keyboardInfo.get(KMManager.KMKey_KeyboardName), + keyboardInfo.get(KMManager.KMKey_LanguageID), + keyboardInfo.get(KMManager.KMKey_LanguageName), + keyboardInfo.get(KMManager.KMKey_KeyboardVersion), + keyboardInfo.get(KMManager.KMKey_HelpLink), + keyboardInfo.get(KMManager.KMKey_KMPLink), + isNewKeyboard, + keyboardInfo.get(KMManager.KMKey_Font), + keyboardInfo.get(KMManager.KMKey_OskFont)); + KeyboardController.getInstance().add(k); + KeyboardController.getInstance().save(context); } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardSettingsActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardSettingsActivity.java index 1a389176532a0f814b56c618aaa2afb9380ce06a..84076ff4504ffaa19a0be04abcb48eacdbfcf7f0 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardSettingsActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/KeyboardSettingsActivity.java @@ -11,6 +11,7 @@ import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.app.DialogFragment; +import android.app.DownloadManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; @@ -32,6 +33,10 @@ import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; +import com.tavultesoft.kmea.cloud.CloudApiTypes; +import com.tavultesoft.kmea.cloud.CloudDownloadMgr; +import com.tavultesoft.kmea.cloud.impl.CloudKeyboardPackageDownloadCallback; +import com.tavultesoft.kmea.cloud.impl.CloudLexicalPackageDownloadCallback; import com.tavultesoft.kmea.data.CloudRepository; import com.tavultesoft.kmea.data.Dataset; import com.tavultesoft.kmea.data.Keyboard; @@ -68,21 +73,17 @@ public final class KeyboardSettingsActivity extends AppCompatActivity { final ListView listView = findViewById(R.id.listView); - final Keyboard kbd = (Keyboard)getIntent().getSerializableExtra(KMManager.KMKey_Keyboard); + Bundle bundle = getIntent().getExtras(); + if (bundle == null) { + return; + } + final Keyboard kbd = (Keyboard)bundle.getSerializable(KMManager.KMKey_Keyboard); final String packageID = kbd.getPackageID(); final String languageID = kbd.getLanguageID(); final String languageName = kbd.getLanguageName(); - final String kbID = kbd.getResourceId(); - final String kbName = kbd.getResourceName(); + final String kbID = kbd.getKeyboardID(); + final String kbName = kbd.getKeyboardName(); final String kbVersion = kbd.getVersion(); - String latestKbdCloudVersion = kbVersion; - - // Determine if keyboard update is available from the cloud - Dataset dataset = CloudRepository.shared.fetchDataset(this); - final Keyboard latestKbd = dataset.keyboards.findMatch(kbd); - if (latestKbd != null) { - latestKbdCloudVersion = latestKbd.getVersion(); - } final TextView textView = findViewById(R.id.bar_title); textView.setText(kbName); @@ -96,8 +97,8 @@ public final class KeyboardSettingsActivity extends AppCompatActivity { HashMap hashMap = new HashMap<>(); hashMap.put(titleKey, getString(R.string.keyboard_version)); hashMap.put(subtitleKey, kbVersion); - // Display notification to download update if latestKbdCloudVersion > kbVersion (installed) - if (FileUtils.compareVersions(latestKbdCloudVersion, kbVersion) == FileUtils.VERSION_GREATER) { + // Display notification to download update if available + if (kbd.hasUpdateAvailable()) { hashMap.put(subtitleKey, context.getString(R.string.update_available, kbVersion)); icon = String.valueOf(R.drawable.ic_cloud_download); } @@ -106,7 +107,7 @@ public final class KeyboardSettingsActivity extends AppCompatActivity { // Display keyboard help link hashMap = new HashMap<>(); - final String customHelpLink = kbd.getCustomHelpLink(); + final String customHelpLink = kbd.getHelpLink(); // Check if app declared FileProvider icon = String.valueOf(R.drawable.ic_arrow_forward); // Don't show help link arrow if File Provider unavailable, or custom help doesn't exist @@ -119,9 +120,8 @@ public final class KeyboardSettingsActivity extends AppCompatActivity { hashMap.put(iconKey, icon); infoList.add(hashMap); - // Display uninstall keyboard - if (!packageID.equalsIgnoreCase(KMManager.KMDefault_PackageID) || - !kbID.equalsIgnoreCase(KMManager.KMDefault_KeyboardID)) { + // If not default keyboard, display uninstall keyboard + if (!kbID.equalsIgnoreCase(KMManager.KMDefault_KeyboardID)) { hashMap = new HashMap<>(); hashMap.put(titleKey, getString(R.string.uninstall_keyboard)); hashMap.put(subtitleKey, ""); @@ -159,10 +159,11 @@ public final class KeyboardSettingsActivity extends AppCompatActivity { // "Version" link clicked to download latest keyboard version from cloud if (itemTitle.equals(getString(R.string.keyboard_version))) { - Bundle args = latestKbd.buildDownloadBundle(); + Bundle args = kbd.buildDownloadBundle(); Intent i = new Intent(getApplicationContext(), KMKeyboardDownloaderActivity.class); i.putExtras(args); startActivity(i); + finish(); // "Help" link clicked } else if (itemTitle.equals(getString(R.string.help_link))) { @@ -198,7 +199,7 @@ public final class KeyboardSettingsActivity extends AppCompatActivity { LinearLayout qrLayout = (LinearLayout) view.findViewById(R.id.qrLayout); listView.addFooterView(qrLayout); - String url = String.format(QRCodeUtil.QR_BASE, kbID); + String url = String.format(QRCodeUtil.QR_CODE_URL_FORMATSTR, kbID); Bitmap myBitmap = QRCodeUtil.toBitmap(url); ImageView imageView = (ImageView) findViewById(R.id.qrCode); imageView.setImageBitmap(myBitmap); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguageListUtil.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguageListUtil.java deleted file mode 100644 index b1d75393559ad68547ef2b64552163b973ac4934..0000000000000000000000000000000000000000 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguageListUtil.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright (C) 2017 SIL International. All rights reserved. - */ - -package com.tavultesoft.kmea; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.json.JSONArray; -import org.json.JSONObject; -import com.tavultesoft.kmea.cloud.CloudDataJsonUtil; -import com.tavultesoft.kmea.util.MapCompat; - -import androidx.annotation.NonNull; -import android.content.Context; -import android.content.Intent; -import android.util.Log; - -/** - * "Add new keyboard" - * Gets the list of installable languages from Keyman cloud and allows user to download a keyboard. - * After downloading, the new keyboard is selected. - * - * The language list is saved to a cache file "jsonKeyboardsCache.dat". - */ -public final class LanguageListUtil { - - private Context context; - - private static final String TAG = "LanguageListUtility"; - - // These two JSON objects and their getters are still used by legacy metadata functions. - private static JSONArray languages = null; - - protected static JSONArray languages() { - return languages; - } - - private static JSONObject options = null; - - protected static JSONObject options() { - return options; - } - - // Also these. - private static HashMap> keyboardsInfo = null; - private static HashMap keyboardModifiedDates = null; - - // Still used by KMManager and/or KMKeyboard. - protected static HashMap> getKeyboardsInfo(Context context) { - if (keyboardsInfo != null) { - return keyboardsInfo; - } else { - try { - JSONObject jsonObj = CloudDataJsonUtil.getCachedJSONObject( - CloudDataJsonUtil.getKeyboardCacheFile(context)); - if (jsonObj == null) { - return null; - } - - languages = jsonObj.getJSONObject(KMKeyboardDownloaderActivity.KMKey_Languages).getJSONArray(KMKeyboardDownloaderActivity.KMKey_Languages); - options = jsonObj.getJSONObject(KMKeyboardDownloaderActivity.KMKey_Options); - keyboardsInfo = new HashMap>(); - keyboardModifiedDates = new HashMap(); - - int langLength = languages.length(); - for (int i = 0; i < langLength; i++) { - JSONObject language = languages.getJSONObject(i); - String kbKey = ""; - String pkgID = ""; - String kbID = ""; - String langID = language.getString(KMManager.KMKey_ID); - String kbName = ""; - String langName = language.getString(KMManager.KMKey_Name); - String kbVersion = "1.0"; - String isCustom = "N"; - String kbFont = ""; - JSONArray langKeyboards = language.getJSONArray(KMKeyboardDownloaderActivity.KMKey_LanguageKeyboards); - JSONObject keyboard = null; - - int kbLength = langKeyboards.length(); - if (kbLength == 1) { - keyboard = langKeyboards.getJSONObject(0); - pkgID = keyboard.optString(KMManager.KMKey_PackageID, KMManager.KMDefault_UndefinedPackageID); - kbID = keyboard.getString(KMManager.KMKey_ID); - kbName = keyboard.getString(KMManager.KMKey_Name); - kbVersion = keyboard.optString(KMManager.KMKey_KeyboardVersion, "1.0"); - kbFont = keyboard.optString(KMManager.KMKey_Font, ""); - - kbKey = String.format("%s_%s", langID, kbID); - HashMap hashMap = new HashMap(); - hashMap.put(KMManager.KMKey_PackageID, pkgID); - hashMap.put(KMManager.KMKey_KeyboardName, kbName); - hashMap.put(KMManager.KMKey_LanguageName, langName); - hashMap.put(KMManager.KMKey_KeyboardVersion, kbVersion); - hashMap.put(KMManager.KMKey_CustomKeyboard, isCustom); - hashMap.put(KMManager.KMKey_Font, kbFont); - keyboardsInfo.put(kbKey, hashMap); - - if (keyboardModifiedDates.get(kbID) == null) { - keyboardModifiedDates.put(kbID, keyboard.getString(KMManager.KMKey_KeyboardModified)); - } - } else { - for (int j = 0; j < kbLength; j++) { - keyboard = langKeyboards.getJSONObject(j); - pkgID = keyboard.optString(KMManager.KMKey_PackageID, KMManager.KMDefault_UndefinedPackageID); - kbID = keyboard.getString(KMManager.KMKey_ID); - kbName = keyboard.getString(KMManager.KMKey_Name); - kbVersion = keyboard.optString(KMManager.KMKey_KeyboardVersion, "1.0"); - kbFont = keyboard.optString(KMManager.KMKey_Font, ""); - - kbKey = String.format("%s_%s", langID, kbID); - HashMap hashMap = new HashMap(); - hashMap.put(KMManager.KMKey_PackageID, pkgID); - hashMap.put(KMManager.KMKey_KeyboardName, kbName); - hashMap.put(KMManager.KMKey_LanguageName, langName); - hashMap.put(KMManager.KMKey_KeyboardVersion, kbVersion); - hashMap.put(KMManager.KMKey_CustomKeyboard, isCustom); - hashMap.put(KMManager.KMKey_Font, kbFont); - keyboardsInfo.put(kbKey, hashMap); - - if (keyboardModifiedDates.get(kbID) == null) { - keyboardModifiedDates.put(kbID, keyboard.getString(KMManager.KMKey_KeyboardModified)); - } - } - } - } - - return keyboardsInfo; - } catch (Exception e) { - Log.e(TAG, "getKeyboardsInfo() error: " + e); - return null; - } - } - } -} \ No newline at end of file diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguageSettingsActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguageSettingsActivity.java index 4cfdc0733a6bf780cdb37a632806f176c8aea780..552d6069a0644796462247fd890b29c97339e985 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguageSettingsActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguageSettingsActivity.java @@ -8,7 +8,6 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; -import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -31,6 +30,7 @@ import com.tavultesoft.kmea.data.Dataset; import com.tavultesoft.kmea.data.Keyboard; import com.tavultesoft.kmea.data.adapters.NestedAdapter; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; import java.util.HashMap; @@ -90,7 +90,7 @@ public final class LanguageSettingsActivity extends AppCompatActivity { } // If the active keyboard is for this language, immediately enact the new pref setting. - String kbdLgCode = KMManager.getCurrentKeyboardInfo(context).get(KMManager.KMKey_LanguageID); + String kbdLgCode = KMManager.getCurrentKeyboardInfo(context).getLanguageID(); if (kbdLgCode.equals(lgCode)) { // Not only registers the model but also applies our modeling preferences. KMManager.registerAssociatedLexicalModel(lgCode); @@ -118,7 +118,7 @@ public final class LanguageSettingsActivity extends AppCompatActivity { Bundle bundle = getIntent().getExtras(); if (bundle == null) { // Should never actually happen. - Log.e(TAG, "Language data not specified for LanguageSettingsActivity!"); + KMLog.LogError(TAG, "Language data not specified for LanguageSettingsActivity!"); finish(); if(KMManager.isDebugMode()) { @@ -166,7 +166,7 @@ public final class LanguageSettingsActivity extends AppCompatActivity { layout = (RelativeLayout)findViewById(R.id.model_picker); textView = (TextView) layout.findViewById(R.id.text1); - textView.setText(getString(R.string.model)); + textView.setText(getString(R.string.model_label)); lexicalModelTextView = layout.findViewById(R.id.text2); @@ -209,7 +209,9 @@ public final class LanguageSettingsActivity extends AppCompatActivity { Keyboard kbdInfo = ((FilteredKeyboardsAdapter) listView.getAdapter()).getItem(position); Intent intent = new Intent(context, KeyboardSettingsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); - intent.putExtra(KMManager.KMKey_Keyboard, kbdInfo); + Bundle bundle = new Bundle(); + bundle.putSerializable(KMManager.KMKey_Keyboard, kbdInfo); + intent.putExtras(bundle); startActivity(intent); } }); @@ -235,7 +237,7 @@ public final class LanguageSettingsActivity extends AppCompatActivity { } else { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); dialogBuilder.setTitle(getString(R.string.title_add_keyboard)); - dialogBuilder.setMessage(String.format("\n%s\n", getString(R.string.cannot_connect))); + dialogBuilder.setMessage(getString(R.string.cannot_connect)); dialogBuilder.setPositiveButton(getString(R.string.label_ok), null); AlertDialog dialog = dialogBuilder.create(); dialog.show(); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguagesSettingsActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguagesSettingsActivity.java index bae8e89390d8ee7209e34e1d7100eae08ab6aed6..99e838a2eaad46c4812d593d27e8ab521ee17411 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguagesSettingsActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/LanguagesSettingsActivity.java @@ -124,7 +124,7 @@ public final class LanguagesSettingsActivity extends AppCompatActivity { } else { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); dialogBuilder.setTitle(getString(R.string.title_add_keyboard)); - dialogBuilder.setMessage(String.format("\n%s\n", getString(R.string.cannot_connect))); + dialogBuilder.setMessage(getString(R.string.cannot_connect)); dialogBuilder.setPositiveButton(getString(R.string.label_ok), null); AlertDialog dialog = dialogBuilder.create(); dialog.show(); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelInfoActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelInfoActivity.java index 40c3d2e60805cf7832e8ac058ab897f7b53772b9..7213a2cd685425ee56d1349cf7a3edae36f65c74 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelInfoActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelInfoActivity.java @@ -61,26 +61,12 @@ public final class ModelInfoActivity extends AppCompatActivity { final ListView listView = findViewById(R.id.listView); - final String packageID = getIntent().getStringExtra(KMManager.KMKey_PackageID); - final String languageID = getIntent().getStringExtra(KMManager.KMKey_LanguageID); - final String modelID = getIntent().getStringExtra(KMManager.KMKey_LexicalModelID); - final String modelName = getIntent().getStringExtra(KMManager.KMKey_LexicalModelName); - final String modelVersion = getIntent().getStringExtra(KMManager.KMKey_LexicalModelVersion); - String latestModelCloudVersion = modelVersion; - - // Determine if model update is available from the cloud - Dataset dataset = CloudRepository.shared.fetchDataset(this); - HashMap modelInfo = new HashMap<>(); - modelInfo.put(KMManager.KMKey_PackageID, packageID); - modelInfo.put(KMManager.KMKey_LanguageID, languageID); - modelInfo.put(KMManager.KMKey_LexicalModelID, modelID); - modelInfo.put(KMManager.KMKey_LexicalModelName, modelName); - - LexicalModel modelQuery = new LexicalModel(modelInfo); - final LexicalModel latestModel = dataset.lexicalModels.findMatch(modelQuery); - if (latestModel != null) { - latestModelCloudVersion = latestModel.getVersion(); - } + final LexicalModel lm = (LexicalModel)getIntent().getSerializableExtra(KMManager.KMKey_LexicalModel); + final String packageID = lm.getPackageID(); + final String languageID = lm.getLanguageID(); + final String modelID = lm.getLexicalModelID(); + final String modelName = lm.getLexicalModelName(); + final String modelVersion = lm.getVersion(); final TextView textView = findViewById(R.id.bar_title); textView.setText(String.format(getString(R.string.model_info_header), modelName)); @@ -92,8 +78,8 @@ public final class ModelInfoActivity extends AppCompatActivity { HashMap hashMap = new HashMap<>(); hashMap.put(titleKey, getString(R.string.model_version)); hashMap.put(subtitleKey, modelVersion); - // Display notification to download update if latestModelCloudVersion > modelVersion (installed) - if (FileUtils.compareVersions(latestModelCloudVersion, modelVersion) == FileUtils.VERSION_GREATER) { + // Display notification to download update if available + if (lm.hasUpdateAvailable()) { hashMap.put(subtitleKey, context.getString(R.string.update_available, modelVersion)); icon = String.valueOf(R.drawable.ic_cloud_download); } @@ -102,7 +88,7 @@ public final class ModelInfoActivity extends AppCompatActivity { // Display model help link hashMap = new HashMap<>(); - final String customHelpLink = getIntent().getStringExtra(KMManager.KMKey_CustomHelpLink); + final String customHelpLink = lm.getHelpLink(); // Check if app declared FileProvider // Currently, model help only available if custom link exists icon = String.valueOf(R.drawable.ic_arrow_forward); @@ -154,10 +140,11 @@ public final class ModelInfoActivity extends AppCompatActivity { // "Version" link clicked to download latest model version from cloud if (itemTitle.equals(getString(R.string.model_version))) { - Bundle args = latestModel.buildDownloadBundle(); + Bundle args = lm.buildDownloadBundle(); Intent i = new Intent(getApplicationContext(), KMKeyboardDownloaderActivity.class); i.putExtras(args); startActivity(i); + finish(); // "Help" link clicked } else if (itemTitle.equals(getString(R.string.help_link))) { diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelPickerActivity.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelPickerActivity.java index b0fbe254217dfaec135861b476a56db24646f0cd..4ab7b77a8cd0aecbc99b9443abc51e434f0e9718 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelPickerActivity.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelPickerActivity.java @@ -4,7 +4,6 @@ package com.tavultesoft.kmea; import android.content.Context; import android.content.Intent; import android.os.Bundle; -import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -23,6 +22,7 @@ import com.tavultesoft.kmea.data.CloudRepository; import com.tavultesoft.kmea.data.Dataset; import com.tavultesoft.kmea.data.LexicalModel; import com.tavultesoft.kmea.data.adapters.NestedAdapter; +import com.tavultesoft.kmea.util.BCP47; import com.tavultesoft.kmea.util.MapCompat; import java.io.File; @@ -84,57 +84,49 @@ public final class ModelPickerActivity extends AppCompatActivity { didExecuteParser = true; repo = CloudRepository.shared.fetchDataset(context); - // Initialize the dataset of installed lexical models - listView.setAdapter(new FilteredLexicalModelAdapter(context, KeyboardPickerActivity.getInstalledDataset(context), languageID)); + // Initialize the dataset of available lexical models (installed and from the cloud catalog) + listView.setAdapter(new FilteredLexicalModelAdapter(context, repo, languageID)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, long id) { int selectedIndex = position; LexicalModel model = ((FilteredLexicalModelAdapter) listView.getAdapter()).getItem(position); - Map modelInfo = model.map; - String packageID = modelInfo.get(KMManager.KMKey_PackageID); - String languageID = modelInfo.get(KMManager.KMKey_LanguageID); - String modelID = modelInfo.get(KMManager.KMKey_LexicalModelID); - String modelName = modelInfo.get(KMManager.KMKey_LexicalModelName); - String langName = modelInfo.get(KMManager.KMKey_LanguageName); - - // File check to see if lexical model already exists locally - File modelCheck = new File(KMManager.getLexicalModelsDir() + packageID + File.separator + modelID + ".model.js"); + String packageID = model.getPackageID(); + String languageID = model.getLanguageID(); + String modelID = model.getLexicalModelID(); + String modelName = model.getLexicalModelName(); + String langName = model.getLanguageName(); + String version = model.getVersion(); - String modelKey = String.format("%s_%s_%s", packageID, languageID, modelID); - boolean modelInstalled = KeyboardPickerActivity.containsLexicalModel(context, modelKey); boolean immediateRegister = false; - Map preInstalledModelMap = KMManager.getAssociatedLexicalModel(languageID); + // File check to see if lexical model file already exists locally (may not be currently installed) + File modelCheck = new File(KMManager.getLexicalModelsDir() + packageID + File.separator + modelID + ".model.js"); + String modelKey = model.getKey(); + boolean modelInstalled = KeyboardPickerActivity.containsLexicalModel(context, modelKey); if (modelInstalled) { // Show Model Info listView.setItemChecked(position, true); listView.setSelection(position); // Start intent for selected Predictive Text Model screen - if (!languageID.equalsIgnoreCase(modelInfo.get(KMManager.KMKey_LanguageID))) { - Log.d(TAG, "Language ID " + languageID + " doesn't match model language ID: " + - modelInfo.get(KMManager.KMKey_LanguageID)); - } - Bundle bundle = new Bundle(); - // Note: package ID of a model is different from package ID for a keyboard. - // Language ID can be re-used - bundle.putString(KMManager.KMKey_PackageID, packageID); - bundle.putString(KMManager.KMKey_LanguageID, languageID); - bundle.putString(KMManager.KMKey_LexicalModelID, modelID); - bundle.putString(KMManager.KMKey_LexicalModelName, modelName); - bundle.putString(KMManager.KMKey_LexicalModelVersion, - modelInfo.get(KMManager.KMKey_LexicalModelVersion)); - bundle.putString(KMManager.KMKey_CustomHelpLink, customHelpLink); Intent i = new Intent(context, ModelInfoActivity.class); - i.putExtras(bundle); + i.putExtra(KMManager.KMKey_LexicalModel, model); startActivityForResult(i, 1); } else if (modelCheck.exists()) { // Handle scenario where previously installed kmp already exists so // we only need to add the model to the list of installed models + HashMap modelInfo = new HashMap(); + modelInfo.put(KMManager.KMKey_PackageID, packageID); + modelInfo.put(KMManager.KMKey_LexicalModelID, modelID); + modelInfo.put(KMManager.KMKey_LanguageID, languageID); + modelInfo.put(KMManager.KMKey_LexicalModelName, modelName); + modelInfo.put(KMManager.KMKey_LanguageName, langName); + modelInfo.put(KMManager.KMKey_LexicalModelVersion, version); // Add help link modelInfo.put(KMManager.KMKey_CustomHelpLink, ""); + boolean result = KMManager.addLexicalModel(context, new HashMap<>(modelInfo)); if (result) { Toast.makeText(context, getString(R.string.model_install_toast), Toast.LENGTH_SHORT).show(); @@ -154,10 +146,19 @@ public final class ModelPickerActivity extends AppCompatActivity { if(!modelInstalled) { // While awkward, we must obtain the preInstalledModelMap before any installations occur. // We don't want to remove the model we just installed, after all! + HashMap preInstalledModelMap = KMManager.getAssociatedLexicalModel(languageID); if(preInstalledModelMap != null) { - LexicalModel preInstalled = new LexicalModel(preInstalledModelMap); - String itemKey = String.format("%s_%s_%s", - preInstalled.map.get(KMManager.KMKey_PackageID), preInstalled.getLanguageCode(), preInstalled.getResourceId()); + // This might be unncessary + LexicalModel preInstalled = new LexicalModel( + preInstalledModelMap.get(KMManager.KMKey_PackageID), + preInstalledModelMap.get(KMManager.KMKey_LexicalModelID), + preInstalledModelMap.get(KMManager.KMKey_LexicalModelName), + preInstalledModelMap.get(KMManager.KMKey_LanguageID), + preInstalledModelMap.get(KMManager.KMKey_LanguageName), + preInstalledModelMap.get(KMManager.KMKey_LexicalModelVersion), + preInstalledModelMap.get(KMManager.KMKey_HelpLink), + MapCompat.getOrDefault(preInstalledModelMap, KMManager.KMKey_KMPLink, "")); + String itemKey = preInstalled.getKey(); int modelIndex = KeyboardPickerActivity.getLexicalModelIndex(context, itemKey); KeyboardPickerActivity.deleteLexicalModel(context, modelIndex, true); } @@ -166,8 +167,8 @@ public final class ModelPickerActivity extends AppCompatActivity { if(immediateRegister) { // Register associated lexical model if it matches the active keyboard's language code; // it's safe since we're on the same thread. Needs to be called AFTER deinstalling the old one. - String kbdLgCode = KMManager.getCurrentKeyboardInfo(context).get(KMManager.KMKey_LanguageID); - if(kbdLgCode.equals(languageID)) { + String kbdLgCode = KMManager.getCurrentKeyboardInfo(context).getLanguageID(); + if(BCP47.languageEquals(kbdLgCode, languageID)) { KMManager.registerAssociatedLexicalModel(languageID); } } @@ -241,24 +242,20 @@ public final class ModelPickerActivity extends AppCompatActivity { } // Needed for the check below. - String packageID = model.map.get(KMManager.KMKey_PackageID); - String languageID = model.map.get(KMManager.KMKey_LanguageID); - String modelID = model.map.get(KMManager.KMKey_LexicalModelID); - String modelKey = String.format("%s_%s_%s", packageID, languageID, modelID); + String modelKey = model.getKey(); // TODO: Refactor this check - we should instead test against the installed models listing // once it has its own backing Dataset instance. // Is this an installed model or not? + holder.imgDetails.setImageResource(R.drawable.ic_arrow_forward); if (KeyboardPickerActivity.containsLexicalModel(context, modelKey)) { holder.imgInstalled.setImageResource(R.drawable.ic_check); - holder.imgDetails.setImageResource(R.drawable.ic_arrow_forward); } else { holder.imgInstalled.setImageResource(0); - holder.imgDetails.setImageResource(0); } - holder.text.setText(model.map.get(KMManager.KMKey_LexicalModelName)); + holder.text.setText(model.getLexicalModelName()); return convertView; } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudApiTypes.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudApiTypes.java index 4f55ba367b7d9280bc584b08a846296e7d87f9b4..b1023474be4eb458674634862e93fb0e39d2b2db 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudApiTypes.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudApiTypes.java @@ -44,6 +44,11 @@ public class CloudApiTypes { * Catalog download: available lexical models including meta data. */ LexicalModels, + /** + * Catalog download: available keyboard and lexical model packages and the most current version. + * Used to determine if keyboard/lexical model updates are available + */ + PackageVersion, /** * Keyboard download: keyboard meta data for the selected keyboard. */ @@ -56,12 +61,17 @@ public class CloudApiTypes { * Keyboard download: download keyboard data package and fonts. */ KeyboardData, + /** + * Keyboard package download: download keyboard package + * Used for single keyboard download + */ + KeyboardPackage, /** * Lexical download: download lexical model package * Used for single lexical model download and * automatic lexical model download during keyboard download */ - LexicalModelPackage, + LexicalModelPackage } public enum JSONType { diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudDataJsonUtil.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudDataJsonUtil.java index f5c1449127d8287db8a6687470559be4e2c025e6..77721b91bd86f606e4718a9cf96ee6072268c553 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudDataJsonUtil.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudDataJsonUtil.java @@ -2,41 +2,62 @@ package com.tavultesoft.kmea.cloud; import android.content.Context; import android.os.Build; -import android.util.Log; +import android.os.Bundle; import com.tavultesoft.kmea.JSONParser; import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.KeyboardPickerActivity; import com.tavultesoft.kmea.R; import com.tavultesoft.kmea.cloud.CloudApiTypes; import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.KeyboardController; import com.tavultesoft.kmea.data.LexicalModel; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; +import com.tavultesoft.kmea.util.MapCompat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; +import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; import java.util.List; public class CloudDataJsonUtil { private static final String TAG = "CloudDataJsonUtil"; + + // Deprecated + public static final String JSON_Keyboards_Cache_Filename = "jsonKeyboardsCache.dat"; + + public static final String JSON_Lexical_Models_Cache_Filename = "jsonLexicalModelsCache.dat"; + public static final String JSON_Resources_Cache_Filename = "jsonResourcesCache.json"; + + // keys for api.keyman.com/package-version + private static final String CDKey_Keyboards = "keyboards"; + private static final String CDKey_Models = "models"; + private static final String CDKey_KMP = "kmp"; + private static final String CDKey_Version = "version"; + private static final String CDKey_Error = "error"; + private CloudDataJsonUtil() { //no instances } public static HashMap createKeyboardInfoMap(String aPackageId,String aLanguageId, String aLanguageName, String aKeyboardId, - String aKeyboardName, String aKeyboardVersion, String anIsCustomKeyboard, + String aKeyboardName, String aKeyboardVersion, String aFont, String aOskFont, String aCustomHelpLink) { HashMap keyboardInfo = new HashMap(); @@ -46,7 +67,6 @@ public class CloudDataJsonUtil { keyboardInfo.put(KMManager.KMKey_KeyboardName, aKeyboardName); keyboardInfo.put(KMManager.KMKey_LanguageName, aLanguageName); keyboardInfo.put(KMManager.KMKey_KeyboardVersion, aKeyboardVersion); - keyboardInfo.put(KMManager.KMKey_CustomKeyboard, anIsCustomKeyboard); keyboardInfo.put(KMManager.KMKey_Font, aFont); if (aOskFont != null) { keyboardInfo.put(KMManager.KMKey_OskFont, aOskFont); @@ -65,7 +85,7 @@ public class CloudDataJsonUtil { } try { - // Thank you, Cloud API format. + // Thank you, Cloud API format JSONArray languages = query.getJSONObject(KMKeyboardDownloaderActivity.KMKey_Languages).getJSONArray(KMKeyboardDownloaderActivity.KMKey_Languages); for (int i = 0; i < languages.length(); i++) { JSONObject languageJSON = languages.getJSONObject(i); @@ -79,79 +99,137 @@ public class CloudDataJsonUtil { } } } catch (JSONException | NullPointerException e) { - Log.e(TAG, "JSONParse Error: " + e); - return new ArrayList<>(); // Is this ideal? + KMLog.LogException(TAG, "JSONParse Error: ", e); + return new ArrayList(); // Is this ideal? } return keyboardsList; } - public static List processLexicalModelJSON(JSONArray models) { + /** + * Parse a JSONArray of models to create a list of LexicalModel + * @param models + * @param fromKMP - boolean. If true, only the first language in an array is processed + * @return List of LexicalModel + */ + public static List processLexicalModelJSON(JSONArray models, boolean fromKMP) { List modelList = new ArrayList<>(models.length()); try { // Parse each model JSON Object. int modelsLength = models.length(); for (int i = 0; i < modelsLength; i++) { - JSONObject model = models.getJSONObject(i); - String packageID = "", modelURL = ""; - if (model.has(KMManager.KMKey_PackageID)) { - packageID = model.getString(KMManager.KMKey_PackageID); - } else { - // Determine package ID from packageFilename - modelURL = model.optString("packageFilename", ""); - packageID = FileUtils.getFilename(modelURL); - packageID = packageID.replace(FileUtils.MODELPACKAGE, ""); - } - - // api.keyman.com query returns an array of language IDs Strings while - // kmp.json "languages" is an array of JSONObject - String languageID = "", langName = ""; - Object obj = model.getJSONArray("languages"); - if (((JSONArray) obj).get(0) instanceof String) { - // language name not provided, so re-use language ID - languageID = model.getJSONArray("languages").getString(0); - langName = languageID; - } else if (((JSONArray) obj).get(0) instanceof JSONObject) { - JSONObject languageObj = model.getJSONArray("languages").getJSONObject(0); - languageID = languageObj.getString("id"); - langName = languageObj.getString("name"); - } - - String modelID = model.getString(KMManager.KMKey_ID); - String modelName = model.getString(KMManager.KMKey_Name); - - // Cloud data may not contain lexical model version, so fallback to (package) version - String version = model.optString(KMManager.KMKey_Version, "1.0"); - String modelVersion = model.optString(KMManager.KMKey_LexicalModelVersion, version); - - String isCustom = model.optString(KMManager.KMKey_CustomModel, "N"); - - String icon = "0"; - - HashMap hashMap = new HashMap(); - hashMap.put(KMManager.KMKey_PackageID, packageID); - hashMap.put(KMManager.KMKey_LanguageID, languageID.toLowerCase()); - hashMap.put(KMManager.KMKey_LexicalModelID, modelID); - hashMap.put(KMManager.KMKey_LexicalModelName, modelName); - hashMap.put(KMManager.KMKey_LanguageName, langName); - hashMap.put(KMManager.KMKey_LexicalModelVersion, modelVersion); - hashMap.put(KMManager.KMKey_CustomModel, isCustom); - hashMap.put(KMManager.KMKey_LexicalModelPackageFilename, modelURL); - hashMap.put("isEnabled", "true"); - hashMap.put(KMManager.KMKey_Icon, String.valueOf(R.drawable.ic_arrow_forward)); - - modelList.add(new LexicalModel(hashMap)); + JSONObject modelJSON = models.getJSONObject(i); + modelList.addAll(LexicalModel.LexicalModelList(modelJSON, fromKMP)); } } catch (JSONException | NullPointerException e) { - Log.e(TAG, "JSONParse Error: " + e); - return new ArrayList<>(); // Is this ideal? + KMLog.LogException(TAG, "JSONParse Error: ", e); + return new ArrayList(); // Is this ideal? } return modelList; } - public static JSONArray getCachedJSONArray(File file) { + /** + * Process the "keyboards" JSON Object to determine keyboard updates + * @param aContext Context + * @param pkgData JSONObject from the package-version API + * @param updateBundles - List of keyboard bundle updates + */ + public static void processKeyboardPackageUpdateJSON(Context aContext, JSONObject pkgData, List updateBundles) { + boolean saveKeyboardList = false; + // Parse for the keyboard package updates + if (pkgData.has(CDKey_Keyboards)) { + try { + JSONObject cloudKeyboardPackages = pkgData.getJSONObject(CDKey_Keyboards); + Iterator keyboardIDs = cloudKeyboardPackages.keys(); + while (keyboardIDs.hasNext()) { + String keyboardID = keyboardIDs.next(); + JSONObject cloudKeyboardObj = cloudKeyboardPackages.getJSONObject(keyboardID); + if (!cloudKeyboardObj.has(CDKey_Error)) { + String cloudVersion = cloudKeyboardObj.getString(CDKey_Version); + String cloudKMP = cloudKeyboardObj.getString(CDKey_KMP); + // Valid keyboard package exists. See if keyboard list needs to be updated + for (int i = 0; i < KeyboardController.getInstance().get().size(); i++) { + Keyboard kbd = KeyboardController.getInstance().getKeyboardInfo(i); + String version = kbd.getVersion(); + if (keyboardID.equalsIgnoreCase(kbd.getKeyboardID()) && + (FileUtils.compareVersions(cloudVersion, version) == FileUtils.VERSION_GREATER) && + (!kbd.getUpdateKMP().equalsIgnoreCase(cloudKMP))) { + // Update keyboard with the latest KMP link + kbd.setUpdateKMP(cloudKMP); + KeyboardController.getInstance().add(kbd); + + // Update bundle list + Bundle bundle = new Bundle(kbd.buildDownloadBundle()); + updateBundles.add(bundle); + + saveKeyboardList = true; + } + } + } + } + } catch (JSONException | NullPointerException e) { + KMLog.LogException(TAG, "processPackageUpdateJSON Error process keyboards: ", e); + } + } + + if (saveKeyboardList) { + KeyboardController.getInstance().save(aContext); + } + } + + public static void processLexicalModelPackageUpdateJSON(Context aContext, JSONObject pkgData, List updateBundles) { + boolean saveModelsList = false; + // Parse for lexical model package updates + if (pkgData.has(CDKey_Models)) { + try { + JSONObject cloudModelPackages = pkgData.getJSONObject(CDKey_Models); + Iterator lexicalModelIDs = cloudModelPackages.keys(); + while (lexicalModelIDs.hasNext()) { + String lexicalModelID = lexicalModelIDs.next(); + JSONObject cloudModelObj = cloudModelPackages.getJSONObject(lexicalModelID); + if (!cloudModelObj.has(CDKey_Error)) { + String cloudVersion = cloudModelObj.getString(CDKey_Version); + String cloudKMP = cloudModelObj.getString(CDKey_KMP); + // Valid lexical model package exists. See if lexical model list needs to be updated + // Valid keyboard package exists. See if keyboard list needs to be updated + int index = KeyboardPickerActivity.getLexicalModelIndex(aContext, lexicalModelID); + if (index != -1) { + HashMap lmInfo = KeyboardPickerActivity.getLexicalModelInfo(aContext, index); + String version = lmInfo.get(KMManager.KMKey_Version); + if (lexicalModelID.equalsIgnoreCase(lmInfo.get(KMManager.KMKey_LexicalModelID)) && + (FileUtils.compareVersions(cloudVersion, version) == FileUtils.VERSION_GREATER) && + (!MapCompat.getOrDefault(lmInfo, KMManager.KMKey_KMPLink, "").equalsIgnoreCase(cloudKMP))) { + // Update keyboard with the latest KMP link + lmInfo.put(KMManager.KMKey_KMPLink, cloudKMP); + KeyboardPickerActivity.addLexicalModel(aContext, lmInfo); + + // Update bundle list + LexicalModel lm = new LexicalModel( + lmInfo.get(KMManager.KMKey_PackageID), + lmInfo.get(KMManager.KMKey_LexicalModelID), + lmInfo.get(KMManager.KMKey_LexicalModelName), + lmInfo.get(KMManager.KMKey_LanguageID), + lmInfo.get(KMManager.KMKey_LanguageName), + lmInfo.get(KMManager.KMKey_Version), + lmInfo.get(KMManager.KMKey_CustomHelpLink), + lmInfo.get(KMManager.KMKey_KMPLink)); + Bundle bundle = new Bundle(lm.buildDownloadBundle()); + updateBundles.add(bundle); + + saveModelsList = true; + } + } + } + } + } catch (JSONException | NullPointerException e) { + KMLog.LogException(TAG, "processPackageUpdateJSON Error processing models: ", e); + } + } + } + + public static JSONArray getCachedJSONArray(File file) { JSONArray lmData = null; try { // Read from cache file @@ -161,7 +239,7 @@ public class CloudDataJsonUtil { objInput.close(); } } catch (Exception e) { - Log.e(TAG, "Failed to read from cache file. Error: " + e); + KMLog.LogException(TAG, "getCachedJSONArray failed to read from cache file. Error: ", e); lmData = null; } @@ -173,12 +251,17 @@ public class CloudDataJsonUtil { try { // Read from cache file if (file.exists()) { - ObjectInputStream objInput = new ObjectInputStream(new FileInputStream(file)); - kbData = new JSONObject(objInput.readObject().toString()); + StringBuilder sb = new StringBuilder(0); + String line; + BufferedReader objInput = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); + while ((line = objInput.readLine()) != null) { + sb.append(line); + } + kbData = new JSONObject(sb.toString()); objInput.close(); } } catch (Exception e) { - Log.e(TAG, "Failed to read from cache file. Error: " + e); + KMLog.LogException(TAG, "getCachedJSONObject failed to read from cache file. Error: ", e); kbData = null; } @@ -199,38 +282,26 @@ public class CloudDataJsonUtil { objOutput.writeObject(json.toString()); objOutput.close(); } catch (Exception e) { - Log.e(TAG, "Failed to save to cache file. Error: " + e); - } - } - - /** - * Save the JSON catalog data that's available from the cloud. - * The catalog is saved to a unique file. Separate files should - * be used for each API call, such as for keyboards vs lexical models. - * @param json - JSON object containing API return info - */ - public static void saveJSONObjectToCache(File file, JSONObject json) { - ObjectOutput objOutput; - try { - // Save to cache file - objOutput = new ObjectOutputStream(new FileOutputStream(file)); - objOutput.writeObject(json.toString()); - objOutput.close(); - } catch (Exception e) { - Log.e(TAG, "Failed to save to cache file. Error: " + e); + KMLog.LogException(TAG, "Failed to save to cache file. Error: ", e); } } + // Deprecated public static File getKeyboardCacheFile(Context context) { - final String jsonCacheFilename = "jsonKeyboardsCache.dat"; + final String jsonCacheFilename = JSON_Keyboards_Cache_Filename; return new File(context.getCacheDir(), jsonCacheFilename); } public static File getLexicalModelCacheFile(Context context) { - final String jsonLexicalCacheFilename = "jsonLexicalModelsCache.dat"; + final String jsonLexicalCacheFilename = JSON_Lexical_Models_Cache_Filename; return new File(context.getCacheDir(), jsonLexicalCacheFilename); } + public static File getResourcesCacheFile(Context context) { + final String jsonCacheFilename = JSON_Resources_Cache_Filename; + return new File(context.getCacheDir(), jsonCacheFilename); + } + /** * retrieve a json object from a downloaded file. * @param aDownload the download @@ -251,7 +322,7 @@ public class CloudDataJsonUtil { dataObject = jsonParser.getJSONObjectFromFile(aDownload.getDestinationFile(),JSONObject.class); } } catch (Exception e) { - Log.d(TAG, e.getMessage(),e); + KMLog.LogException(TAG, "", e); } finally { aDownload.getDestinationFile().delete(); } @@ -299,7 +370,7 @@ public class CloudDataJsonUtil { } } } catch (JSONException e) { - Log.e(TAG, "findTTF exception" + e); + KMLog.LogException(TAG, "findTTF exception", e); } } @@ -314,7 +385,7 @@ public class CloudDataJsonUtil { } return false; } catch (JSONException e) { - Log.e(TAG, "hasTTFFont exception" + e); + KMLog.LogException(TAG, "hasTTFFont exception", e); return false; } } @@ -354,6 +425,7 @@ public class CloudDataJsonUtil { urls.add(baseUri + fontFilename); } } catch (JSONException e) { + KMLog.LogException(TAG, "", e); return null; } } @@ -368,6 +440,7 @@ public class CloudDataJsonUtil { urls.add(baseUri + fontFilename); } } catch (JSONException e) { + KMLog.LogException(TAG, "", e); return null; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudDownloadMgr.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudDownloadMgr.java index 666e7cad53e23da10b816a66d8a82711d01876d9..0b6fd31a4663c232db42ee1bc19f484d00760235 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudDownloadMgr.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/CloudDownloadMgr.java @@ -8,6 +8,8 @@ import android.content.IntentFilter; import android.net.Uri; import android.util.Log; +import com.tavultesoft.kmea.util.KMLog; + import java.io.File; import java.util.HashMap; import java.util.List; @@ -60,7 +62,7 @@ public class CloudDownloadMgr{ aContext.registerReceiver(completeListener, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); } catch (IllegalStateException e) { String message = "initialize error: "; - Log.e(TAG, message + e); + KMLog.LogException(TAG, message, e); } isInitialized = true; } @@ -77,7 +79,7 @@ public class CloudDownloadMgr{ aContext.unregisterReceiver(completeListener); } catch (IllegalStateException e) { String message = "shutdown error: "; - Log.e(TAG, message + e); + KMLog.LogException(TAG, message, e); } isInitialized = false; } @@ -138,7 +140,7 @@ public class CloudDownloadMgr{ CloudApiTypes.CloudDownloadSet _parentSet = getDownloadSetForInternalDownloadId(anInternalDownloadId); if(_parentSet==null) { - Log.e(TAG, "Download with ID " + anInternalDownloadId + " is not available"); + KMLog.LogError(TAG, "Download with ID " + anInternalDownloadId + " is not available"); return; } _parentSet.setDone(anInternalDownloadId); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudCatalogDownloadCallback.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudCatalogDownloadCallback.java index 268b78da369541c2ee87d52f24179c138d6a1707..3315ab3fed448447bd266f7bc028d0cb90fa3b01 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudCatalogDownloadCallback.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudCatalogDownloadCallback.java @@ -13,6 +13,7 @@ import com.tavultesoft.kmea.cloud.ICloudDownloadCallback; import com.tavultesoft.kmea.data.CloudRepository; import com.tavultesoft.kmea.data.Dataset; import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.KeyboardController; import com.tavultesoft.kmea.data.LanguageResource; import com.tavultesoft.kmea.data.LexicalModel; import com.tavultesoft.kmea.util.FileUtils; @@ -101,12 +102,12 @@ public class CloudCatalogDownloadCallback implements ICloudDownloadCallback keyboardsArrayList = CloudDataJsonUtil.processKeyboardJSON(jsonTuple.keyboardJSON, false); - List lexicalModelsArrayList = CloudDataJsonUtil.processLexicalModelJSON(jsonTuple.lexicalModelJSON); + final boolean fromKMP = false; + List lexicalModelsArrayList = CloudDataJsonUtil.processLexicalModelJSON(jsonTuple.lexicalModelJSON, fromKMP); Dataset installedData = KeyboardPickerActivity.getInstalledDataset(context); final List updateBundles = new ArrayList<>(); @@ -153,76 +155,38 @@ public class CloudCatalogDownloadCallback implements ICloudDownloadCallback=0; i--) { + LexicalModel model = lexicalModelsArrayList.get(i); // cloud catalog + LexicalModel match = aDataSet.lexicalModels.findMatch(model); // installed model + // Check for model update information before removing duplicate if (match != null) { - Bundle bundle = updateCheck(match, keyboard); + Bundle bundle = updateCheck(model, match); if (bundle != null) { + String kmp = model.getUpdateKMP(); + if (kmp != null && !kmp.isEmpty()) { + match.setUpdateKMP(kmp); + } updateBundles.add(bundle); } - } // else no match == no special handling. - } - - // Filter out any duplicates from already-installed models, properly merging the lists. - for (int i = 0; i < lexicalModelsArrayList.size(); i++) { - LexicalModel model = lexicalModelsArrayList.get(i); - // Check for duplicates / possible updates. - LexicalModel match = aDataSet.lexicalModels.findMatch(model); - - if (match != null) { - if (compareVersions(model, match) == FileUtils.VERSION_GREATER) { - aDataSet.lexicalModels.remove(match); - } else { - lexicalModelsArrayList.remove(model); - i--; // Decrement our index to reflect the removal. - } + lexicalModelsArrayList.remove(model); } // else no match == no special handling. } // Add the cloud-returned lexical model info to the CloudRepository's lexical models adapter. aDataSet.lexicalModels.addAll(lexicalModelsArrayList); - // Do the actual update checks. - for (int i = 0; i < installedData.lexicalModels.getCount(); i++) { - LexicalModel model = installedData.lexicalModels.getItem(i); - - // Check for duplicates / possible updates. - LexicalModel match = aDataSet.lexicalModels.findMatch(model); - - if (match != null) { - Bundle bundle = updateCheck(match, model); - if (bundle != null) { - updateBundles.add(bundle); - } - } // else no match == no special handling. - } - if (updateBundles.size() > 0 && !(DEBUG_SIMULATE_UPDATES && !executeCallbacks)) { // Time for updates! Log.v(TAG, "Performing keyboard and model updates for " + updateBundles.size() + " resources."); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudCatalogDownloadReturns.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudCatalogDownloadReturns.java index 373e66d8d7bf8449bdc7a0ac6dfd3dfed538d1c8..c563ee817ee0171719a958ff5b8369cbcda28699 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudCatalogDownloadReturns.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudCatalogDownloadReturns.java @@ -11,13 +11,15 @@ import java.util.List; * Result type for catalogue download. */ public class CloudCatalogDownloadReturns { - public JSONObject keyboardJSON; + public JSONObject keyboardJSON; // TODO: remove public JSONArray lexicalModelJSON; + public JSONObject packagesJSON; // Used by the CloudCatalogDownloadTask, as it fits well with doInBackground's param structure. public CloudCatalogDownloadReturns(List returns) { JSONObject kbd = null; JSONArray lex = null; + JSONObject pkg = null; //TODO: Seems to be wrong because only the last result for each type will be processed for(CloudApiTypes.CloudApiReturns ret: returns) { @@ -27,23 +29,30 @@ public class CloudCatalogDownloadReturns { break; case LexicalModels: lex = ret.jsonArray; + break; + case PackageVersion: + pkg = ret.jsonObject; + break; } } // Errors are thrown if we try to do this assignment within the loop. this.keyboardJSON = kbd; this.lexicalModelJSON = lex; + this.packagesJSON = pkg; } - public CloudCatalogDownloadReturns(JSONObject keyboardJSON, JSONArray lexicalModelJSON) { + public CloudCatalogDownloadReturns(JSONObject keyboardJSON, JSONArray lexicalModelJSON, JSONObject packagesJSON) { this.keyboardJSON = keyboardJSON; this.lexicalModelJSON = lexicalModelJSON; + this.packagesJSON = packagesJSON; } public boolean isEmpty() { boolean emptyKbd = keyboardJSON == null || keyboardJSON.length() == 0; boolean emptyLex = lexicalModelJSON == null || lexicalModelJSON.length() == 0; + boolean emptyPkg = packagesJSON == null || packagesJSON.length() == 0; - return emptyKbd && emptyLex; + return emptyKbd && emptyLex && emptyPkg; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardDataDownloadCallback.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardDataDownloadCallback.java index b9709656fef6893d29140f02d3b03c3c7f24dd60..3d8e07808e34c2cf8324e037b546d75267ab672e 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardDataDownloadCallback.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardDataDownloadCallback.java @@ -10,6 +10,7 @@ import com.tavultesoft.kmea.R; import com.tavultesoft.kmea.cloud.CloudApiTypes; import com.tavultesoft.kmea.cloud.ICloudDownloadCallback; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; import java.io.File; import java.io.IOException; @@ -83,9 +84,8 @@ public class CloudKeyboardDataDownloadCallback implements ICloudDownloadCallback FileUtils.copy(_d.getDestinationFile(), _data_file); } - catch (IOException _e) - { - Log.e(TAG,_e.getLocalizedMessage(),_e); + catch (IOException e) { + KMLog.LogException(TAG, "", e); } } else diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardDownloadReturns.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardDownloadReturns.java index 4801b01583459ad0db29c36146dfb472cb88b2a8..97caad0854d4faf0faf876fdf7b81966e7862bc7 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardDownloadReturns.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardDownloadReturns.java @@ -8,14 +8,14 @@ import java.util.Map; */ public class CloudKeyboardDownloadReturns { public final Integer kbdResult; - public final List> installedLexicalModels; + public final List> installedResource; public CloudKeyboardDownloadReturns(Integer i) { this(i, null); } - public CloudKeyboardDownloadReturns(Integer i, List> installedLexicalModels) { + public CloudKeyboardDownloadReturns(Integer i, List> installedResource) { this.kbdResult = i; - this.installedLexicalModels = installedLexicalModels; + this.installedResource = installedResource; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardMetaDataDownloadCallback.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardMetaDataDownloadCallback.java index 493805705678559a6d57d4d57992e26bb9ad3387..e3719ba58c155277ca2b8ac02dda620bcc761351 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardMetaDataDownloadCallback.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardMetaDataDownloadCallback.java @@ -1,7 +1,7 @@ package com.tavultesoft.kmea.cloud.impl; import android.content.Context; -import android.util.Log; +import android.os.Bundle; import android.widget.Toast; import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; @@ -12,7 +12,9 @@ import com.tavultesoft.kmea.cloud.CloudApiTypes; import com.tavultesoft.kmea.cloud.CloudDataJsonUtil; import com.tavultesoft.kmea.cloud.CloudDownloadMgr; import com.tavultesoft.kmea.cloud.ICloudDownloadCallback; +import com.tavultesoft.kmea.data.KeyboardController; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; import org.json.JSONArray; import org.json.JSONException; @@ -42,10 +44,6 @@ public class CloudKeyboardMetaDataDownloadCallback implements ICloudDownloadCall private static final String TAG = "CloudKeyboardMetaDldCb"; - /** - * Additional Cloud API parameter: Is custom keyboard. - */ - public static final String PARAM_IS_CUSTOM = "is_custom"; /** * Additional Cloud API parameter: language id. */ @@ -95,7 +93,7 @@ public class CloudKeyboardMetaDataDownloadCallback implements ICloudDownloadCall return; } - processCloudResults(aCloudResult); + processCloudResults(aContext, aCloudResult); startDownloads(aContext, aCloudResult); } @@ -152,25 +150,21 @@ public class CloudKeyboardMetaDataDownloadCallback implements ICloudDownloadCall /** * process the meta data result and prepare the additional downloads. + * @param aContext the context * @param aMetaDataResult the meta data results */ - private void processCloudResults(List aMetaDataResult) { - for(MetaDataResult _r:aMetaDataResult) - { - if(_r.returnjson.target== CloudApiTypes.ApiTarget.Keyboard) - { - handleKeyboardMetaData(_r); + private void processCloudResults(Context aContext, List aMetaDataResult) { + for(MetaDataResult _r:aMetaDataResult) { + if (_r.returnjson.target== CloudApiTypes.ApiTarget.Keyboard) { + //handleKeyboardMetaData(_r); } - if(_r.returnjson.target== CloudApiTypes.ApiTarget.KeyboardLexicalModels) - { + if(_r.returnjson.target== CloudApiTypes.ApiTarget.KeyboardLexicalModels) { JSONArray lmData = _r.returnjson.jsonArray; if (lmData != null && lmData.length() > 0) { - try - { + try { JSONObject modelInfo = lmData.getJSONObject(0); - if (modelInfo.has("packageFilename") && modelInfo.has("id")) - { + if (modelInfo.has("packageFilename") && modelInfo.has("id")) { String _modelID = modelInfo.getString("id"); ArrayList urls = new ArrayList<>(); urls.add(new CloudApiTypes.CloudApiParam( @@ -180,10 +174,19 @@ public class CloudKeyboardMetaDataDownloadCallback implements ICloudDownloadCall _r.additionalDownloads= urls; } } catch (JSONException e) { - Log.e(TAG, "Error parsing lexical model from api.keyman.com. " + e); + KMLog.LogException(TAG, "Error parsing lexical model from api.keyman.com. ", e); } } } + if (_r.returnjson.target == CloudApiTypes.ApiTarget.PackageVersion) { + JSONObject pkgData = _r.returnjson.jsonObject; + + if (pkgData != null) { + List updateBundles = new ArrayList<>(); + CloudDataJsonUtil.processKeyboardPackageUpdateJSON(aContext, pkgData, updateBundles); + CloudDataJsonUtil.processLexicalModelPackageUpdateJSON(aContext, pkgData, updateBundles); + } + } } } @@ -193,15 +196,9 @@ public class CloudKeyboardMetaDataDownloadCallback implements ICloudDownloadCall */ private void handleKeyboardMetaData(MetaDataResult theKbData) { - if (theKbData.params.getAdditionalProperty(PARAM_IS_CUSTOM,Boolean.class)) { - throw new IllegalStateException("Cannot download custom non-KMP keyboard"); - } - String _key_id = theKbData.params.getAdditionalProperty(PARAM_KB_ID,String.class); String _lang_id = theKbData.params.getAdditionalProperty(PARAM_LANG_ID,String.class); - String _kbIsCustom = - theKbData.params.getAdditionalProperty(PARAM_IS_CUSTOM,Boolean.class) ? "Y" : "N"; JSONObject _kb_data = theKbData.returnjson.jsonObject; try { @@ -277,12 +274,11 @@ public class CloudKeyboardMetaDataDownloadCallback implements ICloudDownloadCall theKbData.additionalDownloadid = CloudKeyboardDataDownloadCallback.createDownloadId(_key_id); theKbData.keyboardInfo = CloudDataJsonUtil .createKeyboardInfoMap( - _pkgID, _lang_id, _langName, _key_id, _kbName, _kbVersion, _kbIsCustom, _font, _oskFont, _customHelpLink); + _pkgID, _lang_id, _langName, _key_id, _kbName, _kbVersion, _font, _oskFont, _customHelpLink); theKbData.additionalDownloads = urls; } - catch(JSONException _e) - { - Log.e(TAG,_e.getLocalizedMessage(),_e); + catch(JSONException e) { + KMLog.LogException(TAG, "", e); } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardPackageDownloadCallback.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardPackageDownloadCallback.java new file mode 100644 index 0000000000000000000000000000000000000000..4f1d42fea614a9e0ba4a37fd742ccbdb5c9aabe5 --- /dev/null +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudKeyboardPackageDownloadCallback.java @@ -0,0 +1,130 @@ +package com.tavultesoft.kmea.cloud.impl; + +import android.content.Context; +import android.net.Uri; +import android.widget.Toast; + +import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; +import com.tavultesoft.kmea.KeyboardEventHandler; +import com.tavultesoft.kmea.R; +import com.tavultesoft.kmea.cloud.CloudApiTypes; +import com.tavultesoft.kmea.cloud.ICloudDownloadCallback; +import com.tavultesoft.kmea.packages.LexicalModelPackageProcessor; +import com.tavultesoft.kmea.packages.PackageProcessor; +import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; + +import org.json.JSONException; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * Install Keyboard package + */ +public class CloudKeyboardPackageDownloadCallback implements ICloudDownloadCallback< + Void, CloudKeyboardDownloadReturns> +{ + + private static final String TAG = "CloudKbdPKGDldCb"; + + private File resourceRoot; + private File cacheDir; + private String languageID; + + public void setLanguageID(String languageID) { + this.languageID = languageID; + } + + @Override + public void initializeContext(Context context) + { + resourceRoot = new File(context.getDir("data", Context.MODE_PRIVATE).toString() + File.separator); + cacheDir = context.getCacheDir(); + } + + @Override + public CloudKeyboardDownloadReturns extractCloudResultFromDownloadSet( + CloudApiTypes.CloudDownloadSet aDownload) + { + PackageProcessor kbdKMPProcessor = new PackageProcessor(resourceRoot); + List> installedKeyboards = null; + + int _result = FileUtils.DOWNLOAD_SUCCESS; + for(CloudApiTypes.SingleCloudDownload _d:aDownload.getSingleDownloads()) + { + if (_d.getDestinationFile() != null && _d.getDestinationFile().length() > 0) + { + + try { + if (_d.getCloudParams().target == CloudApiTypes.ApiTarget.KeyboardPackage) { + installedKeyboards = new LinkedList<>(); + + // Parse url for the kmp filename + Uri uri = Uri.parse(_d.getCloudParams().url); + String packageID = uri.getLastPathSegment(); + if (packageID == null || packageID.isEmpty()) { + KMLog.LogError(TAG, "Cloud URL " + _d.getCloudParams().url + " has null packageID"); + } + String kmpFilename = String.format("%s%s", packageID, FileUtils.KEYMANPACKAGE); + + // Extract the kmp. + File kmpFile = new File(cacheDir, kmpFilename); + + FileUtils.copy(_d.getDestinationFile(), kmpFile); + + String pkgTarget = kbdKMPProcessor.getPackageTarget(kmpFile); + if (pkgTarget.equals(PackageProcessor.PP_TARGET_KEYBOARDS)) { + File unzipPath = kbdKMPProcessor.unzipKMP(kmpFile); + ArrayList languageList = new ArrayList(); + if (languageID != null && !languageID.isEmpty()) { + languageList.add(languageID); + } + installedKeyboards.addAll(kbdKMPProcessor.processKMP(kmpFile, unzipPath, PackageProcessor.PP_KEYBOARDS_KEY, languageList)); + } + } + } + catch (IOException | JSONException e) { + KMLog.LogException(TAG, "", e); + } + } + else + { + _result = FileUtils.DOWNLOAD_ERROR; + } + } + return new CloudKeyboardDownloadReturns(_result, installedKeyboards); + } + + + + @Override + public void applyCloudDownloadToModel(Context aContext, Void aModel, CloudKeyboardDownloadReturns aCloudResult) + { + Toast.makeText(aContext, + aContext.getString(R.string.keyboard_download_finished), + Toast.LENGTH_SHORT).show(); + + if(aCloudResult.installedResource != null) + { + KeyboardEventHandler.notifyListeners(KMKeyboardDownloaderActivity.getKbDownloadEventListeners(), + KeyboardEventHandler.EventType.PACKAGE_INSTALLED, + aCloudResult.installedResource, aCloudResult.kbdResult); + } + } + + /** + * create a download id for the model. + * @param languageID the language ID + * @param keyboardID the keyboard ID + * @return the result + */ + public static String createDownloadId(String languageID, String keyboardID) + { + return String.format("keyboard_%s_%s", languageID, keyboardID); + } +} diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudLexicalPackageDownloadCallback.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudLexicalPackageDownloadCallback.java index 71ef0f4e3d8576a9ae817f6670d79d7c9c7beac7..872ef170b7fa3eec1250fc91240509d9bde239ff 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudLexicalPackageDownloadCallback.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/cloud/impl/CloudLexicalPackageDownloadCallback.java @@ -1,7 +1,7 @@ package com.tavultesoft.kmea.cloud.impl; import android.content.Context; -import android.util.Log; +import android.net.Uri; import android.widget.Toast; import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; @@ -12,6 +12,7 @@ import com.tavultesoft.kmea.cloud.ICloudDownloadCallback; import com.tavultesoft.kmea.packages.LexicalModelPackageProcessor; import com.tavultesoft.kmea.packages.PackageProcessor; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; import org.json.JSONException; @@ -54,11 +55,18 @@ public class CloudLexicalPackageDownloadCallback implements ICloudDownloadCallba { try { - - if (_d.getCloudParams().target== CloudApiTypes.ApiTarget.LexicalModelPackage) { + if (_d.getCloudParams().target == CloudApiTypes.ApiTarget.LexicalModelPackage) { installedLexicalModels = new LinkedList<>(); + + // Parse url for the kmp filename + Uri uri = Uri.parse(_d.getCloudParams().url); + String kmpFilename = uri.getLastPathSegment(); + if (kmpFilename == null || kmpFilename.isEmpty()) { + KMLog.LogError(TAG, "Cloud URL " + _d.getCloudParams().url + " has null model package"); + } + // Extract the kmp. Validate it contains only lexical models, and then process the lexical model package - File kmpFile = new File(cacheDir, FileUtils.getFilename(_d.getCloudParams().url)); + File kmpFile = new File(cacheDir, kmpFilename); FileUtils.copy(_d.getDestinationFile(), kmpFile); @@ -69,9 +77,8 @@ public class CloudLexicalPackageDownloadCallback implements ICloudDownloadCallba } } } - catch (IOException | JSONException _e) - { - Log.e(TAG,_e.getLocalizedMessage(),_e); + catch (IOException | JSONException e) { + KMLog.LogException(TAG, "", e); } } else @@ -91,11 +98,11 @@ public class CloudLexicalPackageDownloadCallback implements ICloudDownloadCallba aContext.getString(R.string.dictionary_download_finished), Toast.LENGTH_SHORT).show(); - if(aCloudResult.installedLexicalModels != null) + if(aCloudResult.installedResource != null) { KeyboardEventHandler.notifyListeners(KMKeyboardDownloaderActivity.getKbDownloadEventListeners(), KeyboardEventHandler.EventType.LEXICAL_MODEL_INSTALLED, - aCloudResult.installedLexicalModels, aCloudResult.kbdResult); + aCloudResult.installedResource, aCloudResult.kbdResult); } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/CloudRepository.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/CloudRepository.java index 2f51b3789e4af238d1730843b2909e17388638af..0bed00ec3f305a63e7922a8f418fa014de921e55 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/CloudRepository.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/CloudRepository.java @@ -2,7 +2,6 @@ package com.tavultesoft.kmea.data; import android.content.Context; import android.os.Bundle; -import android.util.Log; import android.widget.Toast; import androidx.annotation.NonNull; @@ -18,6 +17,8 @@ import com.tavultesoft.kmea.cloud.impl.CloudCatalogDownloadReturns; import com.tavultesoft.kmea.cloud.CloudDataJsonUtil; import com.tavultesoft.kmea.cloud.CloudDownloadMgr; import com.tavultesoft.kmea.packages.JSONUtils; +import com.tavultesoft.kmea.util.BCP47; +import com.tavultesoft.kmea.util.KMLog; import org.json.JSONArray; import org.json.JSONException; @@ -27,6 +28,7 @@ import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; +import java.util.HashMap; import java.util.List; public class CloudRepository { @@ -35,6 +37,13 @@ public class CloudRepository { public static final String DOWNLOAD_IDENTIFIER_CATALOGUE = "catalogue"; + public static final String API_PRODUCTION_HOST = "api.keyman.com"; + public static final String API_STAGING_HOST = "api.keyman-staging.com"; + + public static final String API_MODEL_QUERY = "?q"; + public static final String API_MODEL_FORMATSTR = "https://%s/model%s"; + public static final String API_PACKAGE_VERSION_FORMATSTR = "https://%s/package-version?platform=android%s%s"; + private Dataset memCachedDataset; private Calendar lastLoad; // To be used for Dataset caching. private boolean invalidateLexicalCache = false; @@ -56,6 +65,33 @@ public class CloudRepository { void onUpdateDetection(List updateBundles); } + /** + * Get the api.keyman.com host (production vs staging) based on the tier + * @return String of api.keyman.com host + */ + public static String getHost() { + switch (KMManager.getTier(BuildConfig.VERSION_NAME)) { + case ALPHA: + case BETA: + return API_STAGING_HOST; + default: + return API_PRODUCTION_HOST; + } + } + + /** + * Get the validity for cached resources (lexical model cache and package-version) + * @param context the main activity of the application + * @return boolean of the cache validity + */ + public boolean getCacheValidity(@NonNull Context context) { + boolean loadLexicalModelsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getLexicalModelCacheFile(context)); + boolean loadResourcesFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getResourcesCacheFile(context)); + + boolean cacheValid = loadLexicalModelsFromCache && loadResourcesFromCache; + return cacheValid; + } + public boolean hasCache(Context context) { if(DEBUG_DISABLE_CACHE) { return false; @@ -64,8 +100,7 @@ public class CloudRepository { if(shouldUseMemCache(context)) { return true; } else { - return shouldUseCache(context, CloudDataJsonUtil.getKeyboardCacheFile(context)) && - shouldUseCache(context, CloudDataJsonUtil.getLexicalModelCacheFile(context)); + return getCacheValidity(context); } } @@ -111,6 +146,25 @@ public class CloudRepository { } } + /** + * Search the available lexical models list and see there's an associated model for a + * given language ID. Available models are from the cloud catalog and locally installed models. + * @param context Context + * @param languageID String of the language ID to search + * @return LexicalModel of an associated lexical model. Null if no match found + */ + public LexicalModel getAssociatedLexicalModel(@NonNull Context context, String languageID) { + if (memCachedDataset != null) { + for (int i=0; i < memCachedDataset.lexicalModels.getCount(); i++) { + LexicalModel lm = memCachedDataset.lexicalModels.getItem(i); + if (BCP47.languageEquals(lm.getLanguageID(), languageID)) { + return lm; + } + } + } + return null; + } + // Should be called whenever a new language code starts being managed in order to help signal // retrieval of the language code's lexical models. public void invalidateLexicalModelCache(@NonNull Context context) { @@ -122,35 +176,45 @@ public class CloudRepository { file.delete(); } - private CloudApiTypes.CloudApiParam prepareKeyboardUpdateQuery(Context aContext) - { - String deviceType = CloudDataJsonUtil.getDeviceTypeForCloudQuery(aContext); - - // Sanitize appVersion to #.#.# to match the API spec - // Regex needs to match the entire string - String appVersion = KMManager.getVersion(); - // Retrieves the cloud-based keyboard catalog in Android's preferred format. - String keyboardURL = String.format("%s?version=%s&device=%s&languageidtype=bcp47", - KMKeyboardDownloaderActivity.kKeymanApiBaseURL, appVersion, deviceType); - - //cloudQueries[cloudQueryEntries++] = new CloudApiParam(ApiTarget.Keyboards, keyboardURL, JSONType.Object); - return new CloudApiTypes.CloudApiParam( - CloudApiTypes.ApiTarget.Keyboards, keyboardURL).setType(CloudApiTypes.JSONType.Object); + private CloudApiTypes.CloudApiParam prepareResourcesUpdateQuerty(Context aContext) { + // Keyman cloud keyboard + // Append each keyboard id + String keyboardQuery = ""; + for(Keyboard k : KeyboardController.getInstance().get()) { + String keyboardID = k.getKeyboardID(); + if (!keyboardQuery.contains(keyboardID)) { + keyboardQuery = String.format("%s&keyboard=%s", keyboardQuery, keyboardID); + } + } + + String lexicalModelQuery = ""; + for(HashMap hashMap : KMManager.getLexicalModelsList(aContext)) { + if (hashMap != null && hashMap.containsKey(KMManager.KMKey_LexicalModelID)) { + String lexicalModelID = hashMap.get(KMManager.KMKey_LexicalModelID); + if (!lexicalModelQuery.contains(lexicalModelID)) { + lexicalModelQuery = String.format("%s&model=%s", lexicalModelQuery, lexicalModelID); + } + } + } + + String queryURL = String.format(API_PACKAGE_VERSION_FORMATSTR, getHost(), keyboardQuery, lexicalModelQuery); + return new CloudApiTypes.CloudApiParam( + CloudApiTypes.ApiTarget.PackageVersion, queryURL).setType(CloudApiTypes.JSONType.Object); } - private CloudApiTypes.CloudApiParam prepareLexicalModellUpdateQuery(Context aContext) + private CloudApiTypes.CloudApiParam prepareLexicalModelUpdateQuery(Context aContext) { // This allows us to directly get the full lexical model catalog. // TODO: Remove and replace with commented-out code below once the proper multi-language // query is ready! - String lexicalURL = String.format("%s?q", KMKeyboardDownloaderActivity.kKeymanApiModelURL); + String lexicalURL = String.format(API_MODEL_FORMATSTR, getHost(), API_MODEL_QUERY); return new CloudApiTypes.CloudApiParam(CloudApiTypes.ApiTarget.LexicalModels, lexicalURL) .setType(CloudApiTypes.JSONType.Array); - // TODO: We want a list of lexical models for every language with an installed resource (kbd, lex model) -// String lexicalURL = String.format("%s?q=bcp47:", KMKeyboardDownloaderActivity.kKeymanApiModelURL); + +// String lexicalURL = String.format(API_MODEL_FORMATSTR, getHost(), "?q=bcp47:"); // // for(String lgCode: languageCodes) { // lexicalURL = String.format("%s%s,", lexicalURL, lgCode); @@ -186,10 +250,7 @@ public class CloudRepository { */ public void updateDatasetIfNeeded(@NonNull Context context, UpdateHandler updateHandler, Runnable onSuccess, Runnable onFailure) { - boolean loadKeyboardsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getKeyboardCacheFile(context)); - boolean loadLexicalModelsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getLexicalModelCacheFile(context)); - - boolean cacheValid = loadKeyboardsFromCache && loadLexicalModelsFromCache; + boolean cacheValid = getCacheValidity(context); if(cacheValid && shouldUseMemCache(context)) { onSuccess.run(); @@ -211,10 +272,7 @@ public class CloudRepository { */ private void preCacheDataSet(@NonNull Context context, UpdateHandler updateHandler, Runnable onSuccess, Runnable onFailure) { - boolean loadKeyboardsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getKeyboardCacheFile(context)); - boolean loadLexicalModelsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getLexicalModelCacheFile(context)); - - boolean cacheValid = loadKeyboardsFromCache && loadLexicalModelsFromCache; + boolean cacheValid = getCacheValidity(context); if(cacheValid && shouldUseMemCache(context)) { return; // isn't null - checked by `shouldUseCache`. @@ -241,6 +299,7 @@ public class CloudRepository { // Consolidate kmp.json info from packages/ JSONObject kmpLanguagesArray = wrapKmpKeyboardJSON(JSONUtils.getLanguages()); JSONArray kmpLexicalModelsArray = JSONUtils.getLexicalModels(); + final boolean fromKMP = true; try { if (kmpLanguagesArray.getJSONObject(KMKeyboardDownloaderActivity.KMKey_Languages). @@ -248,10 +307,10 @@ public class CloudRepository { memCachedDataset.keyboards.addAll(CloudDataJsonUtil.processKeyboardJSON(kmpLanguagesArray, true)); } if (kmpLexicalModelsArray.length() > 0) { - memCachedDataset.lexicalModels.addAll(CloudDataJsonUtil.processLexicalModelJSON(kmpLexicalModelsArray)); + memCachedDataset.lexicalModels.addAll(CloudDataJsonUtil.processLexicalModelJSON(kmpLexicalModelsArray, fromKMP)); } } catch (Exception e) { - Log.e(TAG, "preCacheDataSet error " + e); + KMLog.LogException(TAG, "preCacheDataSet error ", e); } CloudCatalogDownloadCallback _download_callback = new CloudCatalogDownloadCallback( context, updateHandler, onSuccess, onFailure); @@ -259,44 +318,42 @@ public class CloudRepository { // Default values: empty JSON instances. `null` will instead break things. JSONObject kbdData = new JSONObject(); JSONArray lexData = new JSONArray(); + JSONObject pkgData = new JSONObject(); - if(loadKeyboardsFromCache) { - kbdData = CloudDataJsonUtil.getCachedJSONObject(CloudDataJsonUtil.getKeyboardCacheFile(context)); + if (cacheValid) { + // Get the lexical model info + lexData = CloudDataJsonUtil.getCachedJSONArray(CloudDataJsonUtil.getLexicalModelCacheFile(context)); - // In case something went wrong with the last cache attempt, which can cause a null return. - if(kbdData == null) { - kbdData = new JSONObject(); - loadKeyboardsFromCache = false; + // In case something went wrong with the last cache attempt, which can cause a null return + if (lexData == null) { + lexData = new JSONArray(); + cacheValid = false; } - } - if(loadLexicalModelsFromCache) { - lexData = CloudDataJsonUtil.getCachedJSONArray(CloudDataJsonUtil.getLexicalModelCacheFile(context)); + pkgData = CloudDataJsonUtil.getCachedJSONObject(CloudDataJsonUtil.getResourcesCacheFile(context)); - if(lexData == null) { - lexData = new JSONArray(); - loadLexicalModelsFromCache = false; + if (pkgData == null) { + pkgData = new JSONObject(); } } + // Reuse any valid parts of the cache. - if(loadKeyboardsFromCache || loadLexicalModelsFromCache) { - CloudCatalogDownloadReturns jsonData = new CloudCatalogDownloadReturns(kbdData, lexData); + if (cacheValid) { + CloudCatalogDownloadReturns jsonData = new CloudCatalogDownloadReturns(kbdData, lexData, pkgData); // Call the processor method directly with the cached API data. - _download_callback.processCloudReturns(memCachedDataset,jsonData, - loadKeyboardsFromCache && loadLexicalModelsFromCache); // TODO: Take params for finish, return val for failures + _download_callback.processCloudReturns(memCachedDataset, jsonData, + cacheValid); // TODO: Take params for finish, return val for failures } } + /** * Fetches a Dataset object corresponding to keyboards and models available from cache or file cache. * @param context The current Activity requesting the Dataset. * @return A Dataset object implementing the Adapter interface to be asynchronously filled. */ public Dataset fetchDataset(@NonNull Context context) { - boolean loadKeyboardsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getKeyboardCacheFile(context)); - boolean loadLexicalModelsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getLexicalModelCacheFile(context)); - - boolean cacheValid = loadKeyboardsFromCache && loadLexicalModelsFromCache; + boolean cacheValid = getCacheValidity(context); if(cacheValid && shouldUseMemCache(context)) { return memCachedDataset; // isn't null - checked by `shouldUseCache`. @@ -321,27 +378,16 @@ public class CloudRepository { * @param onFailure A callback to be triggered upon failure of a query. */ private void downloadMetaDataFromServer(@NonNull Context context, UpdateHandler updateHandler, Runnable onSuccess, Runnable onFailure) { - boolean loadKeyboardsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getKeyboardCacheFile(context)); - boolean loadLexicalModelsFromCache = this.shouldUseCache(context, CloudDataJsonUtil.getLexicalModelCacheFile(context)); - - boolean cacheValid = loadKeyboardsFromCache && loadLexicalModelsFromCache; + boolean cacheValid = getCacheValidity(context); if(cacheValid && shouldUseMemCache(context)) { return; // isn't null - checked by `shouldUseCache`. } // check if cache file is valid - if(loadKeyboardsFromCache) { - // In case something went wrong with the last cache attempt, which can cause a null return. - if(CloudDataJsonUtil.getCachedJSONObject(CloudDataJsonUtil.getKeyboardCacheFile(context)) == null) { - loadKeyboardsFromCache = false; - } - } - - // check if cache file is valid - if(loadLexicalModelsFromCache) { + if(cacheValid) { if(CloudDataJsonUtil.getCachedJSONArray(CloudDataJsonUtil.getLexicalModelCacheFile(context)) == null) { - loadLexicalModelsFromCache = false; + cacheValid = false; } } @@ -349,13 +395,9 @@ public class CloudRepository { // int cloudQueryEntries = 0; List cloudQueries = new ArrayList<>(2); - if (!loadKeyboardsFromCache) { - - cloudQueries.add(prepareKeyboardUpdateQuery(context)); - } - - if (!loadLexicalModelsFromCache) { - cloudQueries.add(prepareLexicalModellUpdateQuery(context)); + if (!cacheValid) { + cloudQueries.add(prepareLexicalModelUpdateQuery(context)); + cloudQueries.add(prepareResourcesUpdateQuerty(context)); } int cloudQueryEntries = cloudQueries.size(); @@ -387,7 +429,7 @@ public class CloudRepository { JSONObject json = new JSONObject().put(KMKeyboardDownloaderActivity.KMKey_Languages, languagesArray); return new JSONObject().put(KMKeyboardDownloaderActivity.KMKey_Languages, json); } catch (JSONException e) { - Log.e(TAG, "Failed to properly handle KMP JSON. Error: " + e); + KMLog.LogException(TAG, "Failed to properly handle KMP JSON. Error: ", e); return null; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/Dataset.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/Dataset.java index 5ba12e2fac69319cd1238f299ce7e262f7975a53..dcc1e5817d3285c94a25b4b2ab5201a2a4dd2e27 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/Dataset.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/Dataset.java @@ -112,7 +112,7 @@ public class Dataset extends ArrayAdapter implements Li public Type findMatch(Type target) { for(Type obj: data) { - if(obj.getResourceId().equals(target.getResourceId()) && obj.getLanguageID().equals(target.getLanguageID())) { + if (target.equals(obj)) { return obj; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/Keyboard.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/Keyboard.java index 6a3fde64c019617fb8fa7cbda4430b2b6c7e553c..ec5aed8c7c54e0b8724bfe66fcf0c0fbebc08a7f 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/Keyboard.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/Keyboard.java @@ -1,50 +1,65 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ package com.tavultesoft.kmea.data; +import android.content.Context; import android.os.Bundle; -import android.util.Log; + +import androidx.annotation.NonNull; import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KeyboardPickerActivity; +import com.tavultesoft.kmea.util.BCP47; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; -import java.util.Map; -public class Keyboard implements Serializable, LanguageResource { +public class Keyboard extends LanguageResource implements Serializable { private static final String TAG = "Keyboard"; private static final String HELP_URL_FORMATSTR = "https://help.keyman.com/keyboard/%s/%s"; - private String packageID; - private String keyboardID; - private String keyboardName; - private String languageID; - private String languageName; - private boolean isCustomKeyboard; private boolean isNewKeyboard; private String font; private String oskFont; - private String helpLink; - private String version; + // JSON keys + private static String KB_NEW_KEYBOARD_KEY = "isNewKeyboard"; + private static String KB_FONT_KEY = "font"; + private static String KB_OSK_FONT_KEY = "oskFont"; + + private static Keyboard FALLBACK_KEYBOARD; + + /** + * Constructor using JSON Objects from installed keyboards list + * @param installedObj + */ + public Keyboard(JSONObject installedObj) { + this.fromJSON(installedObj); + } + + /** + * Constructor using JSON Objects from keyboard cloud catalog + * @param languageJSON + * @param keyboardJSON + */ public Keyboard(JSONObject languageJSON, JSONObject keyboardJSON) { try { this.packageID = keyboardJSON.optString(KMManager.KMKey_PackageID, KMManager.KMDefault_UndefinedPackageID); - this.keyboardID = keyboardJSON.getString(KMManager.KMKey_ID); + this.resourceID = keyboardJSON.getString(KMManager.KMKey_ID); - this.keyboardName = keyboardJSON.getString(KMManager.KMKey_Name); + this.resourceName = keyboardJSON.getString(KMManager.KMKey_Name); // language ID and language name from languageJSON this.languageID = languageJSON.getString(KMManager.KMKey_ID).toLowerCase(); this.languageName = languageJSON.getString(KMManager.KMKey_Name); - this.isCustomKeyboard = keyboardJSON.has(KMManager.KMKey_CustomKeyboard) && - keyboardJSON.get(KMManager.KMKey_CustomKeyboard).equals("Y"); - this.isNewKeyboard = keyboardJSON.has(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD) && keyboardJSON.get(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD).equals(KeyboardPickerActivity.KMKEY_INTERNAL_NEW_KEYBOARD); @@ -52,83 +67,67 @@ public class Keyboard implements Serializable, LanguageResource { this.oskFont = keyboardJSON.optString(KMManager.KMKey_OskFont, ""); - this.version = keyboardJSON.optString(KMManager.KMKey_KeyboardVersion, "1.0"); + this.version = keyboardJSON.optString(KMManager.KMKey_KeyboardVersion, null); this.helpLink = keyboardJSON.optString(KMManager.KMKey_CustomHelpLink, - String.format(HELP_URL_FORMATSTR, this.keyboardID, this.version)); + String.format(HELP_URL_FORMATSTR, this.resourceID, this.version)); } catch (JSONException e) { - Log.e(TAG, "Keyboard exception parsing JSON: " + e); + KMLog.LogException(TAG, "Keyboard exception parsing JSON: ", e); } } - public Keyboard(String packageID, String keyboardID, String keyboardName, String languageID, String languageName, - boolean isCustomKeyboard, boolean isNewKeyboard, - String font, String oskFont, String version, String helpLink) { + public Keyboard(String packageID, String keyboardID, String keyboardName, + String languageID, String languageName, String version, + String helpLink, String kmp, + boolean isNewKeyboard, String font, String oskFont) { + super(packageID, keyboardID, keyboardName, languageID, languageName, version, + (FileUtils.isWelcomeFile(helpLink)) ? helpLink : + String.format(HELP_URL_FORMATSTR, keyboardID, version), + kmp); - this.packageID = (packageID != null) ? packageID : KMManager.KMDefault_UndefinedPackageID; - this.keyboardID = keyboardID; - this.keyboardName = keyboardName; - this.languageID = languageID.toLowerCase(); - this.languageName = languageName; - this.isCustomKeyboard = isCustomKeyboard; this.isNewKeyboard = isNewKeyboard; this.font = (font != null) ? font : ""; this.oskFont = (oskFont != null) ? oskFont : ""; - this.version = (version != null) ? version : "1.0"; - this.helpLink = (FileUtils.isWelcomeFile(helpLink)) ? helpLink : - String.format(HELP_URL_FORMATSTR, this.keyboardID, this.version); } - public boolean isCustomKeyboard() { return isCustomKeyboard; } + public Keyboard(Keyboard k) { + super(k.getPackageID(), k.getKeyboardID(), k.getKeyboardName(), + k.getLanguageID(), k.getLanguageName(), k.getVersion(), + k.getHelpLink(), k.getUpdateKMP()); + this.isNewKeyboard = false; + this.font = k.getFont(); + this.oskFont = k.getOSKFont(); + } - public boolean isNewKeyboard() { return isNewKeyboard; } + public String getKeyboardID() { return getResourceID(); } + public String getKeyboardName() { return getResourceName(); } - public String getResourceId() { return keyboardID; } + public boolean getNewKeyboard() { return isNewKeyboard; } + public void setNewKeyboard(boolean isNewKeyboard) { this.isNewKeyboard = isNewKeyboard; } public String getFont() { return font; } public String getOSKFont() { return oskFont; } - public String getLanguageID() { return languageID; } - - // Deprecated in Keyman 14.0 for getLanguageID() - @Override - public String getLanguageCode() { return languageID; } - - public String getLanguageName() { return languageName; } - - public String getResourceName() { return keyboardName; } - - public String getCustomHelpLink() { return helpLink; } - - public String getVersion() { return version; } - - public String getPackageID() { return packageID; } - - // Deprecated in Keyman 14.0 for getPackageID() - @Override - public String getPackage() { return packageID; } - public Bundle buildDownloadBundle() { Bundle bundle = new Bundle(); bundle.putString(KMKeyboardDownloaderActivity.ARG_PKG_ID, packageID); - bundle.putString(KMKeyboardDownloaderActivity.ARG_KB_ID, keyboardID); + bundle.putString(KMKeyboardDownloaderActivity.ARG_KB_ID, resourceID); bundle.putString(KMKeyboardDownloaderActivity.ARG_LANG_ID, languageID); - bundle.putString(KMKeyboardDownloaderActivity.ARG_KB_NAME, keyboardName); + bundle.putString(KMKeyboardDownloaderActivity.ARG_KB_NAME, resourceName); bundle.putString(KMKeyboardDownloaderActivity.ARG_LANG_NAME, languageName); - bundle.putBoolean(KMKeyboardDownloaderActivity.ARG_IS_CUSTOM, isCustomKeyboard); - bundle.putString(KMKeyboardDownloaderActivity.ARG_CUSTOM_HELP_LINK, helpLink); + bundle.putString(KMKeyboardDownloaderActivity.ARG_KMP_LINK, kmp); return bundle; } public boolean equals(Object obj) { if(obj instanceof Keyboard) { - boolean lgCodeMatch = ((Keyboard) obj).getLanguageID().equals(this.getLanguageID()); - boolean idMatch = ((Keyboard) obj).getResourceId().equals(this.getResourceId()); + boolean lgCodeMatch = BCP47.languageEquals(((Keyboard) obj).getLanguageID(), this.getLanguageID()); + boolean idMatch = ((Keyboard) obj).getKeyboardID().equals(this.getKeyboardID()); return lgCodeMatch && idMatch; } @@ -136,10 +135,67 @@ public class Keyboard implements Serializable, LanguageResource { return false; } - @Override - public int hashCode() { - String id = getResourceId(); - String lgCode = getLanguageID(); - return id.hashCode() * lgCode.hashCode(); + protected void fromJSON(JSONObject installedObj) { + super.fromJSON(installedObj); + try { + this.isNewKeyboard = installedObj.getBoolean(KB_NEW_KEYBOARD_KEY); + this.font = installedObj.getString(KB_FONT_KEY); + this.oskFont = installedObj.getString(KB_OSK_FONT_KEY); + } catch (JSONException e) { + KMLog.LogException(TAG, "fromJSON exception: ", e); + } + } + + public JSONObject toJSON() { + JSONObject o = super.toJSON(); + if (o != null) { + try { + o.put(KB_NEW_KEYBOARD_KEY, this.isNewKeyboard); + o.put(KB_FONT_KEY, this.font); + o.put(KB_OSK_FONT_KEY, this.oskFont); + } catch (JSONException e) { + KMLog.LogException(TAG, "toJSON exception: ", e); + } + } + return o; + } + + /** + * Get the fallback keyboard. If never specified, use sil_euro_latin + * @param context Context + * @return Keyboard - the fallback keyboard + */ + public static Keyboard getDefaultKeyboard(@NonNull Context context) { + if (context == null) { + KMLog.LogError(TAG, "getDefaultKeyboard with null context"); + } + if (FALLBACK_KEYBOARD == null) { + String version = KMManager.getLatestKeyboardFileVersion( + context, KMManager.KMDefault_PackageID, KMManager.KMDefault_KeyboardID); + + FALLBACK_KEYBOARD = new Keyboard( + KMManager.KMDefault_PackageID, + KMManager.KMDefault_KeyboardID, + KMManager.KMDefault_KeyboardName, + KMManager.KMDefault_LanguageID, + KMManager.KMDefault_LanguageName, + version, + null, // will use help.keyman.com link because context required to determine local welcome.htm path, + "", + false, + KMManager.KMDefault_KeyboardFont, + KMManager.KMDefault_KeyboardFont); + } + return FALLBACK_KEYBOARD; + } + + /** + * Set the fallback keyboard. If keyboard is null, the fallback keyboard will + * revert to sil_euro_latin + * @param k Keyboard to set as the fallback keyboard + */ + public static void setDefaultKeyboard(Keyboard k) { + // If k is null, getDefaultKeyboard() will regenerate fallback keyboard sil_euro_latin + FALLBACK_KEYBOARD = k; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/KeyboardController.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/KeyboardController.java new file mode 100644 index 0000000000000000000000000000000000000000..1793a38d043c48a0dc4d06764b5022517534f68d --- /dev/null +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/KeyboardController.java @@ -0,0 +1,361 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ + +package com.tavultesoft.kmea.data; + +import android.content.Context; +import android.util.Log; + +import com.tavultesoft.kmea.JSONParser; +import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.KeyboardPickerActivity; +import com.tavultesoft.kmea.util.BCP47; +import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.MapCompat; +import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.util.KMLog; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileInputStream; +import java.io.ObjectInputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class KeyboardController { + public static final String TAG = "KeyboardController"; + public static final String KMFilename_Installed_KeyboardsList = "keyboards_list.json"; + public static final int INDEX_NOT_FOUND = -1; + + private static KeyboardController instance; + + /** + * @return get or create shared singleton instance. + */ + public static KeyboardController getInstance() { + if (instance == null) { + instance = new KeyboardController(); + } + return instance; + } + + private boolean isInitialized = false; + private List list; + + public synchronized void initialize(Context context) { + if (isInitialized) { + Log.w(TAG, "initialize called multiple times"); + return; + } + + File keyboards_dat = new File(context.getDir("userdata", Context.MODE_PRIVATE), + KMManager.KMFilename_KeyboardsList); + File keyboards_json = new File(context.getDir("userdata", Context.MODE_PRIVATE), + KMFilename_Installed_KeyboardsList); + if (list == null) { + list = new ArrayList(); + if (keyboards_dat.exists() && !keyboards_json.exists()) { + try { + // Migrate installed_keyboards.dat to keyboards_list.json + ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(keyboards_dat)); + ArrayList> dat_list = (ArrayList>) inputStream.readObject(); + inputStream.close(); + list = KMManager.updateOldKeyboardsList(context, dat_list); + } catch (Exception e) { + KMLog.LogException(TAG, "Exception migrating installed_keyboards.dat", e); + list.add(Keyboard.getDefaultKeyboard(context)); + } + } else if (keyboards_json.exists()) { + JSONArray json_list = null; + try { + // Get installed keyboards from keyboards_list.json + JSONParser jsonParser = new JSONParser(); + json_list = jsonParser.getJSONObjectFromFile(keyboards_json, JSONArray.class); + if (json_list != null) { + // Can't foreach JSONArray + for (int i=0; i 0) { + save(context); + + // Now we can delete legacy keyboards list + if (keyboards_dat.exists()) { + keyboards_dat.delete(); + } + } + } + isInitialized = true; + } + + /** + * Return the installed keyboards list + * @return + */ + public List get() { + if (!isInitialized) { + KMLog.LogError(TAG, "get while KeyboardController() not initialized"); + return null; + } + synchronized (list) { + return list; + } + } + + /** + * Returns the list of installed keyboards with unique packageID/keyboardID + */ + public List getInstalledPackagesList() { + if (!isInitialized) { + KMLog.LogError(TAG, "getInstalledPackagesList while KeyboardController() not initialized"); + return null; + } + synchronized (list) { + List packagesList = new ArrayList(); + // Iterate through the installed keyboards list to find unique packageID/keyboardID + for (int i=0; i= list.size()) { + KMLog.LogError(TAG, "set with index: " + index + " out of bounds"); + return; + } + + synchronized (list) { + list.set(index, currentKeyboard); + } + } + + /** + * Remove the keyboard at the specified index. + * @param index + */ + public void remove(int index) { + // Check initialized, and disallow removing default keyboard + if (!isInitialized) { + return; + } + + synchronized (list) { + if (index != INDEX_NOT_FOUND && index < list.size()) { + list.remove(index); + } + } + } + + /** + * Convert the installed keyboard list to JSONArray and write to file + * @param context + * @return boolean - Status if the keyboard list was successfully saved + */ + public boolean save(Context context) { + boolean result = false; + if (list == null || list.size() < 1) { + return result; + } + + JSONArray arr = new JSONArray(); + for (Keyboard k : list) { + JSONObject o = k.toJSON(); + arr.put(o); + } + + if (arr.length() < 1) { + return result; + } + + result = FileUtils.saveList(new File(context.getDir("userdata", Context.MODE_PRIVATE), + KMFilename_Installed_KeyboardsList), arr); + return result; + } +} diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/LanguageResource.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/LanguageResource.java index 02b96856509fc67b617b7814d73d8e53b5195313..fb3ef6520cb736d887449bd9db3ef15702364f49 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/LanguageResource.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/LanguageResource.java @@ -1,21 +1,154 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ package com.tavultesoft.kmea.data; import android.os.Bundle; -public interface LanguageResource { - String getResourceId(); - String getResourceName(); - String getLanguageID(); +import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.util.KMLog; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.Serializable; + +public abstract class LanguageResource implements Serializable { + protected String packageID; + protected String resourceID; + protected String resourceName; + protected String languageID; + protected String languageName; + protected String version; + protected String helpLink; + protected String kmp; // link to latest kmp from the cloud vs what is currently installed + + // JSON keys + private static String LR_PACKAGE_ID_KEY = "packageID"; + private static String LR_RESOURCE_ID_KEY = "resourceID"; + private static String LR_RESOURCE_NAME_KEY = "resourceName"; + private static String LR_LANGUAGE_ID_KEY = "languageID"; + private static String LR_LANGUAGE_NAME_KEY = "languageName"; + private static String LR_VERSION_KEY = "version"; + private static String LR_HELP_LINK_KEY = "helpLink"; + private static String LR_KMP_KEY = "kmp"; + + private static final String TAG = "LanguageResource"; + + public String getResourceID() { return resourceID; } + + public String getResourceName() { return resourceName; } + + public String getLanguageID() { return languageID; } // Deprecated in Keyman 14.0 by getLanguageID(); - String getLanguageCode(); - String getLanguageName(); - String getVersion(); - String getPackageID(); + public String getLanguageCode() { return languageID; } + + public String getLanguageName() { return languageName; } + + public void setLanguage(String languageID, String languageName) { + this.languageID = languageID; + this.languageName = languageName; + } + + public String getVersion() { return version; } + + public String getPackageID() { return packageID; } // Deprecated in Keyman 14.0 by getPackageID() - String getPackage(); - String getCustomHelpLink(); + public String getPackage() { return packageID; } + + public String getHelpLink() { return helpLink; } + + public String getUpdateKMP() { return kmp; } + public void setUpdateKMP(String kmp) { this.kmp = kmp; } + + /** + * Helper method if the language resource has an updated kmp package available to download from the cloud + * @return boolean true if an updated kmp package is available + */ + public boolean hasUpdateAvailable() { + return (kmp != null && !kmp.isEmpty()); + } + + public int hashCode() { + String id = getResourceID(); + String lgCode = getLanguageID(); + if (id == null || lgCode == null) { + KMLog.LogError("LanguageResource", "Invalid hashCode"); + } + return id.hashCode() * lgCode.hashCode(); + } + + public String getKey() { + return String.format("%s_%s", languageID, resourceID); + } + + public abstract Bundle buildDownloadBundle(); + + public LanguageResource() { + // Noop + } + + /** + * Constructor using properties + * @param packageID + * @param resourceID + * @param resourceName + * @param languageID + * @param languageName + * @param version + * @param helpLink + * @param kmp + */ + public LanguageResource(String packageID, String resourceID, String resourceName, + String languageID, String languageName, String version, + String helpLink, String kmp) { + this.packageID = (packageID != null) ? packageID : KMManager.KMDefault_UndefinedPackageID; + this.resourceID = resourceID; + this.resourceName = resourceName; + this.languageID = languageID.toLowerCase(); + // If language name not provided, fallback to re-use language ID + this.languageName = (languageName != null && !languageName.isEmpty()) ? languageName : this.languageID; + this.version = version; + this.helpLink = helpLink; + this.kmp = kmp; + } + + protected void fromJSON(JSONObject installedObj) { + try { + this.packageID = installedObj.getString(LanguageResource.LR_PACKAGE_ID_KEY); + this.resourceID = installedObj.getString(LanguageResource.LR_RESOURCE_ID_KEY); + this.resourceName = installedObj.getString(LanguageResource.LR_RESOURCE_NAME_KEY); + this.languageID = installedObj.getString(LanguageResource.LR_LANGUAGE_ID_KEY); + this.languageName = installedObj.getString(LanguageResource.LR_LANGUAGE_NAME_KEY); + this.version = installedObj.getString(LanguageResource.LR_VERSION_KEY); + this.helpLink = installedObj.getString(LanguageResource.LR_HELP_LINK_KEY); + if (installedObj.has(LanguageResource.LR_KMP_KEY)) { + this.kmp = installedObj.getString(LanguageResource.LR_KMP_KEY); + } else { + this.kmp = ""; + } + } catch (JSONException e) { + KMLog.LogException(TAG, "fromJSON() exception: ", e); + } + } + + public JSONObject toJSON() { + JSONObject o = new JSONObject(); + try { + o.put(LR_PACKAGE_ID_KEY, this.packageID); + o.put(LR_RESOURCE_ID_KEY, this.resourceID); + o.put(LR_RESOURCE_NAME_KEY, this.resourceName); + o.put(LR_LANGUAGE_ID_KEY, this.languageID); + o.put(LR_LANGUAGE_NAME_KEY, this.languageName); + o.put(LR_VERSION_KEY, this.version); + o.put(LR_HELP_LINK_KEY, this.helpLink); + o.put(LR_KMP_KEY, this.kmp); + } catch (JSONException e) { + KMLog.LogException(TAG, "toJSON() exception: ", e); + } - Bundle buildDownloadBundle(); + return o; + } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/LexicalModel.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/LexicalModel.java index d4c21880a12a965da030b42faa8a377d871ca140..c53ef14c413a9d11ab37b3cea0a0d9747f195f1e 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/LexicalModel.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/data/LexicalModel.java @@ -1,105 +1,138 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ package com.tavultesoft.kmea.data; +import android.content.Context; import android.os.Bundle; import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; import com.tavultesoft.kmea.KMManager; -import com.tavultesoft.kmea.util.MapCompat; +import com.tavultesoft.kmea.util.BCP47; +import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; -import java.io.Serializable; -import java.util.Map; - -public class LexicalModel implements Serializable, LanguageResource { - public final Map map; - - /* TODO: (v13 refactor) - * Drop the HashMap and instead directly represent the following as object properties: - * - * hashMap.put(KMManager.KMKey_PackageID, packageID); - * hashMap.put(KMManager.KMKey_LanguageID, languageID); - * hashMap.put(KMManager.KMKey_LexicalModelID, modelID); - * hashMap.put(KMManager.KMKey_LexicalModelName, modelName); - * hashMap.put(KMManager.KMKey_LanguageName, langName); - * hashMap.put(KMManager.KMKey_LexicalModelVersion, modelVersion); - * hashMap.put(KMManager.KMKey_CustomModel, isCustom); - */ - - public LexicalModel(Map modelData) { - this.map = modelData; - } - - public String getResourceId() { - return this.map.get(KMManager.KMKey_LexicalModelID); - } +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; - public String getLanguageID() { - return this.map.get(KMManager.KMKey_LanguageID); - } +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; - // Deprecate in Keyman 14.0 for getLanguageID() - @Override - public String getLanguageCode() { - return this.map.get(KMManager.KMKey_LanguageID); - } +public class LexicalModel extends LanguageResource implements Serializable { + private static final String TAG = "lexicalModel"; - public String getLanguageName() { - return this.map.get(KMManager.KMKey_LanguageName); + /** + * Constructor using JSON Object from installed lexical models list + * @param installedObj + */ + public LexicalModel(JSONObject installedObj) { + this.fromJSON(installedObj); } - public String getResourceName() { - return this.map.get(KMManager.KMKey_LexicalModelName); + /** + * Construct a list of LexicalModel using JSON Object (from either installed KMP or lexical model cloud catalog). + * Adds a model for each language found + * @param lexicalModelJSON + * @param fromKMP boolean - if true, only the first language in an array is processed + */ + public static List LexicalModelList(JSONObject lexicalModelJSON, boolean fromKMP) { + List lexicalModelList = new ArrayList<>(); + try { + String kmp = lexicalModelJSON.optString("packageFilename", ""); + + String packageID = ""; + if (lexicalModelJSON.has(KMManager.KMKey_PackageID)) { + packageID = lexicalModelJSON.getString(KMManager.KMKey_PackageID); + } else if (kmp != null && FileUtils.hasLexicalModelPackageExtension(kmp)) { + // Extract package ID from packageFilename + String filename = FileUtils.getFilename(kmp); + // Truncate .model.kmp file extension + packageID = filename.replace(FileUtils.MODELPACKAGE, ""); + } else { + // Invalid Package ID + KMLog.LogError(TAG, "Invalid package ID"); + } + + String resourceID = lexicalModelJSON.getString(KMManager.KMKey_ID); + + String resourceName = lexicalModelJSON.getString(KMManager.KMKey_Name); + + // Cloud data may not contain lexical model version, so fallback to (package) version + String version = lexicalModelJSON.optString(KMManager.KMKey_Version, "1.0"); + version = lexicalModelJSON.optString(KMManager.KMKey_LexicalModelVersion, version); + + String helpLink = ""; // TOODO: Handle help links + + // language ID and language name from lexicalModelJSON. Iterate through language array + String languageID = "", languageName = ""; + Object obj = lexicalModelJSON.getJSONArray("languages"); + // If processing JSONObject from kmp file, only handle the first language. + int itemsToProcess = (fromKMP) ? 1 : ((JSONArray)obj).length(); + for (int i=0; i The type specification of the Adapter to be nested/linked. */ public class NestedAdapter & ListBacked, FilterArg> extends ArrayAdapter implements ListBacked { + private final static String TAG = "NestedAdapter"; final A wrappedAdapter; final AdapterFilter filter; final List filteredList; @@ -173,11 +177,19 @@ public class NestedAdapter & ListBacked // These methods allow bypassing of our externally-visible 'linking' versions for operations // triggered by the other end of the link. protected void _internalAddAll(@NonNull Collection collection) { - super.addAll(collection); + try { + super.addAll(collection); + } catch (UnsupportedOperationException e) { + KMLog.LogException(TAG, "_internalAddAll exception ", e); + } } protected void _internalClear() { - super.clear(); + try { + super.clear(); + } catch (UnsupportedOperationException e) { + KMLog.LogException(TAG, "_internalClear exception ", e); + } } // TODO: As needed, override mutation functions so that we can reflect the changes onto diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/logic/ResourcesUpdateTool.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/logic/ResourcesUpdateTool.java index 8b95ce3d9a44c95c70180e5c5e23fd2ead9d4e86..60bae638b8e604cfd90612633644a54bb09dbe55 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/logic/ResourcesUpdateTool.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/logic/ResourcesUpdateTool.java @@ -12,7 +12,6 @@ import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Handler; -import android.util.Log; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; @@ -27,6 +26,7 @@ import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KeyboardEventHandler; import com.tavultesoft.kmea.R; import com.tavultesoft.kmea.data.CloudRepository; +import com.tavultesoft.kmea.util.KMLog; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; @@ -41,7 +41,6 @@ import java.util.concurrent.atomic.AtomicInteger; import org.json.JSONException; import org.json.JSONObject; - public class ResourcesUpdateTool implements KeyboardEventHandler.OnKeyboardDownloadEventListener, CloudRepository.UpdateHandler{ private static final String TAG = "ResourceUpdateTool"; @@ -148,7 +147,7 @@ public class ResourcesUpdateTool implements KeyboardEventHandler.OnKeyboardDownl channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this - NotificationManager notificationManager = aContext.getSystemService(NotificationManager.class); + NotificationManager notificationManager = (NotificationManager) aContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); } } @@ -276,9 +275,9 @@ public class ResourcesUpdateTool implements KeyboardEventHandler.OnKeyboardDownl private void addOpenUpdate(Bundle theResourceBundle) { String langid = theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_LANG_ID); - boolean downloadOnlyLexicalModel = theResourceBundle.containsKey(KMKeyboardDownloaderActivity.ARG_MODEL_URL) && - theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_URL) != null && - !theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_URL).isEmpty(); + boolean downloadOnlyLexicalModel = theResourceBundle.containsKey(KMKeyboardDownloaderActivity.ARG_MODEL_ID) && + theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_ID) != null && + !theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_ID).isEmpty(); if (downloadOnlyLexicalModel) { String modelid = theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_ID); @@ -325,7 +324,7 @@ public class ResourcesUpdateTool implements KeyboardEventHandler.OnKeyboardDownl } } } catch (JSONException e) { - Log.e(TAG, "JSON Exception parsing ignoreNotifications preference"); + KMLog.LogException(TAG, "JSON Exception parsing ignoreNotifications preference", e); } } @@ -366,7 +365,7 @@ public class ResourcesUpdateTool implements KeyboardEventHandler.OnKeyboardDownl editor.putString(PREF_KEY_IGNORE_NOTIFICATIONS, ignoredNotificationsObj.toString()); editor.commit(); } catch (JSONException e) { - Log.e(TAG, "JSON Exception updating ignoreNotifications preference"); + KMLog.LogException(TAG, "JSON Exception updating ignoreNotifications preference", e); } } @@ -379,9 +378,9 @@ public class ResourcesUpdateTool implements KeyboardEventHandler.OnKeyboardDownl String langid = theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_LANG_ID); String langName = theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_LANG_NAME); - boolean downloadOnlyLexicalModel = theResourceBundle.containsKey(KMKeyboardDownloaderActivity.ARG_MODEL_URL) && - theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_URL) != null && - !theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_URL).isEmpty(); + boolean downloadOnlyLexicalModel = theResourceBundle.containsKey(KMKeyboardDownloaderActivity.ARG_MODEL_ID) && + theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_ID) != null && + !theResourceBundle.getString(KMKeyboardDownloaderActivity.ARG_MODEL_ID).isEmpty(); int notification_id = this.notificationid.incrementAndGet(); @@ -428,6 +427,7 @@ public class ResourcesUpdateTool implements KeyboardEventHandler.OnKeyboardDownl .setContentTitle(currentContext.getString(R.string.keyboard_updates_available)) .setContentText(message) .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .setAutoCancel(true) .setContentIntent(startUpdateIntent) .setOngoing(true); @@ -522,7 +522,15 @@ public class ResourcesUpdateTool implements KeyboardEventHandler.OnKeyboardDownl @Override public void onPackageInstalled(List> keyboardsInstalled) { - // Do nothing + if (! openUpdates.isEmpty() && keyboardsInstalled != null) { + for (Map k : keyboardsInstalled) { + String _langid = k.get(KMManager.KMKey_LanguageID); + String _kbid = k.get(KMManager.KMKey_KeyboardID); + removeOpenUpdate(createKeyboardId(_langid, _kbid)); + } + } + + tryFinalizeUpdate(); } @Override diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/JSONUtils.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/JSONUtils.java index a233269d4cbad26b5d73d8ebe54a6d0056b719c8..1d36e9c580ede2cb6ab68d904e8cfe283f5df29a 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/JSONUtils.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/JSONUtils.java @@ -10,6 +10,7 @@ import java.util.Map; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.util.FileUtils; import com.tavultesoft.kmea.JSONParser; +import com.tavultesoft.kmea.util.KMLog; import org.json.JSONArray; import org.json.JSONException; @@ -72,7 +73,6 @@ public class JSONUtils { kbdObj.put(KMManager.KMKey_Name, kbdName); kbdObj.put("filename", kbdFilename); kbdObj.put(KMManager.KMKey_KeyboardVersion, kbdVersion); - kbdObj.put(KMManager.KMKey_CustomKeyboard, "Y"); if (kmpKeyboardObj.has(KMManager.KMKey_DisplayFont)) { kbdObj.put(KMManager.KMKey_Font, kmpKeyboardObj.getString(KMManager.KMKey_DisplayFont)); } @@ -113,7 +113,7 @@ public class JSONUtils { } } } catch (JSONException e) { - Log.e(TAG, "getLanguages() Error parsing " + file.getName()); + KMLog.LogException(TAG, "getLanguages() Error parsing " + file.getName(), e); } } } @@ -144,7 +144,7 @@ public class JSONUtils { } } } catch (JSONException e) { - Log.e(TAG, "find ID() error: " + e); + KMLog.LogException(TAG, "find ID() error: ", e); } return ret; } @@ -167,7 +167,7 @@ public class JSONUtils { } } } catch (JSONException e) { - Log.e(TAG, "findHelp() error: " + e); + KMLog.LogException(TAG, "findHelp() error: ", e); } return false; } @@ -192,7 +192,7 @@ public class JSONUtils { options.put("fontBaseUri", "https://s.keyman.com/font/deploy/"); options.put("keyboardVersion", "current"); } catch (JSONException e) { - Log.e(TAG, "defaultOptions() error: " + e); + KMLog.LogException(TAG, "defaultOptions() error: ", e); } return options; } @@ -237,7 +237,6 @@ public class JSONUtils { modelObj.put(KMManager.KMKey_Name, modelName); modelObj.put("filename", modelFilename); modelObj.put(KMManager.KMKey_LexicalModelVersion, packageVersion); - modelObj.put(KMManager.KMKey_CustomModel, "Y"); if (containsHelp) { File welcomeFile = new File(pkg, "welcome.htm"); modelObj.put(KMManager.KMKey_CustomHelpLink, welcomeFile.getPath()); @@ -275,7 +274,7 @@ public class JSONUtils { } } } catch (JSONException e) { - Log.e(TAG, "getLexicalModels() Error parsing " + file.getName()); + KMLog.LogException(TAG, "getLexicalModels() Error parsing " + file.getName(), e); } } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/LexicalModelPackageProcessor.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/LexicalModelPackageProcessor.java index 430c20d4e4bfdfe2787951db2e50ed6d99394c22..77373e3485eadb757f73144371cca75b9f8563b6 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/LexicalModelPackageProcessor.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/LexicalModelPackageProcessor.java @@ -10,6 +10,7 @@ import org.json.JSONObject; import java.io.File; import java.io.FileFilter; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -58,7 +59,7 @@ public class LexicalModelPackageProcessor extends PackageProcessor { return false; } - public Map[] processEntry(JSONObject jsonEntry, String packageId, String packageVersion, String languageID) throws JSONException { + public Map[] processEntry(JSONObject jsonEntry, String packageId, String packageVersion, ArrayList languageList) throws JSONException { JSONArray languages = jsonEntry.getJSONArray("languages"); String modelId = jsonEntry.getString("id"); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/PackageProcessor.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/PackageProcessor.java index 75e4ac086c7f8aec5a76a067c84a9138a9a5ac0d..1be36d8b2b8914079c9ac31b1de0ddfda9ea3b9b 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/PackageProcessor.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/packages/PackageProcessor.java @@ -1,11 +1,16 @@ +/** + * Copyright (C) 2017-2020 SIL International. All rights reserved. + */ package com.tavultesoft.kmea.packages; import androidx.annotation.NonNull; -import android.util.Log; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.JSONParser; +import com.tavultesoft.kmea.data.Keyboard; +import com.tavultesoft.kmea.data.KeyboardController; import com.tavultesoft.kmea.util.FileUtils; +import com.tavultesoft.kmea.util.KMLog; import com.tavultesoft.kmea.util.ZipUtils; import java.io.File; @@ -13,6 +18,8 @@ import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -21,13 +28,11 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -/** - * Created by joshua on 12/7/2017. - */ - /** * A class for use in handling Keyman's .kmp package file format, as it relates to the * KMEA engine. This is primarily for installing keyboard packages. + * Some utility methods are available for parsing the kmp.json before the .kmp file has been extracted. + * Other utilities assume the package file has already been extracted to the file system. */ public class PackageProcessor { protected File resourceRoot = null; @@ -35,6 +40,7 @@ public class PackageProcessor { public static final String PP_DEFAULT_VERSION = "1.0"; public static final String PP_DEFAULT_METADATA = "kmp.json"; + // Package target types public static final String PP_TARGET_INVALID = "invalid"; public static final String PP_TARGET_KEYBOARDS = "keyboards"; public static final String PP_TARGET_LEXICAL_MODELS = "lexicalModels"; @@ -42,6 +48,7 @@ public class PackageProcessor { // keys in kmp.json public static final String PP_KEYBOARDS_KEY = "keyboards"; public static final String PP_LEXICAL_MODELS_KEY = "lexicalModels"; + public static final String PP_LANGUAGES_KEY = "languages"; private static final String TAG = "PackageProcessor"; @@ -115,6 +122,28 @@ public class PackageProcessor { return tempKeyboardPath; } + /** + * Given temp path of extracted keyboard package kmp file and package ID, + * move the tempPath to the permanent packages/ folder + * @param tempPath Filepath of temporarily extracted .kmp file + * @param packageID String of the package ID + */ + public void moveTempToPackages(File tempPath, String packageID) { + File permPath = new File(resourceRoot, KMManager.KMDefault_AssetPackages + File.separator + packageID + File.separator); + try { + if (permPath.exists()) { + // Out with the old. "In with the new" is identical to a new package installation. + FileUtils.deleteDirectory(permPath); + } + } catch (IOException e) { + + } + // No version conflict! Proceed with the install! + // Unfortunately, the nice recursive method provided by Apache Commons-IO's FileUtils class + // isn't available at Android runtime. + tempPath.renameTo(permPath); + } + /** * Given a directory location for an extracted KMP file, extracts its kmp.json information * into a JSON object. Works on temporary directories and the installed package directory. @@ -128,7 +157,7 @@ public class PackageProcessor { JSONParser parser = new JSONParser(); return parser.getJSONObjectFromFile(infoFile); } else { - Log.e(TAG, "kmp.json does not exist"); + KMLog.LogError(TAG, "kmp.json does not exist"); return null; } } @@ -141,47 +170,61 @@ public class PackageProcessor { * @param jsonEntry One entry of the master JSONArray of the top-level "keyboards" property. * @param packageId Package ID * @param packageVersion Package version (used for lexical model version) - * @param languageID Preferred language ID to associate with the entry. If not found, + * @param languageList List of preferred language IDs to associate with the entry. If null, * the first language in kmp.json is used. * @return A list of maps defining one keyboard-language pairing each. * @throws JSONException */ - public Map[] processEntry(JSONObject jsonEntry, String packageId, String packageVersion, String languageID) throws JSONException { - JSONArray languages = jsonEntry.getJSONArray("languages"); + public Map[] processEntry(JSONObject jsonEntry, String packageId, String packageVersion, ArrayList languageList) throws JSONException { + JSONArray languages = jsonEntry.getJSONArray(PP_LANGUAGES_KEY); + int preferredLanguageCount = (languageList != null & !languageList.isEmpty()) ? languageList.size() : 1; + String defaultLanguageID = languages.getJSONObject(0).getString("id"); + if (languageList == null || languageList.isEmpty()) { + languageList = new ArrayList(); + languageList.add(defaultLanguageID); + } + String keyboardId = jsonEntry.getString("id"); if (touchKeyboardExists(packageId, keyboardId)) { - HashMap[] keyboards = new HashMap[1]; + HashMap[] keyboards = new HashMap[preferredLanguageCount]; + boolean firstLanguageAdded = false; int i=0; - keyboards[i] = new HashMap<>(); - keyboards[i].put(KMManager.KMKey_PackageID, packageId); - keyboards[i].put(KMManager.KMKey_KeyboardName, jsonEntry.getString("name")); - keyboards[i].put(KMManager.KMKey_KeyboardID, jsonEntry.getString("id")); - - int languageIndex = JSONUtils.findID(languages, languageID); - if (languageIndex == -1) { - // languageID not found so use first language - languageIndex = 0; - } - keyboards[i].put(KMManager.KMKey_LanguageID, languages.getJSONObject(languageIndex).getString("id").toLowerCase()); - keyboards[i].put(KMManager.KMKey_LanguageName, languages.getJSONObject(languageIndex).getString("name")); + for (String languageID : languageList) { + keyboards[i] = new HashMap<>(); + keyboards[i].put(KMManager.KMKey_PackageID, packageId); + keyboards[i].put(KMManager.KMKey_KeyboardName, jsonEntry.getString("name")); + keyboards[i].put(KMManager.KMKey_KeyboardID, jsonEntry.getString("id")); + + int languageIndex = JSONUtils.findID(languages, languageID); + if (languageIndex == -1) { + // languageID not found so use first language + if (!firstLanguageAdded) { + languageIndex = 0; + } else { + continue; + } + } + keyboards[i].put(KMManager.KMKey_LanguageID, languages.getJSONObject(languageIndex).getString("id").toLowerCase()); + keyboards[i].put(KMManager.KMKey_LanguageName, languages.getJSONObject(languageIndex).getString("name")); - keyboards[i].put(KMManager.KMKey_KeyboardVersion, jsonEntry.getString("version")); - if (jsonEntry.has("displayFont")) { - keyboards[i].put(KMManager.KMKey_Font, jsonEntry.getString("displayFont")); - } - if (jsonEntry.has("oskFont")) { - keyboards[i].put(KMManager.KMKey_OskFont, jsonEntry.getString("oskFont")); - } + keyboards[i].put(KMManager.KMKey_KeyboardVersion, jsonEntry.getString("version")); + if (jsonEntry.has("displayFont")) { + keyboards[i].put(KMManager.KMKey_Font, jsonEntry.getString("displayFont")); + } + if (jsonEntry.has("oskFont")) { + keyboards[i].put(KMManager.KMKey_OskFont, jsonEntry.getString("oskFont")); + } + + if (welcomeExists(packageId)) { + File kmpFile = new File(packageId + ".kmp"); + File packageDir = constructPath(kmpFile, false); + File welcomeFile = new File(packageDir, FileUtils.WELCOME_HTM); + // Only storing relative instead of absolute paths as a convenience for unit tests. + keyboards[i].put(KMManager.KMKey_CustomHelpLink, welcomeFile.getPath()); + } - // For now, all KMP distributed keyboards are custom - keyboards[i].put(KMManager.KMKey_CustomKeyboard, "Y"); - if (welcomeExists(packageId)) { - File kmpFile = new File(packageId + ".kmp"); - File packageDir = constructPath(kmpFile, false); - File welcomeFile = new File(packageDir, "welcome.htm"); - // Only storing relative instead of absolute paths as a convenience for unit tests. - keyboards[i].put(KMManager.KMKey_CustomHelpLink, welcomeFile.getPath()); + i++; } return keyboards; @@ -190,52 +233,148 @@ public class PackageProcessor { } } - public static String getKeyboardVersion(JSONObject json, String kbdId) throws JSONException { - JSONArray keyboards = json.getJSONArray("keyboards"); + /** + * Get the language and keyboard information for the keyboard in a keyboard package at a specified index. + * Use placeholders for other fields like help links, and font info. + * @param json kmp.json as a JSON object + * @param packageID String of the keyboard package ID + * @param index int of the keyboard entry + * @return Keyboard info. Null if no keyboard found + */ + public static Keyboard getKeyboard(JSONObject json, String packageID, int index) { + try { + if (!json.has(PP_KEYBOARDS_KEY)) { + return null; + } + JSONObject keyboardObj = json.getJSONArray(PP_KEYBOARDS_KEY).getJSONObject(index); + JSONArray languages = keyboardObj.getJSONArray(PP_LANGUAGES_KEY); + // Just get first language + JSONObject languageObj = languages.getJSONObject(0); + return new Keyboard( + packageID, + keyboardObj.getString("id"), + keyboardObj.getString("name"), + languageObj.getString("id"), + languageObj.getString("name"), + keyboardObj.getString("version"), + null, + null, + true, + null, + null + ); + } catch (JSONException e) { + KMLog.LogException(TAG, "", e); + return null; + } + } - for(int i=0; i < keyboards.length(); i++) { - JSONObject keyboard = keyboards.getJSONObject(i); + /** + * Parse a kmp.json JSON object and return the keyboard count. Lexical model packages return 0 + * @param json kmp.json as a JSON object + * @return int of number of keyboards. 0 if not found + */ + public static int getKeyboardCount(JSONObject json) { + int count = 0; + try { + if (!json.has(PP_KEYBOARDS_KEY)) { + return count; + } + JSONArray keyboards = json.getJSONArray(PP_KEYBOARDS_KEY); + count = keyboards.length(); + } catch (JSONException e) { + KMLog.LogException(TAG, "", e); + } + + return count; + } - if(keyboard.getString("id").equals(kbdId)) { - return keyboard.getString("version"); + /** + * Parse a kmp.json JSON object and return the language count for the specified resource and index + * @param json kmp.json as a JSON object + * @param key PP_KEYBOARDS_KEY or PP_LEXICAL_MODELS_KEY + * @param index int Item number the resource array + * @return int of number of languages. 0 if not found + */ + public static int getLanguageCount(JSONObject json, String key, int index) { + int count = 0; + try { + if ( (key.equals(PP_KEYBOARDS_KEY) && !json.has(PP_KEYBOARDS_KEY)) || + (key.equals(PP_LEXICAL_MODELS_KEY) && !json.has(PP_LEXICAL_MODELS_KEY)) ){ + KMLog.LogError(TAG, "kmp.json doesn't contain " + key); + return count; } + JSONArray resources = json.getJSONArray(key); + JSONArray languages = resources.getJSONObject(index).getJSONArray(PP_LANGUAGES_KEY); + count = languages.length(); + } catch (NullPointerException e) { + KMLog.LogException(TAG, "getLanguageCount with null JSONObject", e); + } catch (JSONException e) { + KMLog.LogException(TAG, "", e); } - return null; + return count; } /** - * Simply extracts the package's name. - * @param json The metadata JSONObject for the package. - * @return The package name (via String) + * Parse a kmp.json JSON object for a given keyboard ID and return the keyboard version + * @param json kmp.json as a JSON object + * @param kbdId String of the keyboard ID + * @return String of the keyboard version + */ + public static String getKeyboardVersion(JSONObject json, String kbdId) { + try { + JSONArray keyboards = json.getJSONArray(PP_KEYBOARDS_KEY); + + for (int i = 0; i < keyboards.length(); i++) { + JSONObject keyboard = keyboards.getJSONObject(i); + + if (keyboard.getString("id").equals(kbdId)) { + return keyboard.getString("version"); + } + } + + return null; + } catch (JSONException e) { + KMLog.LogException(TAG, "", e); + return null; + } + } + + /** + * Parse a kmp.json JSON object and return the package's name. + * @param json kmp.json as a JSON object + * @return String of the package name */ public String getPackageName(JSONObject json) { try { return json.getJSONObject("info").getJSONObject("name").getString("description"); } catch (Exception e) { + KMLog.LogException(TAG, "", e); return ""; } } /** - * Simply extracts the package's version number. + * Parse a kmp.json JSON object and return the package's version number. * If undefined, return default version "1.0" - * @param json The metadata JSONObject for the package. - * @return The version number (via String) + * @param json kmp.json as a JSON object. + * @return String of the package version number */ public static String getPackageVersion(JSONObject json) { try { return json.getJSONObject("info").getJSONObject("version").getString("description"); } catch (Exception e) { + KMLog.LogException(TAG, "", e); return PP_DEFAULT_VERSION; } } /** - * Simply extracts the package's target (keyboards vs lexical models). + * Parse a kmp.json JSON object and return the package's target (keyboards vs lexical models). * Only one can be valid. Otherwise, return "invalid" - * @param json The metadata JSONObject for the package. - * @return String The target ("keyboards", "lexicalModels", or "invalid") + * @param json kmp.json as a JSON object. + * @return String of the package target ("keyboards", "lexicalModels", or "invalid") */ public String getPackageTarget(JSONObject json) { try { @@ -247,6 +386,7 @@ public class PackageProcessor { return PP_TARGET_INVALID; } } catch (Exception e) { + KMLog.LogException(TAG, "", e); return PP_TARGET_INVALID; } } @@ -264,10 +404,32 @@ public class PackageProcessor { FileUtils.deleteDirectory(tempPath); return target; } catch (Exception e) { + KMLog.LogException(TAG, "", e); return PP_TARGET_INVALID; } } + /** + * Parse a kmp.json JSON object and return boolean if the package contains welcome.htm + * @param json kmp.json as a JSON object + * @return boolean + */ + public boolean hasWelcome(JSONObject json) { + try { + JSONArray files = json.getJSONArray("files"); + for (int i=0; itrue if installing would be a downgrade, otherwise false. * @throws IOException * @throws JSONException */ - boolean isDowngrade(File kmpPath, boolean preExtracted) throws IOException, JSONException { + public boolean isDowngrade(File kmpPath, boolean preExtracted) throws IOException, JSONException { return internalCompareKMPVersion(kmpPath, preExtracted,-1); } @@ -406,14 +568,146 @@ public class PackageProcessor { return false; } + /** + * Generates a list of Keyboards from the keyboard JSONObject. baseKeyboard contains + * keyboard information that's already installed. list is sorted by language name + * @param keyboardJSON JSONObject - Keyboard JSONObject from kmp.json (entry for keyboardID) + * @param baseKeyboard Keyboard - information of the keyboard that's already installed + * @param excludeInstalledLanguages - boolean whether to exclude languages that are already installed + * @return List + */ + private List getKeyboards(JSONObject keyboardJSON, Keyboard baseKeyboard, + boolean excludeInstalledLanguages ) { + List list = new ArrayList(); + String packageID = baseKeyboard.getPackageID(); + String keyboardID = baseKeyboard.getKeyboardID(); + try { + JSONArray languages = keyboardJSON.getJSONArray(PP_LANGUAGES_KEY); + for (int j = 0; j < languages.length(); j++) { + JSONObject language = languages.getJSONObject(j); + String languageID = language.getString("id"); + String languageName = language.getString("name"); + if (!excludeInstalledLanguages || + !(KeyboardController.getInstance().keyboardExists(packageID, keyboardID, languageID))) { + // Copy keyboard info and update language + Keyboard newKeyboard = new Keyboard(baseKeyboard); + newKeyboard.setLanguage(languageID, languageName); + list.add(newKeyboard); + } + } + } catch (Exception e) { + KMLog.LogException(TAG, "getKeyboards() ", e); + } + Collections.sort(list, new LanguageNameSorter()); + return list; + } + + /** + * Get a list of available keyboard and language pairings that are available to add. + * Keyboard list sorted by language name + * (parses the kmp.json for the language list) + * @param infoJSON - kmp.json as a JSON object + * @param packageID - String of the package ID + * @param keyboardID - String of the keyboard ID + * @param tempPath - Boolean whether the kmp.json file is in a temporary location. If true, + * don't use KeyboardController to determine a base keyboard. + * @param excludeInstalledLanguages - Boolean whether to exclude + * installed languages from the returned list. + * @return List of based on kmp.json. If excludeInstalledLanguages is true, this list + * excludes languages already installed + */ + public List getKeyboardList(JSONObject infoJSON, String packageID, String keyboardID, + boolean tempPath, boolean excludeInstalledLanguages) { + List list = new ArrayList(); + try { + JSONArray keyboards = infoJSON.getJSONArray(PP_KEYBOARDS_KEY); + + for (int i = 0; i < keyboards.length(); i++) { + JSONObject keyboard = keyboards.getJSONObject(i); + if (tempPath) { + // temporary path for kmp.json so don't use KeyboardController to get the base keyboard. + if (i==0) { + // Create a "baseKeyboard" for the language picker menu. Don't need full keyboard info... + Keyboard baseKeyboard = getKeyboard(infoJSON, packageID, 0); + return getKeyboards(keyboard, baseKeyboard, excludeInstalledLanguages); + } + } + else if (keyboardID != null && keyboardID.equals(keyboard.getString("id"))) { + // Find the keyboard already installed. We'll use it as the base + // for creating new keyboards + int baseKeyboardIndex = KeyboardController.getInstance().getKeyboardIndex(packageID, keyboardID, ""); + if (baseKeyboardIndex == KeyboardController.INDEX_NOT_FOUND) { + continue; + } + Keyboard baseKeyboard = KeyboardController.getInstance().getKeyboardInfo(baseKeyboardIndex); + return getKeyboards(keyboard, baseKeyboard, excludeInstalledLanguages); + } + } + } catch (Exception e) { + KMLog.LogException(TAG, "getKeyboardList() ", e); + } + return list; + } + + /** + * Parses installed kmp.json to get a specified keyboard with an associated language. If languageID not + * provided, return the keyboard with the first associated language. + * This differs from getKeyboardList because this method doesn't search through + * KeyboardController (installed keyboards) + * @param packageID String of the package ID + * @param keyboardID String of the keyboard ID + * @param languageID String of the language ID + * @return object + */ + public Keyboard getKeyboard(String packageID, String keyboardID, String languageID) { + File packagePath = new File(resourceRoot, KMManager.KMDefault_AssetPackages + File.separator + packageID); + Keyboard kbd = null; + JSONObject infoJSON = loadPackageInfo(packagePath); + String packageVersion = getPackageVersion(infoJSON); + + ArrayList languageList = new ArrayList(); + if (languageID != null && !languageID.isEmpty()) { + languageList.add(languageID); + } + try { + JSONArray keyboards = infoJSON.getJSONArray(PP_KEYBOARDS_KEY); + + for (int i=0; i < keyboards.length(); i++) { + JSONObject keyboard = keyboards.getJSONObject(i); + if (keyboardID.equals(keyboard.getString("id"))) { + Map[] maps = processEntry(keyboard, packageID, packageVersion, languageList); + if (maps != null) { + // Only returning first keyboard map + kbd = new Keyboard( + maps[0].get(KMManager.KMKey_PackageID), + maps[0].get(KMManager.KMKey_KeyboardID), + maps[0].get(KMManager.KMKey_KeyboardName), + maps[0].get(KMManager.KMKey_LanguageID), + maps[0].get(KMManager.KMKey_LanguageName), + maps[0].get(KMManager.KMKey_KeyboardVersion), + maps[0].get(KMManager.KMKey_CustomHelpLink), // can be null + "", + false, + maps[0].get(KMManager.KMKey_Font), + maps[0].get(KMManager.KMKey_OskFont)); + } + } + } + } catch (Exception e) { + KMLog.LogException(TAG, "getKeyboard() ", e); + } + return kbd; + } + /** * The master KMP processing method; use after a .kmp download to fully install within the filesystem. * This will overwrite an existing package. * @param path Filepath of a newly downloaded .kmp file. * @param tempPath Filepath of temporarily extracted .kmp file * @param key String of jsonArray to iterate through ("keyboards" or "lexicalModels") - * @param languageID String of the preferred language ID to associate with the entry. If languageID is null or - * not found in kmp.json, then the first entry will be added. + * @param languageList List of the preferred language ID to associate with the entry. If languageList is null or empty or + * not found in kmp.json, then the first language will be added. The languageList is + * only used for the first keyboard in a package. * @return A list of data maps of the newly installed and/or newly upgraded entries found in the package. * May be empty if the package file is actually an old version. *

@@ -422,7 +716,7 @@ public class PackageProcessor { * @throws IOException * @throws JSONException */ - public List> processKMP(File path, File tempPath, String key, String languageID) throws IOException, JSONException { + public List> processKMP(File path, File tempPath, String key, ArrayList languageList) throws IOException, JSONException { // Block reserved namespaces, like /cloud/. // TODO: Consider throwing an exception instead? ArrayList> specs = new ArrayList<>(); @@ -456,13 +750,32 @@ public class PackageProcessor { JSONArray entries = newInfoJSON.getJSONArray(key); for (int i = 0; i < entries.length(); i++) { - Map[] maps = processEntry(entries.getJSONObject(i), packageId, packageVersion, languageID); + Map[] maps; + ArrayList preferredLanguageList; + JSONArray languages = entries.getJSONObject(i).getJSONArray(PP_LANGUAGES_KEY); + if (i == 0 && key.equalsIgnoreCase(PP_KEYBOARDS_KEY) && languageList != null && !languageList.isEmpty()) { + preferredLanguageList = languageList; + } else { + preferredLanguageList = new ArrayList(); + + if (key.equalsIgnoreCase(PP_LEXICAL_MODELS_KEY)) { + // Use the entire language list for lexical model packages + for (int j = 0; j < languages.length(); j++) { + preferredLanguageList.add(languages.getJSONObject(j).getString("id")); + } + } else { + // Just add the first language + preferredLanguageList.add(languages.getJSONObject(0).getString("id")); + } + } + + maps = processEntry(entries.getJSONObject(i), packageId, packageVersion, preferredLanguageList); if (maps != null) { specs.addAll(Arrays.asList(maps)); } } } else { - Log.e(TAG, path.getName() + " must contain \"" + key + "\""); + KMLog.LogError(TAG, path.getName() + " must contain \"" + key + "\""); } return specs; } @@ -470,4 +783,15 @@ public class PackageProcessor { public List> processKMP(File path, File tempPath, String key) throws IOException, JSONException { return processKMP(path, tempPath, key, null); } + + /** + * Comparator to sort Keyboard list by language name + */ + private class LanguageNameSorter implements Comparator { + @Override + public int compare(Keyboard k1, Keyboard k2) { + return k1.getLanguageName().compareTo(k2.getLanguageName()); + } + } + } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/BCP47.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/BCP47.java new file mode 100644 index 0000000000000000000000000000000000000000..7e396dc55161651d283f37fa3f3f3ea7bdba5bbd --- /dev/null +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/BCP47.java @@ -0,0 +1,21 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ + +package com.tavultesoft.kmea.util; + +public final class BCP47 { + /** + * Utility to compare two language ID strings + * @param id1 Language ID 1 + * @param id2 Language ID 2 + * @return true if the two strings are case-insensitive equal + */ + public static boolean languageEquals(String id1, String id2) { + if (id1 == null || id2 == null) { + return false; + } + + return id1.equalsIgnoreCase(id2); + } +} \ No newline at end of file diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/CharSequenceUtil.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/CharSequenceUtil.java index 717ffbdc970053455b0b5e17742cd18ed4b047b5..d2f952bfe9435d2324f76de1ff3a1165ef0e683d 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/CharSequenceUtil.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/CharSequenceUtil.java @@ -1,7 +1,5 @@ package com.tavultesoft.kmea.util; -import android.util.Log; - import java.lang.CharSequence; public final class CharSequenceUtil { @@ -31,7 +29,7 @@ public final class CharSequenceUtil { } while ((lastIndex - counter >= 0) && (counter < dn) && (numPairs < dn)); return numPairs; } catch (Exception e) { - Log.e(TAG, "Error in countSurrogatePairs: " + e); + KMLog.LogException(TAG, "Error in countSurrogatePairs: ", e); return numPairs; } } @@ -60,7 +58,7 @@ public final class CharSequenceUtil { } return charsToRestore; } catch (Exception e) { - Log.e(TAG, "Error in restoreChars: " + e); + KMLog.LogException(TAG, "Error in restoreChars: ", e); return charsToRestore; } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/Connection.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/Connection.java index 645633121653a747fe456ccac2a6d64423f0e18a..2fcc449df0d12e5a62a832b956e8b750c67c5f5f 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/Connection.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/Connection.java @@ -1,13 +1,12 @@ package com.tavultesoft.kmea.util; -import android.util.Log; - import java.io.InputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public final class Connection { + private static final String TAG = "Connection"; private static final int MAX_REDIRECTS = 5; private static final int TIMEOUT = 20 * 1000; // seconds @@ -30,7 +29,7 @@ public final class Connection { return urlConnection.getInputStream(); } } catch (IOException e) { - Log.e("Connection", "getInputStream failed: " + e); + KMLog.LogException(TAG, "getInputStream failed: ", e); } return urlConnection.getErrorStream(); }; @@ -101,7 +100,7 @@ public final class Connection { } } } catch (Exception e) { - Log.e("Connection", "Initialization failed:" + e); + KMLog.LogException(TAG, "Initialization failed:", e); } return ret; diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/DownloadIntentService.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/DownloadIntentService.java index 7d87b0802509808b544545905349616aaa794211..03e821829906964b9c689eacd7e4594a72bed327 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/DownloadIntentService.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/DownloadIntentService.java @@ -6,7 +6,7 @@ import android.os.Bundle; import android.os.ResultReceiver; public class DownloadIntentService extends IntentService { - + private static final String TAG = "DownloadIntentSvc"; public DownloadIntentService() { super(DownloadIntentService.class.getName()); @@ -33,6 +33,7 @@ public class DownloadIntentService extends IntentService { } } catch (Exception e) { receiver.send(FileUtils.DOWNLOAD_ERROR, Bundle.EMPTY); + KMLog.LogException(TAG, "", e); } } } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/FileUtils.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/FileUtils.java index 69c31be4ea2e8652c998c79db5fdd0e145f1ea8a..4eb3def4c3c2419f4ce255c49ca605e643fef0da 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/FileUtils.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/FileUtils.java @@ -1,10 +1,12 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ package com.tavultesoft.kmea.util; import android.content.Context; -import android.os.Build; -import android.util.Log; -import com.tavultesoft.kmea.KMManager; +import org.json.JSONObject; +import org.json.JSONArray; import java.io.BufferedInputStream; import java.io.File; @@ -12,9 +14,10 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.ObjectOutputStream; import java.io.OutputStream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; /** * Limitations: @@ -23,6 +26,7 @@ import java.util.regex.Pattern; * This might be usable once we can upgrade to Android Oreo */ public final class FileUtils { + public static final String TAG = "FileUtils"; public static final int DOWNLOAD_ERROR = -1; public static final int DOWNLOAD_SUCCESS = 1; @@ -109,8 +113,8 @@ public final class FileUtils { ret = DOWNLOAD_SUCCESS; } } catch (Exception e) { + KMLog.LogException(TAG, "Download failed! Error: ", e); ret = -1; - Log.e("FileUtils", "Download failed! Error: " + e); } finally { if (ret > 0) { if (tmpFile.exists() && tmpFile.length() > 0) { @@ -130,7 +134,7 @@ public final class FileUtils { if (tmpFile != null && tmpFile.exists()) { tmpFile.delete(); } - Log.e("FileUtils", "Could not download filename " + filename); + KMLog.LogError(TAG, "Could not download filename " + filename); } Connection.disconnect(); @@ -213,6 +217,36 @@ public final class FileUtils { } } + /** + * Write obj Object to filepath + * @param File path to filename to write + * @param obj JSONObject or JSONArray to save + * @return boolean if the save was successful + */ + public static boolean saveList(File filepath, Object obj) { + boolean result = false; + final int INDENT = 2; // 2 spaces indent + try { + OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream(filepath), StandardCharsets.UTF_8); + if (obj instanceof JSONObject) { + outputStream.write(((JSONObject)obj).toString(INDENT)); + result = true; + } else if (obj instanceof JSONArray) { + outputStream.write(((JSONArray) obj).toString(INDENT)); + result = true; + } else { + KMLog.LogError(TAG, "saveList failed. arr not JSONObject or JSONArray"); + } + outputStream.flush(); + outputStream.close(); + } catch (Exception e) { + KMLog.LogException(TAG, "saveList failed to save " + filepath.getName() + ". Error: ", e); + result = false; + } + + return result; + } + /** * Utility to parse a URL and extract the filename * @param urlStr String @@ -229,57 +263,6 @@ public final class FileUtils { return filename; } - /** - * Utility to parse a URL and determine if it's a custom keyboard - * @param u String of the URL - * @return boolean false if URL matches [*.]keyman.com/ - */ - public static boolean isCustomKeyboard(String u) { - boolean ret = true; - if (u == null) { - return ret; - } - String lowerU = u.toLowerCase(); - Pattern pattern = Pattern.compile("^http(s)?://(.+\\.)?keyman.com/.*"); - Matcher matcher = pattern.matcher(lowerU); - if (matcher.matches()) { - ret = false; - } - return ret; - } - - /** - * Utility to parse a URL and determine if it's a valid keyman: - * Currently, only "keyman" scheme with "download" path and query is supported. - * Legacy keyman:// protocol is deprecated and not supported. - * @param u String of the URL - * @return boolean true if URL is a supported Keyman link - */ - public static boolean isKeymanLink(String u) { - boolean ret = false; - if (u == null) { - return ret; - } - String lowerU = u.toLowerCase(); - Pattern pattern = Pattern.compile("^keyman:(\\w+)\\?(.+)"); - Matcher matcher = pattern.matcher(lowerU); - // Check URL starts with "keyman" - if (matcher.matches() && (matcher.group(1) != null)) { - // For now, only handle "download" - switch (matcher.group(1).toLowerCase()) { - case "download": - if (matcher.group(2) != null) { - // Contains query - ret = true; - } - break; - default: - ret = false; - } - } - return ret; - } - /** * Utility to compare two version strings * @param v1 String @@ -414,7 +397,7 @@ public final class FileUtils { int i = Integer.parseInt(s); retVal = new Integer(i); } catch (Exception e) { - Log.e("FileUtils", "parseInteger Error: " + e); + KMLog.LogException(TAG, "parseInteger Error: ", e); retVal = null; } diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/HelpFile.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/HelpFile.java index 588a7546db922d0d4192140de13c6c44285fd0e4..7a90a7f7b1f0e49e2a47045b563d44a1fced32c0 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/HelpFile.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/HelpFile.java @@ -5,7 +5,6 @@ import android.content.ClipDescription; import android.content.Context; import android.content.Intent; import android.net.Uri; -import android.util.Log; import android.widget.Toast; import androidx.core.content.FileProvider; @@ -17,7 +16,6 @@ import com.tavultesoft.kmea.util.FileUtils; import java.io.File; import java.io.FileFilter; - public final class HelpFile { private static final String TAG = "HelpFile"; private static final String[] ASSET_MIME_TYPES = { @@ -78,7 +76,7 @@ public final class HelpFile { } catch (NullPointerException e) { String message = "FileProvider undefined in app to load" + customHelp.toString(); Toast.makeText(context, message, Toast.LENGTH_LONG).show(); - Log.e(TAG, message); + KMLog.LogException(TAG, message, e); } } else { i.setData(Uri.parse(helpFile)); diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/KMLog.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/KMLog.java new file mode 100644 index 0000000000000000000000000000000000000000..b6cc7ec719845542226dae30823228bcb0dce0c6 --- /dev/null +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/KMLog.java @@ -0,0 +1,72 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ + +package com.tavultesoft.kmea.util; + +import android.util.Log; +import io.sentry.core.Sentry; +import io.sentry.core.SentryLevel; + +public final class KMLog { + private static final String TAG = "KMLog"; + + /** + * Utility to log error and send to Sentry + * @param tag String of the caller + * @param msg String of the error message + */ + public static void LogError(String tag, String msg) { + if (msg != null && !msg.isEmpty()) { + Log.e(tag, msg); + + if (Sentry.isEnabled()) { + Sentry.captureMessage(msg, SentryLevel.ERROR); + } + } + } + + /** + * Utility to log exceptions and send to Sentry + * @param tag String of the caller + * @param msg String of the exception message + * @param e Throwable exception + */ + public static void LogException(String tag, String msg, Throwable e) { + if (msg != null && !msg.isEmpty()) { + Log.e(tag, msg + "\n" + e); + } else if (e != null) { + Log.e(tag, e.getMessage(), e); + } + + if (Sentry.isEnabled()) { + if (msg != null && !msg.isEmpty()) { + Sentry.addBreadcrumb(msg); + } + Sentry.captureException(e); + } + } + + /** + * Utility to print an Object in the log exception sent to Sentry + * @param tag String of the caller + * @param msg String of the exception message + * @param objName String of the object name + * @param obj Object which will be formatted as a string + * @param e Throwable exception + */ + public static void LogExceptionWithData(String tag, String msg, + String objName, Object obj, Throwable e) { + if (obj != null && Sentry.isEnabled()) { + String objStr = null; + try { + objStr = obj.toString(); + Sentry.setExtra(objName, objStr); + } catch (Exception innerE) { + LogException(TAG, "Sentry.setExtra failed for " + objName, innerE); + } + // Report the original exception + LogException(tag, msg, e); + } + } +} diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/KMPLink.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/KMPLink.java new file mode 100644 index 0000000000000000000000000000000000000000..5086b9d8b6ebb50d6543dd2a11781d8913205efd --- /dev/null +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/KMPLink.java @@ -0,0 +1,133 @@ +/** + * Copyright (C) 2020 SIL International. All rights reserved. + */ +package com.tavultesoft.kmea.util; + +import android.net.Uri; +import android.os.Build; + +import com.tavultesoft.kmea.BuildConfig; +import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; +import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.KMManager.Tier; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Utilities for parsing keyboard install and keyboard download URLs + */ +public final class KMPLink { + + public static final String KMP_PRODUCTION_HOST = "keyman.com"; + public static final String KMP_STAGING_HOST = "keyman-staging.com"; + + private static final String KMP_INSTALL_KEYBOARDS_PATTERN_FORMATSTR = "^http(s)?://(%s|%s)/keyboards/install/([^\\?/]+)(\\?(.+))?$"; + private static final String installPatternFormatStr = String.format(KMP_INSTALL_KEYBOARDS_PATTERN_FORMATSTR, + KMP_PRODUCTION_HOST, + KMP_STAGING_HOST); + private static final Pattern installPattern = Pattern.compile(installPatternFormatStr); + + // Keyman 14.0+ keyboard download links from Keyman server + private static final String KMP_DOWNLOAD_KEYBOARDS_PATTERN_FORMATSTR = "^https://(%s|%s)(/go/package/download/)(\\w+)(\\?platform=android&tier=(alpha|beta|stable))(&bcp47=)?(.+)?"; + private static final String downloadPatternFormatStr = String.format(KMP_DOWNLOAD_KEYBOARDS_PATTERN_FORMATSTR, + KMP_PRODUCTION_HOST, + KMP_STAGING_HOST); + private static final Pattern downloadPattern = Pattern.compile(downloadPatternFormatStr); + + // Keyman 14.0+ generated URL for keyboard download links + private static final String KMP_DOWNLOAD_KEYBOARDS_FORMATSTR = "https://%s/go/package/download/%s"; + + /** + * Check if a URL is a valid Keyman keyboard install link with a packageID + * @param url String of the URL to parse + * @return boolean + */ + public static boolean isKeymanInstallLink(String url) { + boolean status = false; + if (url == null || url.isEmpty()) { + return status; + } + Matcher matcher = installPattern.matcher(url); + if (matcher.matches() && matcher.group(3) != null) { + status = true; + } + + return status; + } + + /** + * Check if a URL is a valid Keyman keyboard download KMP link + * @param url String of the URL to parse + * @return boolean + */ + public static boolean isKeymanDownloadLink(String url) { + boolean status = false; + if (url == null || url.isEmpty()) { + return status; + } + Matcher matcher = downloadPattern.matcher(url); + if (matcher.matches()) { + status = true; + } + + return status; + } + + /** + * Get the keyman.com host (production vs staging) based on the tier + * @return String of keyman.com host + */ + public static String getHost() { + switch (KMManager.getTier(BuildConfig.VERSION_NAME)) { + case ALPHA: + case BETA: + return KMP_STAGING_HOST; + default: + return KMP_PRODUCTION_HOST; + } + } + + /** + * Parses a URL and generates the Keyman keyboard download link. URL contains: + * host (required) + * packageID (required) + * tier (optional) + * BCP 47 languageID (optional) + * @param url String of the URL to parse + * @return Uri of the Keyman keyboard download link + */ + public static Uri getKeyboardDownloadLink(String url) { + Uri uri = null; + + if (url == null || url.isEmpty()) { + return uri; + } + + Matcher matcher = installPattern.matcher(url); + // Validate deep link with package ID and optional bcp47 tag + if (matcher.matches() && matcher.group(3) != null) { + String host = matcher.group(2); + String packageID = matcher.group(3); + String tier = KMManager.getTier(BuildConfig.VERSION_NAME).toString().toLowerCase(); + Uri installUri = Uri.parse(url); + String languageID = installUri.getQueryParameter(KMKeyboardDownloaderActivity.KMKey_BCP47); + + String downloadURL = String.format(KMP_DOWNLOAD_KEYBOARDS_FORMATSTR, + host, + packageID); + uri = Uri.parse(downloadURL) + .buildUpon() + .appendQueryParameter(KMKeyboardDownloaderActivity.KMKey_Platform, "android") + .appendQueryParameter(KMKeyboardDownloaderActivity.KMKey_Tier, tier) + .build(); + if (languageID != null) { + uri = uri.buildUpon() + .appendQueryParameter(KMKeyboardDownloaderActivity.KMKey_BCP47, languageID) + .build(); + } + } + + return uri; + } +} diff --git a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/QRCodeUtil.java b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/QRCodeUtil.java index 0318a9fd15e69d65f8f761f79051327bb1a0964a..c30729aaadaf128b529c47ca3aef419bebe089a7 100644 --- a/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/QRCodeUtil.java +++ b/android/KMEA/app/src/main/java/com/tavultesoft/kmea/util/QRCodeUtil.java @@ -11,7 +11,7 @@ import net.glxn.qrgen.android.QRCode; public final class QRCodeUtil { public static final int DEFAULT_HEIGHT = 800; public static final int DEFAULT_WIDTH = 800; - public static final String QR_BASE = "https://keyman.com/go/keyboard/%s/share"; + public static final String QR_CODE_URL_FORMATSTR = "https://keyman.com/go/keyboard/%s/share"; /** * Generate QR Code as a Bitmap @@ -29,6 +29,7 @@ public final class QRCodeUtil { Class.forName("net.glxn.qrgen.android.QRCode"); return true; } catch (ClassNotFoundException e) { + // Intentionally not sending to Sentry because 3rd party apps may not include this library return false; } } diff --git a/android/KMEA/app/src/main/res/layout/list_toolbar.xml b/android/KMEA/app/src/main/res/layout/list_toolbar.xml index 93ba49a11a7fa1339b2c03884676b5b5d30977ac..2e2050cfaf1fe4c56fb801efbc281fccd8f35342 100644 --- a/android/KMEA/app/src/main/res/layout/list_toolbar.xml +++ b/android/KMEA/app/src/main/res/layout/list_toolbar.xml @@ -17,13 +17,17 @@ android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center" + android:ellipsize="end" + android:singleLine="true" android:text="@string/title_add_keyboard" - android:textSize="16sp" + android:textSize="@dimen/titlebar_label_textsize" android:textStyle="bold" /> + 50dp 205dp + 16sp 34.25dp 49.25dp 21dp diff --git a/android/KMEA/app/src/main/res/values/strings.xml b/android/KMEA/app/src/main/res/values/strings.xml index abeb65b676418367174e02f5e474641b542bfca6..fbdd7f601cee1bf2211f2c0d6d87008bbca2d9d0 100644 --- a/android/KMEA/app/src/main/res/values/strings.xml +++ b/android/KMEA/app/src/main/res/values/strings.xml @@ -7,100 +7,201 @@ KMEA - + Keyboard Keyboards - Add New Keyboard - Add Keyboard from Device - Installed Languages - %1$s Settings - - - Add - Cancel + + + Add New Keyboard + + + Installed Languages + + + %1$s Settings + + + + Add + + + Back + + + Cancel + + Close + + Close Keyman - Download - Install + + Download + + + Install + + Later - OK - Update - - - Cannot connect to Keyman server! - Would you like to delete this keyboard? - Would you like to download the latest version of this keyboard? - Would you like to update keyboards and dictionaries now? - Custom Keyboard - Warning: Font failed to download - Error: Keyboard failed to download + + + Next + + + OK + + + Update + + + + \nCannot connect to Keyman server!\n + + + Would you like to delete this keyboard? + + + Would you like to download the latest version of this keyboard? + + + Would you like to update keyboards and dictionaries now? + + Resource Updates - Resource Updates Available - %1$s (Update Available) + + + Resource Updates Available + + + %1$s (Update Available) + + Updates available for keyboard %1$s: %2$s + + Updates available for dictionary %1$s: %2$s - - Keyboard version - Help link - Uninstall keyboard - new + + + Keyboard version + + + Help link + + + Uninstall keyboard + + + [new] %1$s + + Scan this code to load this\nkeyboard on another device - - Would you like to download the latest version of this dictionary? - The resource catalog is unavailable - - Catalog update started in background - + + Would you like to download the latest version of this dictionary? + + + The resource catalog is unavailable + + + + Catalog update started in background + + + The catalog is still downloading; please try again in a moment! - The catalog is still downloading! - Downloading keyboard started in Background - The selected keyboard is already downloading; please try again in a moment! - Keyboard download is finished! - Downloading dictionary started in Background - The selected dictionary is already downloading; please try again in a moment! - Dictionary download is finished. - - - Failed to access server! - "All resources are up to date!" - - - Dictionary version - Uninstall dictionary - Would you like to delete this dictionary? - - - Enable corrections - Enable predictions - Dictionary + + + The catalog is still downloading! + + + Downloading keyboard started in Background + + + The selected keyboard is already downloading; please try again in a moment! + + + Keyboard download is finished! + + + Downloading dictionary started in Background + + + The selected dictionary is already downloading; please try again in a moment! + + + Dictionary download is finished. + + + + Failed to access server! + + + "All resources are up to date!" + + + + Dictionary version + + + Uninstall dictionary + + + Would you like to delete this dictionary? + + + + %1$s keyboard installed + + + Enable corrections + + + Enable predictions + + + Dictionary + + Dictionary: %1$s - %1$s dictionaries - Manage dictionary - Dictionary installed + + + %1$s dictionaries + + + Manage dictionary + + + Dictionary installed + + (%1$d keyboard) (%1$d keyboards) - + + Image Button + + Image View - - - Delete - - + + + + Delete + + + KMAPreferences - - + + Tap here to change keyboard diff --git a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/KMManagerTest.java b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/KMManagerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9a8f1e88f61f9e6f3ecfb98e5f169a08fd904a70 --- /dev/null +++ b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/KMManagerTest.java @@ -0,0 +1,234 @@ +package com.tavultesoft.kmea; + +import android.util.Log; +import androidx.test.core.app.ApplicationProvider; + +import com.tavultesoft.kmea.data.Keyboard; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +@RunWith(RobolectricTestRunner.class) +public class KMManagerTest { + private static final String TAG = "KMManagerTest"; + private static final File TEST_RESOURCE_ROOT = new File("test_resources", "cloud"); + private static final String OLD_KEYBOARDS_LIST = "old_keyboards_list.dat"; + ArrayList> dat_list; + + @Before + public void loadOldKeyboardsList() throws FileNotFoundException { + KMManager.initialize(ApplicationProvider.getApplicationContext(), KMManager.KeyboardType.KEYBOARD_TYPE_INAPP); + + File keyboards_dat = new File(TEST_RESOURCE_ROOT, OLD_KEYBOARDS_LIST); + if (keyboards_dat == null || !keyboards_dat.exists()) { + throw new FileNotFoundException(); + } + try { + ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(keyboards_dat)); + dat_list = (ArrayList>) inputStream.readObject(); + inputStream.close(); + } catch (Exception e) { + Log.e(TAG, "Exception reading keyboards list"); + } + } + + @Test + public void test_getTier() { + String versionName = "14.0.248-alpha"; + KMManager.Tier tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.ALPHA, tier); + + versionName = "14.0.248-alpha-test"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.ALPHA, tier); + + versionName = "14.0.248-alpha-test-1234"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.ALPHA, tier); + + versionName = "14.0.248-alpha-local"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.ALPHA, tier); + + versionName = "14.0.248-beta"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.BETA, tier); + + versionName = "14.0.248-beta-test"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.BETA, tier); + + versionName = "14.0.248-beta-test-1234"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.BETA, tier); + + versionName = "14.0.248-beta-local"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.BETA, tier); + + versionName = "14.0.248-stable"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.STABLE, tier); + + versionName = "14.0.248-stable-test"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.STABLE, tier); + + versionName = "14.0.248-stable-test-1234"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.STABLE, tier); + + versionName = "14.0.248-stable-local"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.STABLE, tier); + + // If versionName is null or blank, tier based on com.tavultesoft.kmea.BuildConfig.VERSION_NAME + // But we can't test for it. + + // If regex fails, tier is stable + versionName = "14.0.248"; + tier = KMManager.getTier(versionName); + Assert.assertEquals(KMManager.Tier.STABLE, tier); + } + + /* + * This test is manually run to edit/regenerate the old keyboards list + */ + @Ignore + @Test + public void create_newKeyboardsList() { + dat_list = new ArrayList>(); + + HashMap usInfo = new HashMap(); + usInfo.put(KMManager.KMKey_PackageID, "cloud"); + usInfo.put(KMManager.KMKey_KeyboardID, "us"); + usInfo.put(KMManager.KMKey_LanguageID, "en"); + usInfo.put(KMManager.KMKey_KeyboardName, "US"); + usInfo.put(KMManager.KMKey_LanguageName, "English"); + usInfo.put(KMManager.KMKey_KeyboardVersion, "1.0"); + dat_list.add(usInfo); + + HashMap kmInfo = new HashMap(); + kmInfo.put(KMManager.KMKey_PackageID, "khmer_angkor"); + kmInfo.put(KMManager.KMKey_KeyboardID, "khmer_angkor"); + kmInfo.put(KMManager.KMKey_CustomKeyboard, "Y"); + kmInfo.put(KMManager.KMKey_LanguageID, "km"); + kmInfo.put(KMManager.KMKey_KeyboardName, "Khmer Angkor"); + kmInfo.put(KMManager.KMKey_LanguageName, "Central Khmer"); + kmInfo.put(KMManager.KMKey_KeyboardVersion, "1.0.6"); + dat_list.add(kmInfo); + + HashMap europeanInfo = new HashMap(); + europeanInfo.put(KMManager.KMKey_PackageID, "cloud"); + europeanInfo.put(KMManager.KMKey_KeyboardID, "european"); + europeanInfo.put(KMManager.KMKey_LanguageID, "en"); + europeanInfo.put(KMManager.KMKey_KeyboardName, "EuroLatin keyboard"); + europeanInfo.put(KMManager.KMKey_LanguageName, "English"); + europeanInfo.put(KMManager.KMKey_KeyboardVersion, "1.7"); + dat_list.add(europeanInfo); + + HashMap european2Info = new HashMap(); + european2Info.put(KMManager.KMKey_PackageID, "cloud"); + european2Info.put(KMManager.KMKey_KeyboardID, "european2"); + european2Info.put(KMManager.KMKey_LanguageID, "en"); + european2Info.put(KMManager.KMKey_KeyboardName, "European2 Keyboard"); + european2Info.put(KMManager.KMKey_LanguageName, "English"); + european2Info.put(KMManager.KMKey_KeyboardVersion, "1.6"); + dat_list.add(european2Info); + + HashMap ipaInfo = new HashMap(); + // Intentionally leaving package ID undefined + ipaInfo.put(KMManager.KMKey_KeyboardID, "sil_ipa"); + ipaInfo.put(KMManager.KMKey_LanguageID, "und-fonipa"); + ipaInfo.put(KMManager.KMKey_KeyboardName, "IPA (SIL)"); + ipaInfo.put(KMManager.KMKey_LanguageName, "Undetermined"); + ipaInfo.put(KMManager.KMKey_KeyboardVersion, "1.8.1"); + dat_list.add(ipaInfo); + + HashMap eurolatinInfo = new HashMap(); + eurolatinInfo.put(KMManager.KMKey_PackageID, "sil_euro_latin"); + eurolatinInfo.put(KMManager.KMKey_KeyboardID, "sil_euro_latin"); + eurolatinInfo.put(KMManager.KMKey_LanguageID, "en"); + eurolatinInfo.put(KMManager.KMKey_KeyboardName, "EuroLatin (SIL)"); + eurolatinInfo.put(KMManager.KMKey_LanguageName, "English"); + eurolatinInfo.put(KMManager.KMKey_KeyboardVersion, "1.9"); + eurolatinInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont); + dat_list.add(eurolatinInfo); + + try { + File file = new File(TEST_RESOURCE_ROOT, OLD_KEYBOARDS_LIST); + ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file)); + outputStream.writeObject(dat_list); + outputStream.flush(); + outputStream.close(); + } catch (Exception e) { + Log.e(TAG, "Failed to save " + OLD_KEYBOARDS_LIST, e); + } + } + + @Test + public void test_updateOldKeyboardsList() { + Assert.assertNotNull(dat_list); + + // Verify old keyboards list contains deprecated keyboards + HashMap kbInfo = dat_list.get(0); + Assert.assertEquals("us", kbInfo.get(KMManager.KMKey_KeyboardID)); + kbInfo = dat_list.get(2); + Assert.assertEquals("european", kbInfo.get(KMManager.KMKey_KeyboardID)); + kbInfo = dat_list.get(3); + Assert.assertEquals("european2", kbInfo.get(KMManager.KMKey_KeyboardID)); + + // Verify old keyboard list size + int oldKeyboardListSize = dat_list.size(); + Assert.assertEquals(6, oldKeyboardListSize); + + // Verify old keyboards list contains sil_euro_latin at the end + kbInfo = dat_list.get(oldKeyboardListSize-1); + Assert.assertEquals("sil_euro_latin", kbInfo.get(KMManager.KMKey_KeyboardID)); + + // Migrate list + List migratedList = KMManager.updateOldKeyboardsList(ApplicationProvider.getApplicationContext(), dat_list); + + // Verify migrated keyboard list size + int migratedKeyboardListSize = migratedList.size(); + Assert.assertEquals(migratedKeyboardListSize, 3); + + // Verify deprecated keyboards don't exist in migrated keyboards list + for (int i=0; i kbInfo = CloudDataJsonUtil.createKeyboardInfoMap( - pkgID, langID, langName, keyboardID, keyboardName, keyboardVersion, customKeyboard, aFont, oskFont, customHelpLink); + pkgID, langID, langName, keyboardID, keyboardName, keyboardVersion, aFont, oskFont, customHelpLink); Assert.assertEquals(langID.toLowerCase(), kbInfo.get(KMManager.KMKey_LanguageID)); // Test processLexicalModelJSON() JSONParser parser = new JSONParser(); JSONArray cloud = parser.getJSONObjectFromFile(new File(TEST_RESOURCE_ROOT, "sencoten.json"), JSONArray.class); - List results = CloudDataJsonUtil.processLexicalModelJSON(cloud); + List results = CloudDataJsonUtil.processLexicalModelJSON(cloud, true); LexicalModel lmInfo = results.get(0); Assert.assertEquals("str-latn", lmInfo.getLanguageID()); diff --git a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/packages/LexicalModelPackageProcessorTest.java b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/packages/LexicalModelPackageProcessorTest.java index 454ae6f360dcb8a29d5f6a47d07ebf9a2673ae95..543b6d1cb8b5ecea262ece5cec18025d1927ed85 100644 --- a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/packages/LexicalModelPackageProcessorTest.java +++ b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/packages/LexicalModelPackageProcessorTest.java @@ -13,6 +13,7 @@ import org.robolectric.RobolectricTestRunner; import java.io.File; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -64,8 +65,10 @@ public class LexicalModelPackageProcessorTest { Assert.assertNotNull(json); String pkgVersion = lmPP.getPackageVersion(json); + ArrayList languageList = new ArrayList(); + languageList.add("en"); - Map[] models = lmPP.processEntry(json.getJSONArray("lexicalModels").getJSONObject(0), "example.en.custom", pkgVersion, "en"); + Map[] models = lmPP.processEntry(json.getJSONArray("lexicalModels").getJSONObject(0), "example.en.custom", pkgVersion, languageList); HashMap en_custom = new HashMap(); en_custom.put(KMManager.KMKey_PackageID, "example.en.custom"); diff --git a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/packages/PackageProcessorTest.java b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/packages/PackageProcessorTest.java index cb5f97590e28139ef46d91205423ab1778d59a1f..656d3b2f1e91d8ed5538b9b1495fb0347c814ed9 100644 --- a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/packages/PackageProcessorTest.java +++ b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/packages/PackageProcessorTest.java @@ -13,6 +13,7 @@ import org.robolectric.RobolectricTestRunner; import java.io.File; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; @@ -40,6 +41,7 @@ public class PackageProcessorTest { private static final int TEST_GFF_KBD_COUNT = 1; private static final String TEST_GFF_PACKAGE_NAME = "GFF Amharic Keyboard"; private static final String TEST_GFF_KBD_ID = "gff_amh_7"; + private static final String TEST_GFF_KBD_NAME = "Amharic"; private static final String TEST_EN_CUSTOM_MODEL_NAME = "example.en.custom"; private static final File TEST_EN_CUSTOM_MODEL_KMP_FILE = new File(TEST_RESOURCE_ROOT, "packages" + @@ -133,8 +135,8 @@ public class PackageProcessorTest { Assert.assertNotNull(json); String pkgVersion = PP.getPackageVersion(json); - String languageID = null; - Map[] keyboards = PP.processEntry(json.getJSONArray("keyboards").getJSONObject(0), "gff_amh_7_test_json", pkgVersion, languageID); + ArrayList languageList = new ArrayList(); + Map[] keyboards = PP.processEntry(json.getJSONArray("keyboards").getJSONObject(0), "gff_amh_7_test_json", pkgVersion, languageList); HashMap amharic = new HashMap(); amharic.put(KMManager.KMKey_PackageID, "gff_amh_7_test_json"); @@ -143,22 +145,24 @@ public class PackageProcessorTest { amharic.put(KMManager.KMKey_LanguageID, "am"); amharic.put(KMManager.KMKey_LanguageName, "Amharic"); amharic.put(KMManager.KMKey_KeyboardVersion, "1.4"); - amharic.put(KMManager.KMKey_CustomKeyboard, "Y"); amharic.put(KMManager.KMKey_CustomHelpLink, TEST_GFF_KMP_TARGET + File.separator + "welcome.htm"); // If languageID doesn't match, verify only the first language is installed with the keyboard Assert.assertEquals(amharic, keyboards[0]); Assert.assertEquals(TEST_GFF_KBD_COUNT, keyboards.length); - languageID = "am"; - keyboards = PP.processEntry(json.getJSONArray("keyboards").getJSONObject(0), "gff_amh_7_test_json", pkgVersion, languageID); + String languageID = "am"; + languageList.add(languageID); + keyboards = PP.processEntry(json.getJSONArray("keyboards").getJSONObject(0), "gff_amh_7_test_json", pkgVersion, languageList); // Verify "am" matched Assert.assertEquals(amharic, keyboards[0]); Assert.assertEquals(TEST_GFF_KBD_COUNT, keyboards.length); + languageList.remove(0); languageID = "GEZ"; - keyboards = PP.processEntry(json.getJSONArray("keyboards").getJSONObject(0), "gff_amh_7_test_json", pkgVersion, languageID); + languageList.add(languageID); + keyboards = PP.processEntry(json.getJSONArray("keyboards").getJSONObject(0), "gff_amh_7_test_json", pkgVersion, languageList); HashMap geez = new HashMap(); geez.put(KMManager.KMKey_PackageID, "gff_amh_7_test_json"); @@ -167,7 +171,6 @@ public class PackageProcessorTest { geez.put(KMManager.KMKey_LanguageID, "gez"); geez.put(KMManager.KMKey_LanguageName, "Ge'ez"); geez.put(KMManager.KMKey_KeyboardVersion, "1.4"); - geez.put(KMManager.KMKey_CustomKeyboard, "Y"); geez.put(KMManager.KMKey_CustomHelpLink, TEST_GFF_KMP_TARGET + File.separator + "welcome.htm"); // Verify "gez" matched @@ -229,7 +232,7 @@ public class PackageProcessorTest { } @Test - public void test_keyboardVersion() throws Exception { + public void test_keyboardVersion() { JSONObject json = PP.loadPackageInfo(tempPkg); Assert.assertEquals("1.4", PackageProcessor.getKeyboardVersion(json, TEST_GFF_KBD_ID)); diff --git a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/BCP47Test.java b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/BCP47Test.java new file mode 100644 index 0000000000000000000000000000000000000000..b5d68f2250c292cded40f399472c63201b2c1e34 --- /dev/null +++ b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/BCP47Test.java @@ -0,0 +1,30 @@ +package com.tavultesoft.kmea.util; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; + +import com.tavultesoft.kmea.util.BCP47; + +@RunWith(RobolectricTestRunner.class) +public class BCP47Test { + + private final String LANGUAGE_ID_1 = "str-latn"; + private final String LANGUAGE_ID_2 = "str-Latn"; + private final String LANGUAGE_ID_3 = "str"; + + @Test + public void test_languageEquals() { + // Test null language ID + Assert.assertFalse(BCP47.languageEquals(null, LANGUAGE_ID_2)); + Assert.assertFalse(BCP47.languageEquals(LANGUAGE_ID_1, null)); + Assert.assertFalse(BCP47.languageEquals(null, null)); + + Assert.assertFalse(BCP47.languageEquals(LANGUAGE_ID_1, LANGUAGE_ID_3)); + Assert.assertFalse(BCP47.languageEquals(LANGUAGE_ID_2, LANGUAGE_ID_3)); + + Assert.assertTrue(BCP47.languageEquals(LANGUAGE_ID_1, LANGUAGE_ID_1)); + Assert.assertTrue(BCP47.languageEquals(LANGUAGE_ID_1, LANGUAGE_ID_2)); + } +} \ No newline at end of file diff --git a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/FileUtilsTest.java b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/FileUtilsTest.java index b1f4663a00f146014bf7137d59ee143803282443..77af749dd318acc6f4217a0d1c6cf33c51c25de1 100644 --- a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/FileUtilsTest.java +++ b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/FileUtilsTest.java @@ -8,6 +8,7 @@ import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.shadows.ShadowLog; +import java.io.File; import java.util.List; @RunWith(RobolectricTestRunner.class) @@ -25,59 +26,12 @@ public class FileUtilsTest { Assert.assertEquals(4, logs.size()); Assert.assertEquals("Connection", logs.get(2).tag); - Assert.assertEquals("Initialization failed:java.net.MalformedURLException: no protocol: invalidURL", logs.get(2).msg); + Assert.assertEquals("Initialization failed:\njava.net.MalformedURLException: no protocol: invalidURL", logs.get(2).msg); Assert.assertEquals("FileUtils", logs.get(3).tag); Assert.assertEquals("Could not download filename ", logs.get(3).msg); } - @Test - public void test_isCustomKeyboard() { - // True because URL is null or empty (doesn't match *.keyman.com) - Assert.assertTrue(FileUtils.isCustomKeyboard(null)); - Assert.assertTrue(FileUtils.isCustomKeyboard("")); - - Assert.assertFalse(FileUtils.isCustomKeyboard("http://keyman.com/")); - Assert.assertFalse(FileUtils.isCustomKeyboard("https://keyman.com/")); - Assert.assertFalse(FileUtils.isCustomKeyboard("http://api.keyman.com/")); - Assert.assertFalse(FileUtils.isCustomKeyboard("https://api.keyman.com/")); - Assert.assertFalse(FileUtils.isCustomKeyboard("https://keyman.com/keyboard/khmer_angkor")); - - // True because trailing slash is missing - Assert.assertTrue(FileUtils.isCustomKeyboard("http://keyman.com")); - Assert.assertTrue(FileUtils.isCustomKeyboard("https://keyman.com")); - Assert.assertTrue(FileUtils.isCustomKeyboard("http://api.keyman.com")); - Assert.assertTrue(FileUtils.isCustomKeyboard("https://api.keyman.com")); - - // "custom" site - Assert.assertTrue(FileUtils.isCustomKeyboard("https://amerikeyman.com/")); - } - - @Test - public void test_isKeymanLink() { - Assert.assertFalse(FileUtils.isKeymanLink(null)); - Assert.assertFalse(FileUtils.isKeymanLink("")); - - // Valid Keyman links - Assert.assertTrue(FileUtils.isKeymanLink("keyman:download?keyboard")); - Assert.assertTrue(FileUtils.isKeymanLink("Keyman:Download?keyboard")); - - // keyman:// invalid - Assert.assertFalse(FileUtils.isKeymanLink("keyman://keyboard")); - Assert.assertFalse(FileUtils.isKeymanLink("Keyman://keyboard")); - Assert.assertFalse(FileUtils.isKeymanLink("keyman:download//keyboard")); - Assert.assertFalse(FileUtils.isKeymanLink("keyman://download/keyboard")); - - // link missing query - Assert.assertFalse(FileUtils.isKeymanLink("keyman:download?")); - - // Other methods not supported - Assert.assertFalse(FileUtils.isKeymanLink("keyman:method//keyboard")); - Assert.assertFalse(FileUtils.isKeymanLink("keyman:method?keyboard")); - - Assert.assertFalse(FileUtils.isKeymanLink("example:keyman?")); - } - @Test public void test_compareVersions() { Assert.assertEquals(FileUtils.VERSION_INVALID, FileUtils.compareVersions(null, "1.0")); @@ -286,7 +240,7 @@ public class FileUtilsTest { filename = "test/welcome.HTM"; Assert.assertTrue(FileUtils.isWelcomeFile(filename)); - filename = "test\\welcome.htm"; + filename = "test" + File.separator + "welcome.htm"; Assert.assertTrue(FileUtils.isWelcomeFile(filename)); filename = "test/WELCOME.HTM"; diff --git a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/KMPLinkTest.java b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/KMPLinkTest.java new file mode 100644 index 0000000000000000000000000000000000000000..013da4132a79d1f5f978bc335971620330de6d37 --- /dev/null +++ b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/util/KMPLinkTest.java @@ -0,0 +1,57 @@ +package com.tavultesoft.kmea.util; + +import org.junit.Assert; +import org.junit.Test; + +import com.tavultesoft.kmea.util.KMPLink; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; + +public class KMPLinkTest { + + @Test + public void test_isKeymanInstallLink() { + Assert.assertFalse(KMPLink.isKeymanInstallLink(null)); + Assert.assertFalse(KMPLink.isKeymanInstallLink("")); + + // Valid Keyman keyboard install links + Assert.assertTrue(KMPLink.isKeymanInstallLink("https://keyman-staging.com/keyboards/install/malar_malayalam")); + Assert.assertTrue(KMPLink.isKeymanInstallLink("https://keyman-staging.com/keyboards/install/malar_malayalam?bcp47=ml")); + Assert.assertTrue(KMPLink.isKeymanInstallLink("https://keyman-staging.com/keyboards/install/fv_sencoten?bcp47=str-Latn")); + Assert.assertTrue(KMPLink.isKeymanInstallLink("https://keyman.com/keyboards/install/lao%20unicode")); // legacy keyboard within download dialog + Assert.assertTrue(KMPLink.isKeymanInstallLink("https://keyman.com/keyboards/install/khmer_angkor?_gid=112233&bcp47=lo")); // other query params appearing + + Assert.assertTrue(KMPLink.isKeymanInstallLink("https://keyman.com/keyboards/install/malar_malayalam")); + Assert.assertTrue(KMPLink.isKeymanInstallLink("https://keyman.com/keyboards/install/malar_malayalam?bcp47=ml")); + + // Keyboard link is wrong + Assert.assertFalse(KMPLink.isKeymanInstallLink("https://keyman-staging.com/keyboard/install/malar_malayalam")); + + // link missing packageID + Assert.assertFalse(KMPLink.isKeymanInstallLink("https://keyman-staging.com/keyboards/install")); + Assert.assertFalse(KMPLink.isKeymanInstallLink("https://keyman-staging.com/keyboards/install/")); + Assert.assertFalse(KMPLink.isKeymanInstallLink("https://keyman.com/keyboards/install")); + Assert.assertFalse(KMPLink.isKeymanInstallLink("https://keyman.com/keyboards/install/")); + } + + @Test + public void test_isKeymanDownloadLink() { + Assert.assertFalse(KMPLink.isKeymanDownloadLink(null)); + Assert.assertFalse(KMPLink.isKeymanDownloadLink("")); + + // Valid Keyman keyboard download links + Assert.assertTrue(KMPLink.isKeymanDownloadLink("https://keyman-staging.com/go/package/download/malar_malayalam?platform=android&tier=alpha")); + Assert.assertTrue(KMPLink.isKeymanDownloadLink("https://keyman-staging.com/go/package/download/malar_malayalam?platform=android&tier=alpha&bcp47=ml")); + Assert.assertTrue(KMPLink.isKeymanDownloadLink("https://keyman.com/go/package/download/malar_malayalam?platform=android&tier=alpha")); + Assert.assertTrue(KMPLink.isKeymanDownloadLink("https://keyman.com/go/package/download/malar_malayalam?platform=android&tier=alpha&bcp47=ml")); + + // link missing packageID + Assert.assertFalse(KMPLink.isKeymanDownloadLink("https://keyman-staging.com/go/package/download")); + Assert.assertFalse(KMPLink.isKeymanDownloadLink("https://keyman-staging.com/go/package/download/")); + Assert.assertFalse(KMPLink.isKeymanDownloadLink("https://keyman.com/go/package/download")); + Assert.assertFalse(KMPLink.isKeymanDownloadLink("https://keyman.com/go/package/download/")); + } +} diff --git a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/view/FunctionalTestHelper.java b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/view/FunctionalTestHelper.java index ba9996f81a027babd7226943bdbcf6d273a7d584..2788ad9f6ceff0c17a4661a01cee90e12b3d85d7 100644 --- a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/view/FunctionalTestHelper.java +++ b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/view/FunctionalTestHelper.java @@ -9,6 +9,7 @@ import android.util.Log; import androidx.test.core.app.ApplicationProvider; import com.tavultesoft.kmea.KMManager; +import com.tavultesoft.kmea.data.Keyboard; import com.tavultesoft.kmea.packages.PackageProcessor; import com.tavultesoft.kmea.util.FileUtils; @@ -48,12 +49,7 @@ class FunctionalTestHelper { */ static void setInitialKeyboard() { - KMManager.setKeyboard(KMManager.KMDefault_PackageID, - KMManager.KMDefault_KeyboardID, - KMManager.KMDefault_LanguageID, - KMManager.KMDefault_KeyboardName, - KMManager.KMDefault_LanguageName, - KMManager.KMDefault_KeyboardFont, null); + KMManager.setKeyboard(KMManager.getDefaultKeyboard(ApplicationProvider.getApplicationContext())); } /** diff --git a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/view/KeyboardPickerTest.java b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/view/KeyboardPickerTest.java index 2007ed276b53550284936dcb7f80ca579c8929cd..21fcec27ccc8f894e5a385f0ca35a7982feac18e 100644 --- a/android/KMEA/app/src/test/java/com/tavultesoft/kmea/view/KeyboardPickerTest.java +++ b/android/KMEA/app/src/test/java/com/tavultesoft/kmea/view/KeyboardPickerTest.java @@ -2,6 +2,7 @@ package com.tavultesoft.kmea.view; import android.content.Intent; +import android.util.Log; import android.view.View; import android.widget.ListView; @@ -11,6 +12,7 @@ import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KeyboardInfoActivity; import com.tavultesoft.kmea.KeyboardPickerActivity; import com.tavultesoft.kmea.R; +import com.tavultesoft.kmea.data.Keyboard; import org.json.JSONException; import org.junit.After; @@ -34,6 +36,7 @@ public class KeyboardPickerTest { private static final File TEST_RESOURCE_ROOT = new File("test_resources"); + private static final File TEST_DEFAULT_KMP_FILE = new File(TEST_RESOURCE_ROOT, "v14" + File.separator + "sil_euro_latin.kmp"); private static final String TEST_GFF_KMP_NAME = "gff_amh_7_test_json"; private static final File TEST_GFF_KMP_FILE = new File(TEST_RESOURCE_ROOT, "v14" + File.separator + TEST_GFF_KMP_NAME + ".kmp"); @@ -50,6 +53,14 @@ public class KeyboardPickerTest { //initializes the keyboard picker (and keyboard list in background) keyboardPickerActivityActivityController = Robolectric.buildActivity(KeyboardPickerActivity.class).setup(); + +// install new custom keyboard programmatically + try { + FunctionalTestHelper.installCustomKeyboard(TEST_DEFAULT_KMP_FILE); + } catch (IOException | JSONException e) { + Log.e("KeyboardPickerTest", "Exception installing default kmp"); + } + //Initial keyboard load (normally done by webview) // should be done directly in FunctionalTestHelper.initializeKeyman(); // but we need to initialize the keyboardpicker first, because auf initialization process @@ -102,10 +113,6 @@ public class KeyboardPickerTest { { KeyboardPickerActivity activity = keyboardPickerActivityActivityController.get(); - // get current keyboard - Map _old = KMManager.getCurrentKeyboardInfo(ApplicationProvider.getApplicationContext()); - Assert.assertNotNull(_old); - // install new custom keyboard programmatically FunctionalTestHelper.installCustomKeyboard(TEST_GFF_KMP_FILE); @@ -122,10 +129,9 @@ public class KeyboardPickerTest { Assert.assertTrue(activity.isFinishing()); // check if keyboardswitch is done - Map _current = KMManager.getCurrentKeyboardInfo(ApplicationProvider.getApplicationContext()); + int index = KeyboardPickerActivity.selectedIndex(); + Keyboard _current = KMManager.getKeyboardInfo(ApplicationProvider.getApplicationContext(), index); Assert.assertNotNull(_current); - - Assert.assertNotEquals(_old.get(KMManager.KMKey_KeyboardID),_current.get(KMManager.KMKey_KeyboardID)); } /** @@ -151,7 +157,8 @@ public class KeyboardPickerTest { Assert.assertNotNull(_view); // click the info button to open keyboard info activity - View _itemview = _view.getAdapter().getView(1, null, null); + int expectedKeyboardID = 0; // Index for expected keyboard + View _itemview = _view.getAdapter().getView(expectedKeyboardID, null, null); Assert.assertNotNull(_itemview); _itemview.findViewById(R.id.imageButton1).performClick(); @@ -169,7 +176,7 @@ public class KeyboardPickerTest { Assert.assertNotNull(_infolistview); //find helplink and click - View _helplink = _view.getAdapter().getView(1, null, null); + View _helplink = _view.getAdapter().getView(expectedKeyboardID, null, null); Assert.assertNotNull(_helplink); _infolistview.performItemClick(_helplink,1,_infolistview.getAdapter().getItemId(1)); diff --git a/android/KMEA/build.gradle b/android/KMEA/build.gradle index ea635fa67bd2d2ba85c56a78ca2172cbb514956c..02bd78c623e2a6265c67219a98c8c58f80dec37d 100644 --- a/android/KMEA/build.gradle +++ b/android/KMEA/build.gradle @@ -7,7 +7,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:3.5.2' // io.sentry:sentry-android-gradle-plugin not available for library project - classpath 'io.sentry:sentry-android:2.0.1' + classpath 'io.sentry:sentry-android:2.3.0' classpath 'name.remal:gradle-plugins:1.0.157' } } diff --git a/android/KMEA/build.sh b/android/KMEA/build.sh index 579f9f9df4437afdf300d6642ec302bd274a9465..8078f95f9054df37a3abdb65352d727fa07fb7d4 100755 --- a/android/KMEA/build.sh +++ b/android/KMEA/build.sh @@ -6,6 +6,14 @@ # KMEA - Keyman Engine Android # KMW - Keyman Web +# Set sensible script defaults: +# set -e: Terminate script if a command returns an error +set -e +# set -u: Terminate script if an unset variable is used +set -u +# set -x: Debugging use, print each statement +# set -x + ## START STANDARD BUILD SCRIPT INCLUDE # adjust relative paths as necessary THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" @@ -13,7 +21,7 @@ THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BA ## END STANDARD BUILD SCRIPT INCLUDE display_usage ( ) { - echo "build.sh [-no-kmw-build] | [-no-kmw] [-no-daemon] | [-no-test]" + echo "build.sh [-no-kmw-build] | [-no-kmw] [-no-daemon] | [-no-test] | [-debug]" echo echo "Build Keyman Engine Android (KMEA) using Keyman Web (KMW) artifacts" echo " -no-kmw-build Don't build KMW. Just copy existing artifacts" @@ -21,6 +29,7 @@ display_usage ( ) { echo " -no-daemon Don't start the Gradle daemon. Use for CI" echo " -no-test Don't run the unit-test suite. Use for development builds" echo " to facilitate manual debugging and testing" + echo " -debug Local debug build; use for development builds" exit 1 } @@ -54,6 +63,7 @@ DO_BUILD=true DO_COPY=true DO_TEST=true NO_DAEMON=false +DEBUG_BUILD=false EMBED_BUILD=-embed KMW_PATH= diff --git a/android/KMEA/gradle/wrapper/gradle-wrapper.jar b/android/KMEA/gradle/wrapper/gradle-wrapper.jar index 8c0fb64a8698b08ecc4158d828ca593c4928e9dd..5c2d1cf016b3885f6930543d57b744ea8c220a1a 100644 Binary files a/android/KMEA/gradle/wrapper/gradle-wrapper.jar and b/android/KMEA/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/KMEA/gradle/wrapper/gradle-wrapper.properties b/android/KMEA/gradle/wrapper/gradle-wrapper.properties index 903f2b03575ff4045bb13e49575fd48edc2741a2..5028f28f8e4755a78a5bf0fef4644577b199c8c4 100644 --- a/android/KMEA/gradle/wrapper/gradle-wrapper.properties +++ b/android/KMEA/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Mon Oct 30 08:32:52 ICT 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip diff --git a/android/KMEA/gradlew b/android/KMEA/gradlew index 91a7e269e19dfc62e27137a0b57ef3e430cee4fd..84fb57da07e013acc8638c8de2aaab4fef16cdcd 100755 --- a/android/KMEA/gradlew +++ b/android/KMEA/gradlew @@ -1,4 +1,20 @@ -#!/usr/bin/env bash +#!/bin/bash + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ############################################################################## ## @@ -6,20 +22,38 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" -warn ( ) { +warn () { echo "$*" } -die ( ) { +die () { echo echo "$*" echo @@ -30,6 +64,7 @@ die ( ) { cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true @@ -40,31 +75,11 @@ case "`uname`" in MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -90,7 +105,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then @@ -110,10 +125,11 @@ if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` @@ -154,11 +170,19 @@ if $cygwin ; then esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +exec "$JAVACMD" "$@" diff --git a/android/KMEA/gradlew.bat b/android/KMEA/gradlew.bat index 8a0b282aa6885fb573c106b3551f7275c5f17e8e..9618d8d9607cd91a0efb866bcac4810064ba6fac 100644 --- a/android/KMEA/gradlew.bat +++ b/android/KMEA/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -8,14 +24,14 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome @@ -46,10 +62,9 @@ echo location of your Java installation. goto fail :init -@rem Get command-line arguments, handling Windowz variants +@rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. @@ -60,11 +75,6 @@ set _SKIP=2 if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ :execute @rem Setup the command line diff --git a/android/KMEA/test_resources/cloud/old_keyboards_list.dat b/android/KMEA/test_resources/cloud/old_keyboards_list.dat new file mode 100644 index 0000000000000000000000000000000000000000..f8c83fc76b26273c7285623737ff5c679fa3fe6c Binary files /dev/null and b/android/KMEA/test_resources/cloud/old_keyboards_list.dat differ diff --git a/android/KMEA/test_resources/v14/sil_euro_latin.kmp b/android/KMEA/test_resources/v14/sil_euro_latin.kmp new file mode 100644 index 0000000000000000000000000000000000000000..8f5c57f8e148a4152edf33a7cf018083ca18eb5a Binary files /dev/null and b/android/KMEA/test_resources/v14/sil_euro_latin.kmp differ diff --git a/android/README.md b/android/README.md index 655ad91ab9833410620cb9e8405faacdc5520706..311c4bf6adca9693aa38443540692ba58062d686 100644 --- a/android/README.md +++ b/android/README.md @@ -14,8 +14,8 @@ https://github.com/ojdkbuild/ojdkbuild 2. On on windows: use the default java path C:\Program Files\Java to avoid error message "Error 0x80010135 Path Too Long". 3. Aso set an environment variable for JAVA_HOME e.g C:\Program Files\Java\openjdk-1.8.0.232-1 -## Minimum Android Requirements -Keyman for Android has a minSdkVersion of 16 for [Android 4.1 Jelly Bean](https://developer.android.com/about/versions/android-4.1) +## Keyman Minimum Android Requirements +Keyman for Android has a minSdkVersion of 21 for [Android 5.0 Lollipop](https://developer.android.com/about/versions/lollipop) ## Setup Android Studio @@ -48,6 +48,12 @@ Keyman for Android (formerly named KMAPro) can be built from a command line (pre Building Keyman Web is a precursor for compiling KMEA, so verify your system has all the [Minimum Web Compilation Requirements](../web/README.md#minimum-web-compilation-requirements) +### Install JQ +jq 1.6+ is used during the build process to determine the latest versions of the default keyboard (sil_euro_latin.kmp) and lexical-model (en.nrc.mtnt.model.kmp) packages to download. For builds on Windows, jq is already included in `/resources/build/` + +On Linux +sudo apt install jq + ### Crash Reporting Keyman for Android uses [Sentry](https://sentry.io) for crash reporting at a server https://sentry.keyman.com. The analytics for Debug are associated with an App Bundle ID `com.tavultesoft.kmapro.debug`. @@ -64,12 +70,14 @@ export SENTRY_PROJECT=keyman-android To validate your configuration, from the `android/` folder run `sentry-cli info`. ### Compiling From Command Line -1. Launch a command prompt -2. Change to one of these directories depending on what you want to compile: - * For compiling KMEA and KMAPro, cd to the directory **keyman/android** - * For compiling only KMAPro, cd to the directory **keyman/android/KMAPro** -3. `./build.sh -debug` -4. The APK will be found in **KMAPro/kMAPro/build/outputs/apk/debug/kMAPro-debug.apk** +1. Launch a command prompt and cd to the directory **keyman/android** +2. Run the top level build script `./build.sh -debug` which will: + * Compile KMEA (and its KMW dependency) + * Download default keyboard and dictionary resources as needed + * Compile KMAPro + * Note: to force an update to the latest keyboard and dictionary packages, use the `-download-resources` flag. + +3. The APK will be found in **keyman/android/KMAPro/kMAPro/build/outputs/apk/debug/kMAPro-debug.apk** ### Compiling From Android Studio 1. Ensure that [Keyman Engine for Android](#how-to-build-keyman-engine-for-android) is built. @@ -128,16 +136,14 @@ Building these projects follow the same steps as KMAPro: **android/Tests/KeyboardHarness** app is a test harness for developers to troubleshoot keyboards. -1. Copy the keyboard js file and applicable ttf fonts to *android/Tests/KeyboardHarness/app/src/main/assets/cloud/*. - - For users of Keyman Engine pre 10.0, use the folders -*android/Tests/KeyboardHarness/app/src/main/assets/languages/* and -*android/Tests/KeyboardHarness/app/src/main/assets/fonts/* respectively. - -2. Add the keyboard in *android/Tests/KeyboardHarness/app/src/main/java/com/keyman/android/tests/keyboardHarness/MainActivity.java* -3. cd to android/Tests/KeyboardHarness/ -4. `./build.sh` -5. Open Android Studio to run the app +1. Copy the keyboard js file and applicable ttf fonts to *android/Tests/KeyboardHarness/app/src/main/assets/*. +2. In Keyman Developer + * Open the `keyboardharness.kpj` project and add your keyboard files to the keyboard package. + * Build the keyboardharness.kmp keyboard package +3. Add the keyboard in *android/Tests/KeyboardHarness/app/src/main/java/com/keyman/android/tests/keyboardHarness/MainActivity.java* +4. cd to android/Tests/KeyboardHarness/ +5. `./build.sh` +6. Open Android Studio to run the app -------------------------------------------------------------- @@ -154,7 +160,21 @@ Keyman Engine for Android library (**keyman-engine.aar**) is now ready to be imp b. If you choose to use your own build of the Keyman Engine, get the library from **android/Samples/KMSample1/app/libs/keyman-engine.aar** 2. Open your project in Android Studio. 3. Open **build.gradle** (Module: app) in "Gradle Scripts". -4. After the `android {}` object, include the following: +4. Check that the `android{}` object, includes the following: +```gradle +android { + compileSdkVersion 29 + + // Don't compress kmp files so they can be copied via AssetManager + aaptOptions { + noCompress "kmp" + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } +``` +5. After the `android {}` object, include the following: ````gradle repositories { flatDir { @@ -165,15 +185,10 @@ repositories { dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) - implementation 'androidx.appcompat:appcompat:1.1.1' - implementation 'com.google.android.material:material:1.0.0' - api (name:'keyman-engine', ext:'aar') - implementation "com.google.firebase:firebase-analytics:17.2.1" - implementation "com.google.firebase:firebase-messaging:20.0.1" - implementation "com.google.firebase:firebase-crash:16.2.1" - implementation('com.crashlytics.sdk.android:crashlytics:2.10.1@aar') { - transitive = true - } + implementation 'androidx.appcompat:appcompat:1.2.0-alpha03' + implementation 'com.google.android.material:material:1.1.0' + api(name: 'keyman-engine', ext: 'aar') + implementation 'io.sentry:sentry-android:2.0.1' // Include this if you want to have QR Codes displayed on Keyboard Info implementation ('com.github.kenglxn.QRGen:android:2.6.0') { diff --git a/android/Samples/KMSample1/app/build.gradle b/android/Samples/KMSample1/app/build.gradle index 3f45a856f5f256bad8a9e93fd4d5b8375b6013e3..b091fdbc9c37a8fb170b6bebcc4646d8d3c046cd 100644 --- a/android/Samples/KMSample1/app/build.gradle +++ b/android/Samples/KMSample1/app/build.gradle @@ -23,6 +23,7 @@ android { // VERSION_CODE and VERSION_NAME from version.gradle versionCode VERSION_CODE as Integer versionName VERSION_NAME + buildConfigField "String", "VERSION_ENVIRONMENT", "\""+VERSION_ENVIRONMENT+"\"" } buildTypes { release { diff --git a/android/Samples/KMSample1/app/src/main/java/com/keyman/kmsample1/MainActivity.java b/android/Samples/KMSample1/app/src/main/java/com/keyman/kmsample1/MainActivity.java index 3262dd1e5c9063b5e479804fa7688bd9728294e9..47ccb0bd187f863e4c5e973cd5d7e112efd45961 100644 --- a/android/Samples/KMSample1/app/src/main/java/com/keyman/kmsample1/MainActivity.java +++ b/android/Samples/KMSample1/app/src/main/java/com/keyman/kmsample1/MainActivity.java @@ -8,6 +8,7 @@ import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; +import com.tavultesoft.kmea.data.Keyboard; import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KMTextView; @@ -36,15 +37,21 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi textView = (KMTextView) findViewById(R.id.kmTextView); // Add a custom keyboard - HashMap kbInfo = new HashMap(); - kbInfo.put(KMManager.KMKey_PackageID, "basic_kbdtam99"); - kbInfo.put(KMManager.KMKey_KeyboardID, "basic_kbdtam99"); - kbInfo.put(KMManager.KMKey_LanguageID, "ta"); - kbInfo.put(KMManager.KMKey_KeyboardName, "Tamil 99 Basic"); - kbInfo.put(KMManager.KMKey_LanguageName, "Tamil"); - kbInfo.put(KMManager.KMKey_KeyboardVersion, "1.0"); - //kbInfo.put(KMManager.KMKey_Font, "aava1.ttf"); - kbInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont); // Use the default font + Keyboard kbInfo = new Keyboard( + "basic_kbdtam99", // Package ID - filename of the .kmp file + "basic_kbdtam99", // Keyboard ID + "Tamil 99 Basic", // Keyboard Name + "ta", // Language ID + "Tamil", // Language Name + "1.0", // Keyboard Version + null, // URL to help documentation if available + "", // URL to latest .kmp file + true, // Boolean to show this is a new keyboard in the keyboard picker + + // Font information of the .ttf font to use in KMSample1 (for example "aava1.ttf"). + // basic_kbdtam99 doesn't include a font. Can set blank "" or KMManager.KMDefault_KeyboardFont + KMManager.KMDefault_KeyboardFont, // Font for KMSample1 text field + KMManager.KMDefault_KeyboardFont); // Font for OSK KMManager.addKeyboard(this, kbInfo); // Add a dictionary diff --git a/android/Samples/KMSample2/app/build.gradle b/android/Samples/KMSample2/app/build.gradle index bce60985a30eeb12aeed9eec97336c7946cf6f09..79d702d372bed36b0483c6ebb2eb81dd6680da10 100644 --- a/android/Samples/KMSample2/app/build.gradle +++ b/android/Samples/KMSample2/app/build.gradle @@ -23,6 +23,7 @@ android { // VERSION_CODE and VERSION_NAME from version.gradle versionCode VERSION_CODE as Integer versionName VERSION_NAME + buildConfigField "String", "VERSION_ENVIRONMENT", "\""+VERSION_ENVIRONMENT+"\"" } buildTypes { release { diff --git a/android/Samples/KMSample2/app/src/main/assets/example.ta.wordlist.model.kmp b/android/Samples/KMSample2/app/src/main/assets/example.ta.wordlist.model.kmp new file mode 100644 index 0000000000000000000000000000000000000000..901367b86a7db42da4ea9c572dbbd7205225a68b Binary files /dev/null and b/android/Samples/KMSample2/app/src/main/assets/example.ta.wordlist.model.kmp differ diff --git a/android/Samples/KMSample2/app/src/main/java/com/keyman/kmsample2/SystemKeyboard.java b/android/Samples/KMSample2/app/src/main/java/com/keyman/kmsample2/SystemKeyboard.java index b715d510ec2b0d4e9a6cb96a35c09eedeae5bb0f..36f8ec72dc4dec2af6a483350dffb9ec1bf401db 100644 --- a/android/Samples/KMSample2/app/src/main/java/com/keyman/kmsample2/SystemKeyboard.java +++ b/android/Samples/KMSample2/app/src/main/java/com/keyman/kmsample2/SystemKeyboard.java @@ -1,5 +1,6 @@ package com.keyman.kmsample2; +import com.tavultesoft.kmea.data.Keyboard; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KMManager.KeyboardType; import com.tavultesoft.kmea.KMHardwareKeyboardInterpreter; @@ -37,16 +38,32 @@ public class SystemKeyboard extends InputMethodService implements OnKeyboardEven interpreter = new KMHardwareKeyboardInterpreter(getApplicationContext(), KeyboardType.KEYBOARD_TYPE_SYSTEM); // Add a custom keyboard - HashMap kbInfo = new HashMap(); - kbInfo.put(KMManager.KMKey_PackageID, "basic_kbdtam99"); - kbInfo.put(KMManager.KMKey_KeyboardID, "basic_kbdtam99"); - kbInfo.put(KMManager.KMKey_LanguageID, "ta"); - kbInfo.put(KMManager.KMKey_KeyboardName, "Tamil 99 Basic"); - kbInfo.put(KMManager.KMKey_LanguageName, "Tamil"); - kbInfo.put(KMManager.KMKey_KeyboardVersion, "1.0"); - //kbInfo.put(KMManager.KMKey_Font, "aava1.ttf"); - kbInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont); // Use the default font + Keyboard kbInfo = new Keyboard( + "basic_kbdtam99", // Package ID - filename of the .kmp file + "basic_kbdtam99", // Keyboard ID + "Tamil 99 Basic", // Keyboard Name + "ta", // Language ID + "Tamil", // Language Name + "1.0", // Keyboard Version + null, // URL to help documentation if available + "", // URL to latest .kmp file + true, // Boolean to show this is a new keyboard in the keyboard picker + + // Font information of the .ttf font to use in KMSample2 (for example "aava1.ttf"). + // basic_kbdtam99 doesn't include a font. Can set blank "" or KMManager.KMDefault_KeyboardFont + // KMEA will use the font for the OSK, but the Android device determines the system font used for keyboard output + KMManager.KMDefault_KeyboardFont, // Font for KMSample2 + KMManager.KMDefault_KeyboardFont); // Font for OSK KMManager.addKeyboard(this, kbInfo); + + // Add a dictionary + HashMaplexicalModelInfo = new HashMap(); + lexicalModelInfo.put(KMManager.KMKey_PackageID, "example.ta.wordlist"); + lexicalModelInfo.put(KMManager.KMKey_LanguageID, "ta"); + lexicalModelInfo.put(KMManager.KMKey_LexicalModelID, "example.ta.wordlist"); + lexicalModelInfo.put(KMManager.KMKey_LexicalModelVersion, "1.0"); + KMManager.addLexicalModel(this, lexicalModelInfo); + KMManager.registerAssociatedLexicalModel("ta"); } @Override @@ -153,8 +170,9 @@ public class SystemKeyboard extends InputMethodService implements OnKeyboardEven if (inputView != null) inputViewHeight = inputView.getHeight(); + int bannerHeight = KMManager.getBannerHeight(this); int kbHeight = KMManager.getKeyboardHeight(this); - outInsets.contentTopInsets = inputViewHeight - kbHeight; + outInsets.contentTopInsets = inputViewHeight - bannerHeight - kbHeight; outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION; outInsets.touchableRegion.set(0, outInsets.contentTopInsets, size.x, size.y); } @@ -184,6 +202,18 @@ public class SystemKeyboard extends InputMethodService implements OnKeyboardEven @Override public boolean onKeyDown(int keyCode, KeyEvent event) { + if (event.getAction() == KeyEvent.ACTION_DOWN) { + switch (keyCode) { + case KeyEvent.KEYCODE_BACK: + // Dismiss the keyboard if currently shown + if (isInputViewShown()) { + KMManager.hideSystemKeyboard(); + return true; + } + break; + } + } + return interpreter.onKeyDown(keyCode, event); // if false, will revert to default handling. } diff --git a/android/Tests/KeyboardHarness/app/build.gradle b/android/Tests/KeyboardHarness/app/build.gradle index a66d54d218e1d6ba4c17241c1d1f5147207df382..49948b58b21ab94a765a78da0a60a7dd3b02a973 100644 --- a/android/Tests/KeyboardHarness/app/build.gradle +++ b/android/Tests/KeyboardHarness/app/build.gradle @@ -23,6 +23,7 @@ android { // VERSION_CODE and VERSION_NAME from version.gradle versionCode VERSION_CODE as Integer versionName VERSION_NAME + buildConfigField "String", "VERSION_ENVIRONMENT", "\""+VERSION_ENVIRONMENT+"\"" } buildTypes { release { diff --git a/android/Tests/KeyboardHarness/app/src/main/assets/keyboardharness.kmp b/android/Tests/KeyboardHarness/app/src/main/assets/keyboardharness.kmp index b434d7883587e91d0c9f402dc6ab158e1df27c7c..9db5e29cc24510d3493b9d38ad6e812e45dd006a 100644 Binary files a/android/Tests/KeyboardHarness/app/src/main/assets/keyboardharness.kmp and b/android/Tests/KeyboardHarness/app/src/main/assets/keyboardharness.kmp differ diff --git a/android/Tests/KeyboardHarness/app/src/main/java/com/keyman/android/tests/keyboardHarness/MainActivity.java b/android/Tests/KeyboardHarness/app/src/main/java/com/keyman/android/tests/keyboardHarness/MainActivity.java index a979d05f89756e09eaeddb3b39ba055e2a3ee6f7..9454e940b7b99db1e1d6e87908d1200916d4fc7b 100644 --- a/android/Tests/KeyboardHarness/app/src/main/java/com/keyman/android/tests/keyboardHarness/MainActivity.java +++ b/android/Tests/KeyboardHarness/app/src/main/java/com/keyman/android/tests/keyboardHarness/MainActivity.java @@ -6,6 +6,7 @@ import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; +import com.tavultesoft.kmea.data.Keyboard; import com.tavultesoft.kmea.KMKeyboardDownloaderActivity; import com.tavultesoft.kmea.KMManager; import com.tavultesoft.kmea.KMTextView; @@ -35,36 +36,48 @@ public class MainActivity extends AppCompatActivity implements OnKeyboardEventLi // Add custom keyboards // Chirality test keyboard - HashMap chiralityKBInfo = new HashMap(); - chiralityKBInfo.put(KMManager.KMKey_PackageID, "keyboardharness"); - chiralityKBInfo.put(KMManager.KMKey_KeyboardID, "chirality"); - chiralityKBInfo.put(KMManager.KMKey_LanguageID, "en"); - chiralityKBInfo.put(KMManager.KMKey_KeyboardName, "Chirality Keyboard"); - chiralityKBInfo.put(KMManager.KMKey_LanguageName, "English"); - chiralityKBInfo.put(KMManager.KMKey_KeyboardVersion, "1.0"); - chiralityKBInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont); + Keyboard chiralityKBInfo = new Keyboard( + "keyboardharness", + "chirality", + "Chirality Keyboard", + "en", + "English", + "1.0", + "", // help link + "", // kmp + true, + KMManager.KMDefault_KeyboardFont, + KMManager.KMDefault_KeyboardFont); KMManager.addKeyboard(this, chiralityKBInfo); // Longpress test keyboard - HashMap longpressKBbInfo = new HashMap(); - longpressKBbInfo.put(KMManager.KMKey_PackageID, "keyboardharness"); - longpressKBbInfo.put(KMManager.KMKey_KeyboardID, "longpress"); - longpressKBbInfo.put(KMManager.KMKey_LanguageID, "en"); - longpressKBbInfo.put(KMManager.KMKey_KeyboardName, "Longpress Keyboard"); - longpressKBbInfo.put(KMManager.KMKey_LanguageName, "English"); - longpressKBbInfo.put(KMManager.KMKey_KeyboardVersion, "1.0"); - longpressKBbInfo.put(KMManager.KMKey_Font, "code2001.ttf"); + Keyboard longpressKBbInfo = new Keyboard( + "keyboardharness", + "longpress", + "Longpress Keyboard", + "en", + "English", + "1.0", + "", + "", + true, + "code2001.ttf", + "code2001.ttf"); KMManager.addKeyboard(this, longpressKBbInfo); // Platform test keyboard - HashMap platformtestKBbInfo = new HashMap(); - platformtestKBbInfo.put(KMManager.KMKey_PackageID, "keyboardharness"); - platformtestKBbInfo.put(KMManager.KMKey_KeyboardID, "platformtest"); - platformtestKBbInfo.put(KMManager.KMKey_LanguageID, "en"); - platformtestKBbInfo.put(KMManager.KMKey_KeyboardName, "platformtest Keyboard"); - platformtestKBbInfo.put(KMManager.KMKey_LanguageName, "English"); - platformtestKBbInfo.put(KMManager.KMKey_KeyboardVersion, "1.0"); - platformtestKBbInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont); + Keyboard platformtestKBbInfo = new Keyboard( + "keyboardharness", + "platformtest", + "platformtest Keyboard", + "en", + "English", + "1.0", + "", + "", + true, + KMManager.KMDefault_KeyboardFont, + KMManager.KMDefault_KeyboardFont); KMManager.addKeyboard(this, platformtestKBbInfo); } diff --git a/android/Tests/keycode/app/build.gradle b/android/Tests/keycode/app/build.gradle index 46bfb36262740aec31027493aa941e1ea15d0b6b..6a7cc147d359db67d5d885025c69f9532a7e664e 100644 --- a/android/Tests/keycode/app/build.gradle +++ b/android/Tests/keycode/app/build.gradle @@ -13,6 +13,7 @@ android { // VERSION_CODE and VERSION_NAME from version.gradle versionCode VERSION_CODE as Integer versionName VERSION_NAME + buildConfigField "String", "VERSION_ENVIRONMENT", "\""+VERSION_ENVIRONMENT+"\"" } buildTypes { release { diff --git a/android/build-help.sh b/android/build-help.sh index 462eed6c5745917289a9695f25fa193411c57cbc..44b0e4abba478009fac2d9f04b13e9e82d40df51 100755 --- a/android/build-help.sh +++ b/android/build-help.sh @@ -1,4 +1,14 @@ #!/bin/bash +# Uses the open-source `wget` utility to create an embedding-friendly offline mirror +# equivalent of online help. + +# Set sensible script defaults: +# set -e: Terminate script if a command returns an error +set -e +# set -u: Terminate script if an unset variable is used +set -u +# set -x: Debugging use, print each statement +# set -x ## START STANDARD BUILD SCRIPT INCLUDE # adjust relative paths as necessary @@ -6,19 +16,52 @@ THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BA . "$(dirname "$THIS_SCRIPT")/../resources/build/build-utils.sh" ## END STANDARD BUILD SCRIPT INCLUDE -KMA_ROOT="$KEYMAN_ROOT/android" - -# Uses the open-source `wget` utility to create an embedding-friendly offline mirror -# equivalent of online help. +display_usage ( ) { + echo "build-help.sh [-local]" + echo + echo "Get an offline mirror of the VERSION_RELEASE (#.0) of Keyman for Android help" + echo "from help.keyman.com." + echo "For alpha and beta tiers, use http://help.keyman-staging.com" + echo "For stable tier, uses http://help.keyman.com" + echo " -local Instead of live site, get content from help.keyman.com.local" + exit 1 +} -# Set to .local to run against a locally-hosted version. -# Leave empty for live runs. -LOCAL=.local -WAIT= +KMA_ROOT="$KEYMAN_ROOT/android" +HELP_ROOT="$KMA_ROOT/KMAPro/kMAPro/src/main/assets/info" -# When running against live servers, it's best to have a small wait between loads. -# Cloudflare may frown on not waiting, as `wget` is basically a scraper/bot. -#WAIT="--wait=2" +# Default is using live site content +DO_LOCAL=false + +# Parse args +while [[ $# -gt 0 ]] ; do + key="$1" + case $key in + -local) + DO_LOCAL=true + ;; + -h|-?) + display_usage + ;; + esac + shift # past argument +done + +echo +echo "DO_LOCAL: $DO_LOCAL" +echo + +LOCAL_HOST="help.keyman.com.local" +PRODUCTION_HOST="help.keyman.com" +STAGING_HOST="help.keyman-staging.com" + +if [ "$DO_LOCAL" = true ]; then + WAIT= +else + # When running against live servers, it's best to have a small wait between loads. + # Cloudflare may frown on not waiting, as `wget` is basically a scraper/bot. + WAIT="--wait=2" +fi # Allows tracking slightly different settings for different offline-mirroring ops # should we decide to extract the actual mirroring function into its own file. @@ -26,26 +69,23 @@ WAIT= # iOS uses "--no-directories" instead, at least for now. OPTIONS="--no-host-directories" -DEVICE=android -HELP_SITE_SECTION=products/android -HELP_ROOT="$KMA_ROOT/KMAPro/kMAPro/src/main/assets/info" +DEVICE="android" +HELP_SITE_SECTION="products/android" # Clear previous help file downloads (if they exist) if [ -d "$HELP_ROOT" ]; then rm -r "$HELP_ROOT" fi -# If TIER is set to "alpha", use the previous version. Help is usually only updated during -# the "beta" process. -if [ -z $TIER ]; then - # Prevents an error message on the next check. Also, manual runs will likely be during beta. - TIER=beta +# Determine host by tier and local +if [ "$DO_LOCAL" = true ]; then + HOST="$LOCAL_HOST" +elif [ "$TIER" = "alpha" ] || [ "$TIER" = "beta" ]; then + HOST="$STAGING_HOST" +else + HOST="$PRODUCTION_HOST" fi -if [ $TIER = "alpha" ]; then - # Construct a decremented version string with .minor set to .0 - VERSION="$(($VERSION_MAJOR-1)).0" -fi do_offline_mirror() { # $1 - the form-factor specification. @@ -64,7 +104,7 @@ do_offline_mirror() { --exclude-directories /font/deploy \ --directory-prefix="$HELP_ROOT" \ --adjust-extension \ - "help.keyman.com$LOCAL/$HELP_SITE_SECTION/$VERSION/index.php?embed=$DEVICE&formfactor=$1" + "$HOST/$HELP_SITE_SECTION/$VERSION_RELEASE/index.php?embed=$DEVICE&formfactor=$1" # Results in a flat-structured mirror of the specified folder, # together with all needed resources within the 'site' folder. @@ -73,8 +113,8 @@ do_offline_mirror() { do_offline_mirror "phone" # Now for some magic... we rename the page's folder and redownload with the other setting. -mv $HELP_ROOT/$HELP_SITE_SECTION/$VERSION $HELP_ROOT/$HELP_SITE_SECTION/phone +mv "$HELP_ROOT/$HELP_SITE_SECTION/$VERSION_RELEASE" "$HELP_ROOT/$HELP_SITE_SECTION/phone" do_offline_mirror "tablet" -mv $HELP_ROOT/$HELP_SITE_SECTION/$VERSION $HELP_ROOT/$HELP_SITE_SECTION/tablet +mv "$HELP_ROOT/$HELP_SITE_SECTION/$VERSION_RELEASE" "$HELP_ROOT/$HELP_SITE_SECTION/tablet" diff --git a/android/build-publish.sh b/android/build-publish.sh new file mode 100644 index 0000000000000000000000000000000000000000..add0939ed3f658e20ffe31907aa2166f772c44f0 --- /dev/null +++ b/android/build-publish.sh @@ -0,0 +1,85 @@ +#!/bin/bash +# CI script to publish specified app APKs to the Play Store. +# The APKs should already have been built from a separate script + +# Set sensible script defaults: +# set -e: Terminate script if a command returns an error +set -e +# set -u: Terminate script if an unset variable is used +set -u +# set -x: Debugging use, print each statement +# set -x + +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../resources/build/build-utils.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +echo Publishing APKs to Play Store + +# +# Prevents 'clear' on exit of mingw64 bash shell +# +SHLVL=0 + +display_usage ( ) { + echo "build-publish.sh [-no-daemon] [-kmapro] [-fv]" + echo + echo "Publish app to the Play Store" + echo " -no-daemon Don't start the Gradle daemon. Use for CI" + echo " -kmapro Keyman for Android" + echo " -fv First Voices" + exit 1 +} + +NO_DAEMON=false +DO_KMAPRO=false +DO_FV=false + +# Parse args +while [[ $# -gt 0 ]] ; do + key="$1" + case $key in + -no-daemon) + NO_DAEMON=true + ;; + -kmapro) + DO_KMAPRO=true + ;; + -fv) + DO_FV=true + ;; + -h|-?) + display_usage + ;; + esac + shift # past argument +done + +echo +echo "NO_DAEMON: $NO_DAEMON" +echo "DO_KMAPRO: $DO_KMAPRO" +echo "DO_FV: $DO_FV" +echo + +if [ "$NO_DAEMON" = true ]; then + DAEMON_FLAG=--no-daemon +else + DAEMON_FLAG= +fi + +BUILD_FLAGS="publishReleaseApk" +echo "BUILD_FLAGS $BUILD_FLAGS" + +# Publish Keyman for Android +if [ "$DO_KMAPRO" = true ]; then + cd "$KEYMAN_ROOT/android/KMAPro/" + ./gradlew $DAEMON_FLAG $BUILD_FLAGS +fi + +# Publish FV app +if [ "$DO_FV" = true ]; then + cd "$KEYMAN_ROOT/oem/firstvoices/android/" + ./gradlew $DAEMON_FLAG $BUILD_FLAGS +fi diff --git a/android/build.sh b/android/build.sh index d0559e1f2c57530a1f137398dea6e6da5ea58b83..70c0f4800188d317b936c61f845775965ea82542 100755 --- a/android/build.sh +++ b/android/build.sh @@ -1,6 +1,14 @@ #!/bin/bash # Build Keyman Engine Android and KMAPro +# Set sensible script defaults: +# set -e: Terminate script if a command returns an error +set -e +# set -u: Terminate script if an unset variable is used +#set -u: Not set because of $RELEASE_OEM +# set -x: Debugging use, print each statement +# set -x + ## START STANDARD BUILD SCRIPT INCLUDE # adjust relative paths as necessary THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" @@ -38,7 +46,7 @@ cd "$KEYMAN_ROOT/android" if [ ! -z "$RELEASE_OEM" ]; then pushd "$KEYMAN_ROOT/oem/firstvoices/android" - ./build.sh -lib-nobuild "$@" + ./build.sh -download-keyboards -lib-nobuild "$@" if [ $? -ne 0 ]; then die "ERROR: oem/firstvoices/android/build.sh failed" diff --git a/android/history.md b/android/history.md index 2eddc995f12b1c9d8c7338cd2945a0595034dc95..16ce5c45e42e11a9e7288015b58f1b0dd33818a4 100644 --- a/android/history.md +++ b/android/history.md @@ -1,5 +1,39 @@ # Keyman for Android Version History +## 2020-04-20 13.0.6209 stable +* Bug fix: + * Fix crash involving system keyboard update notifications (#3007) + +## 2020-04-15 13.0.6208 stable +* no change to Keyman for Android (updated Keyman Web Engine #2957) + +## 2020-04-01 13.0.6207 stable +* Bug fix: + * Fix crash involving globe button with 3rd party apps (#2932) + +## 2020-03-18 13.0.6206 stable +* No change to Keyman for Android (updated Keyman Web Engine, #2841, 2839) + +## 2020-03-13 13.0.6205 stable +* No change to Keyman for Android (updated Keyman Web Engine, #2823, 2821, 2820, 2823) + +## 2020-03-11 13.0.6204 stable +* No change to Keyman for Android (updated Keyman Web Engine, #2807, 2797) + +## 2020-03-09 13.0.6203 stable +* No change to Keyman for Android (updated Keyman Web Engine, #2694) + +## 2020-03-06 13.0.6202 stable +* No change to Keyman for Android (updated Keyman Web Engine, #2781) + +## 2020-02-25 13.0.6201 stable +* Bug fix: + * Fix crash involving empty keyboard list (#2723) + * Sanitize app version for api query (#2724) + +## 2020-02-19 13.0.6200 stable +* Release 13.0 + ## 2020-02-14 13.0.6059 beta * Bug fix: * Re-initialize CloudDownloadManager when downloading resources after Keyman app is closed (#2635) @@ -105,7 +139,7 @@ ## 2019-10-25 12.0.4205 stable * Bug fix: * Use lexical model package version for dataset (#2242) - + ## 2019-10-14 12.0.4204 stable * Bug Fix: * FirstVoices app may crash if analytics is not present (#2204) @@ -219,7 +253,7 @@ ## 2019-02-15 11.0.2062 beta * No changes. - + ## 2019-02-07 11.0.2061 beta * Bug fix: * Add notifications when keyboard or font fails to download from Keyman cloud (#1570) @@ -333,7 +367,7 @@ ## 2018-06-11 10.0.399 beta * Consolidate Info view (#972) * Platform tests (in keyboards) are now consistent across all platforms (#969) - + ## 2018-06-05 10.0.398 beta * Fix globe button for system keyboard (#942) @@ -402,7 +436,7 @@ * Initial beta release of Keyman for Android 10.0 ## 10.0 alpha -* Refactor how longpress keys on touch layout are processed in KMW engine. This prevents key text +* Refactor how longpress keys on touch layout are processed in KMW engine. This prevents key text from being processed as key codes, and fixes the app crash when longpress with K_SPACE. * Added support for L/R Alt and Ctrl and Caps Lock modifiers for keyboards if specified by a keyboard designer * Add feature to reset keyboard to default layer when new input field focused (#288) @@ -413,7 +447,7 @@ * Add feature to install ad-hoc keyboards via .kmp packages * Add [Firebase Crashlytics](https://firebase.google.com/docs/crashlytics/) for generating crash reports * Add Material Design [icons](https://material.io/icons/) -* Fix path to special OSK font for longpress of special keys (#239) +* Fix path to special OSK font for longpress of special keys (#239) ## 2017-08-10 2.8.300 stable * No changes, just published latest beta as stable diff --git a/android/utility/.gitignore b/android/utility/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7cc5fc0c85e838c4ea511da00ff245949563b0c9 --- /dev/null +++ b/android/utility/.gitignore @@ -0,0 +1,3 @@ +detail.md +summary.md +strings.txt diff --git a/android/utility/i18n-check-unused-strings.sh b/android/utility/i18n-check-unused-strings.sh new file mode 100755 index 0000000000000000000000000000000000000000..0b9104c3b486df7665c3d1fd80b1f3db007b0610 --- /dev/null +++ b/android/utility/i18n-check-unused-strings.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +# Based on /windows/src/test/i18n-check-unused-strings +# +# This script finds all references to strings in strings.xml in order to make sure that old +# strings do not proliferate over time. The script generates the following files: +# +# * strings.txt: A plain-text list of all string identifiers found in strings.xml. +# * summary.md: A summary of number of matches for each string found. +# * details.md: List of every reference to each string found +# +# Note that you should review the results with care; some strings may not ever be found, +# because they may be metadata such as "author of translation", or they may have been +# added as part of upcoming functionality; they may also be found in temporary files and +# build artifacts. Because of this, and because the script takes a little while to run, +# I'm not adding the script to the standard build at this time. +# +# Note: strings that aren't expected to be found generally should have `translateable="false"`` so they don't get +# translated in crowdin. +# + +set -e # die on non-zero exit code +set -u # die on undefined variables + +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../resources/build/build-utils.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +# Preparation + +echo "# List of localized string usage" > detail.md +echo "Collected at: $(date)" >> detail.md +echo >> detail.md + +echo "# Summary of localized string usage" | tee summary.md +echo "Collected at: $(date)" | tee -a summary.md +echo | tee -a summary.md +echo " Count | String | Flag" | tee -a summary.md +echo "-------|--------|------" | tee -a summary.md + +# Lazy extract all identifiers from strings.xml into local strings.txt +# Note that this relies on the XML following a single line per string pattern +# (up to the name attribute, anyway) but this is good enough for now. + +grep -oP ' strings.txt + +while IFS= read -r string; do + echo "## $string" >> detail.md + count=$(grep -Inr \ + --exclude=strings.xml \ + --exclude-dir=utility \ + "$string" \ + "$KEYMAN_ROOT/android/KMAPro/kMAPro/src/main/res/layout" "$KEYMAN_ROOT/android/KMAPro/kMAPro/src/main/res/menu" "$KEYMAN_ROOT/android/KMAPro/kMAPro/src/main/java" \ + "$KEYMAN_ROOT/android/KMEA/app/src/main/res/layout" "$KEYMAN_ROOT/android/KMEA/app/src/main/java" | tee -a detail.md | wc -l) + echo >> detail.md + + # Write summary + if [ $count -eq 0 ]; then + echo "**0** | **$string** | **Not found**" | tee -a summary.md + else + echo "$count | $string" | tee -a summary.md + fi + +done < strings.txt diff --git a/android/version.gradle b/android/version.gradle index 7b95cdd58fef4b8c60188a0ab361b818ac76adde..553903270886e1fcd0bb08d55f2d41a82c8a6c71 100644 --- a/android/version.gradle +++ b/android/version.gradle @@ -19,21 +19,37 @@ def getVersionCode = { -> } def getVersionName = { -> - String env_version = System.getenv("VERSION") - String env_tier = System.getenv("TIER") - if (env_version != null && env_tier != null) { - // If building from script, we have build number in VERSION and tier in TIER - return "$env_version-$env_tier" + String env_version = System.getenv("VERSION_WITH_TAG") + if (env_version != null) { + // If building from script, we have build number in VERSION_WITH_TAG + println "Using build $env_version from VERSION_WITH_TAG" + return "$env_version" } else { // Building probably from IDE, so let's use VERSION.md and TIER.md directly + // This is a close match with VERSION_WITH_TAG, except that 'stable' tier + // is not normally included with VERSION_WITH_TAG String version_md = file("$rootPath/../VERSION.md").text.trim() String tier_md = file("$rootPath/../TIER.md").text.trim() - println "Using build $version_md-$tier_md from project VERSION.md" - return "$version_md-$tier_md" + println "Using build $version_md-$tier_md-local from project VERSION.md/TIER.md" + return "$version_md-$tier_md-local" + } +} + +def getVersionEnvironment = { -> + String env_environment = System.getenv("VERSION_ENVIRONMENT") + if (env_environment != null) { + // If building from script, we have build number in VERSION_ENVIRONMENT + println "Using $env_environment from VERSION_ENVIRONMENT" + return "$env_environment" + } else { + // Building probably from IDE, so use "local" + println "Using local environment" + return "local" } } ext { VERSION_CODE=getVersionCode() VERSION_NAME=getVersionName() + VERSION_ENVIRONMENT=getVersionEnvironment() } \ No newline at end of file diff --git a/common/core/desktop/build.bat b/common/core/desktop/build.bat new file mode 100644 index 0000000000000000000000000000000000000000..137389bd08da7fff3bdf29e499b0d9590ac8968f --- /dev/null +++ b/common/core/desktop/build.bat @@ -0,0 +1,100 @@ +@echo off + +setlocal enabledelayedexpansion + +if "%1"=="" goto help +if "%1"=="all" goto all +if "%1"=="x86" goto build +if "%1"=="x64" goto build + +echo "Invalid parameter." +goto help + +rem ---------------------------------- + +:help +echo Usage: build-core.bat x86^|x64^|all [-c] +echo -c will leave your environment configured for Visual Studio for selected platform. +echo -c can be used only with x86 and x64 options +goto :eof + +rem ---------------------------------- + +:all + +setlocal +cd %KEYMAN_ROOT%\common\core\desktop +cmd /c build.bat x86 +if errorlevel 1 exit /b !errorlevel! + +cd %KEYMAN_ROOT%\common\core\desktop +cmd /c build.bat x64 +if errorlevel 1 exit /b !errorlevel! + +goto :eof + +rem ---------------------------------- + +:build + +if "%2"=="-c" goto :setup + +set ARCH=%1 +echo Building Keyman Core for Windows !ARCH! + +echo === Locating Visual Studio === + +rem From https://github.com/microsoft/vswhere +for /f "usebackq tokens=*" %%i in (`..\..\..\resources\build\vswhere -latest -requires Microsoft.Component.MSBuild -find **\vcvarsall.bat`) do ( + set VCVARSALL="%%i" +) + +if errorlevel 1 ( + echo vswhere failed [!errorlevel!] + exit /b !errorlevel! +) + +if not exist "!VCVARSALL!" ( + echo Could not find vcvarsall.bat [!VCVARSALL!] + exit /b 1 +) + +echo === Configuring VC++ === +call !VCVARSALL! !ARCH! 8.1 +if errorlevel 1 exit /b !errorlevel! + +echo === Calling meson setup === +cd %KEYMAN_ROOT%\common\core\desktop +meson build-!ARCH! --werror +if errorlevel 1 exit /b !errorlevel! + +echo === Building Keyman Core === +cd build-!ARCH! +if errorlevel 1 exit /b !errorlevel! + +ninja +if errorlevel 1 exit /b !errorlevel! + +echo === Running tests === +rem Run test cases immediately as they are quick +meson test --print-errorlogs +if errorlevel 1 exit /b !errorlevel! + +cd .. + +goto :eof + +rem ---------------------------------- + +:setup + +rem Standalone build, so we'll make the environment available to the caller +rem Also setup +endlocal +for /f "usebackq tokens=*" %%i in (`..\..\..\resources\build\vswhere -latest -requires Microsoft.Component.MSBuild -find **\vcvarsall.bat`) do ( + set VCVARSALL="%%i" +) +%VCVARSALL% %1 8.1 +goto :eof + +rem ---------------------------------- diff --git a/common/core/desktop/debian/control b/common/core/desktop/debian/control index a806954d74be5f65cd15fcefd2f115dcff57722f..6045ac196103a31783bf27b48ec23001b18063ad 100644 --- a/common/core/desktop/debian/control +++ b/common/core/desktop/debian/control @@ -5,7 +5,7 @@ Build-Depends: debhelper (>=9~), Section: text Priority: optional Maintainer: Debian Input Method Team -Uploaders: Daniel Glassey +Uploaders: Daniel Glassey , Keyman team Standards-Version: 3.9.8 Homepage: https://www.keyman.com Vcs-Browser: https://salsa.debian.org/input-method-team/keyman-keyboardprocessor diff --git a/common/core/desktop/debian/copyright b/common/core/desktop/debian/copyright index c2c2c26644b0634717632ab602fa7345b9163d33..f5ee4873b0477de6db8d2b00711e76b226459e00 100644 --- a/common/core/desktop/debian/copyright +++ b/common/core/desktop/debian/copyright @@ -3,7 +3,7 @@ Upstream-Name: keyman-keyboardprocessor Upstream-Contact: SIL International Files: * -Copyright: Copyright (C) 2018 SIL International +Copyright: Copyright (C) 2018-2020 SIL International License: MIT License: MIT diff --git a/common/core/desktop/doc/BUILDING.md b/common/core/desktop/doc/BUILDING.md index af7f30c204a3919ae5f6c6d745944008b48f146f..9da4d83310f6bdfdaaccd510d2988d86426cacdf 100644 --- a/common/core/desktop/doc/BUILDING.md +++ b/common/core/desktop/doc/BUILDING.md @@ -3,7 +3,7 @@ ## Prerequisites - Python 3 - Meson build system. -- C++14 or later compiler. +- C++14 or later compiler (VC++ 2017 or later for Windows). - lib std::fs - kmcomp (for tests) -- must be added to path @@ -28,7 +28,14 @@ python3 -m pip install meson ``` ## Building -In your source directory do the following: +For Windows, use `build.bat` -- this handles environment and x86/x64 +cross-compiles with Visual Studio 2017+: + +``` +build.bat all +``` + +For all other platforms, in your source directory do the following: ``` cd desktop meson build --werror @@ -43,10 +50,10 @@ in this repo in /windows/src/developer/kmcomp. The compiler is currently availab PE executable only, but it does run under WINE. ### Windows -The search path can be edited through System settings / Advanced system settings / +The search path can be edited through System settings / Advanced system settings / Environment Variables / User environment variables. -If you have Keyman Developer installed, add %KeymanDeveloperPath% to your path. Otherwise, add +If you have Keyman Developer installed, add %KeymanDeveloperPath% to your path. Otherwise, add the path where you extracted the kmcomp archive. ### Linux diff --git a/common/core/desktop/doc/meson.build b/common/core/desktop/doc/meson.build index fceeca03f954a914abb8550b045b3c3aae7e8bbd..cae6b4be6010c53269de7d813ab35a798e1b4653 100644 --- a/common/core/desktop/doc/meson.build +++ b/common/core/desktop/doc/meson.build @@ -16,7 +16,7 @@ if hotdoc.found() output: 'hotdoc.json', configuration: cfg) deps = files( - '../include/keyboardprocessor.h.in', + '../include/keyman/keyboardprocessor.h.in', '../src/json.hpp', '../src/utfcodec.hpp' ) diff --git a/common/core/desktop/getversion.bat b/common/core/desktop/getversion.bat new file mode 100644 index 0000000000000000000000000000000000000000..dcab02e4d95e572491d8648757ed9fffa50e0850 --- /dev/null +++ b/common/core/desktop/getversion.bat @@ -0,0 +1,3 @@ +@echo off +REM Get the version number from VERSION.md +more ..\..\..\VERSION.md diff --git a/common/core/desktop/getversion.sh b/common/core/desktop/getversion.sh new file mode 100644 index 0000000000000000000000000000000000000000..c145bc6bc6413c1c8d691281f060d7d2857e999b --- /dev/null +++ b/common/core/desktop/getversion.sh @@ -0,0 +1,7 @@ +#!/bin/bash +# Get the version number from VERSION.md +# When building from a Linux source package, `VERSION.md` is in the +# same directory as this script. +VERSIONFILE=VERSION.md +[ -f ../../../VERSION.md ] && VERSIONFILE=../../../VERSION.md +cat $VERSIONFILE diff --git a/common/core/desktop/include/keyboardprocessor.h.in b/common/core/desktop/include/keyboardprocessor.h.in deleted file mode 100644 index e7b4a40ba822cfc995526a8ff45502a015abeb2a..0000000000000000000000000000000000000000 --- a/common/core/desktop/include/keyboardprocessor.h.in +++ /dev/null @@ -1,984 +0,0 @@ -/* - Copyright: © 2018 SIL International. - Description: Cross platform API C/C++ declarations for libkmnkbp keyboard - processor. - Create Date: 2 Oct 2018 - Authors: Tim Eves (TSE) - History: 18 Oct 2018 - TSE - Finialised verion of API. - 6 Oct 2018 - TSE - Move into keyman folder. - -*/ -#pragma once -/* -# Keyman Keyboard Processor API - -## Requirements -1. Cross platform. -2. Cross language. -3. Facilitate stateless operation of the Engine. -4. Keyboard format agnostic -- support both KMN and future LDML based keyboards. -5. Support querying Engine attributes. -6. Support querying Keyboard attributes. -7. Idempotent - - -## Design decisions in support of requirements: -- Use C or C99 types and calling convention for the interface, it has the - broadest language FFI support. [1,2] -- Have client (Platform layer) code load keyboards, manage & pass state. [3,4,7] -- Provide query calls to return static attributes data for keyboards and - engine [5,6] -- Provide get/set calls for client accessible keyboard state information [3,4] - - -## Glossary -- __Platform layer:__ -The code that consumes the Keyman Keyboard Processor API, and provides the -operating system-specific handling of keystroke events and integration with -applications. -- __Client Application:__ -The application that has the focus and receives text events from the Platform -layer. -- __Context:__ Text preceding the insertion point -- __Marker:__ Positional state that can be placed in the Context. -- __Keyboard:__ A set of rules for execution my an Engine -- __Option:__ A variable in a dynamic or static key value store. -- __Processor:__ -The component that implements this API and can parse and execute a particular -keyboard. -- __State:__ An object that hold internal state of the Processor for a given -insertion point -- __Action:__ -A directive output by the processor detailing how the Platform layer should -transform the Client Application's text buffer. There may be several items -produced by a single keyboard event. -- __Keyboard Event:__ -A virtual key event and modifier map received from the platform to be -processed with the state object for this Client application. -- __Virtual Key:__ -A code based on the US English layout, with values matching the Windows -virtual key codes. See keyboardprocessor_vkeys.h for definitions. -- __Modifier Key:__ -The set of Control, Shift, Alt, Caps Lock keys. On some platforms these may -have other names (e.g. Alt is called Option on macOS); other platform-specific -modifiers such as Windows key are excluded from this set. Some modifiers are -transient, such as Control, and others have long-lasting state, such as -Caps Lock. - -## API -### Namespace -All calls, types and enums are prefixed with the namespace identifier `km_kbp_` - -### API idioms -Almost all calls marshalling variable length aggregate data in or out of an API -object take the form: -> km_kbp_status *fn_name*(object_ref, buffer_ptr, size_ptr) - -where the buffer is nullable and all other arguments are required (will result -in an `KM_KBP_STATUS_INVALID_ARGUMENT` status being returned if nulled). When -`buffer` is `nullptr` or `0` the function will place the size of the required -buffer in the variable pointed to by `size_ptr`. - -Calls which result in the allocation of resources, regardless of resulting -ownership, are of the form: -> km_kbp_status *fn_name*(object_ref, out_ptr) - -where `out_ptr` is a valid pointer to a caller allocated variable to hold the -resulting ouput. This is often a reference to a created object. All arguments -are required (will result in an `KM_KBP_STATUS_INVALID_ARGUMENT` status being -returned if nulled). - -For accessors to fixed size attributes of an object these will take the form: -> attr_value __fn_name__(object_ref) - -`object_ref` is required to be valid and will result in a nonsense value being -returned if `nullptr` or `0`. - -All dispose calls are designed to accept null as a valid value and will do -nothing in that event. -```c -*/ -#include -#include -#include -#include - -#define KM_KBP_LIB_CURRENT @lib_curr@ -#define KM_KBP_LIB_AGE @lib_age@ -#define KM_KBP_LIB_REVISION @lib_rev@ - -#if defined(__cplusplus) -extern "C" -{ -#endif -// Basic types -// -#if defined(__cplusplus) -typedef char16_t km_kbp_cp; -typedef char32_t km_kbp_usv; -#else -typedef uint16_t km_kbp_cp; // code point -typedef uint32_t km_kbp_usv; // Unicode Scalar Value -#endif -typedef uint16_t km_kbp_virtual_key; // A virtual key code. -typedef uint32_t km_kbp_status; // Status return code. - -// Opaque object types. -// -typedef struct km_kbp_context km_kbp_context; -typedef struct km_kbp_keyboard km_kbp_keyboard; -typedef struct km_kbp_state km_kbp_state; -typedef struct km_kbp_options km_kbp_options; - -// Forward declarations -// -typedef struct km_kbp_option_item km_kbp_option_item; - -/*``` -### Error Handling -Error handling and success failure notification are communicated through a -general mechanism similar to COM’s `HRESULT` scheme (unlike COM, any non-zero -value is an error). Any functions that can fail will always return a status -value and all results are returned via outparams passed to the function. -```c -*/ -enum km_kbp_status_codes { - KM_KBP_STATUS_OK = 0, - KM_KBP_STATUS_NO_MEM = 1, - KM_KBP_STATUS_IO_ERROR = 2, - KM_KBP_STATUS_INVALID_ARGUMENT = 3, - KM_KBP_STATUS_KEY_ERROR = 4, - KM_KBP_STATUS_INSUFFICENT_BUFFER = 5, - KM_KBP_STATUS_INVALID_UTF = 6, - KM_KBP_STATUS_INVALID_KEYBOARD = 7, - KM_KBP_STATUS_OS_ERROR = 0x80000000 -}; - -/* -``` -The final status code KM_KBP_STATUS_OS_ERROR is intended to allow encapsulating -a platform error code; the remaining 31 low bits are the error code returned by -the OS for cases where the failure mode is platform specific. For HRESULT codes -this only permits failure codes to be passed. - - -### Context -The context is the text prior to the insertion point (caret, cursor). -The context is constructed by the Platform layer, typically by interrogating the -Client Application. The context will be updated by the engine for keystroke -events. If the Platform layer code caches the context, the context should be -reset when a context state change is detected. Context state changes can occur -when the user uses the mouse to move the insertion point, uses cursor keys, -switches applications or input fields, or presses hotkeys such as Ctrl+N to -start a new document. The full set of context state change triggers is up to the -Platform layer. - -Context can also contain positional Markers (also known as 'deadkeys' in kmn -keyboards), which are transitory state flags that are erased whenever a context -state change is detected. Markers are always controlled by the Engine. - -Contexts are always owned by their state. They may be set to a list of -context_items or interrogated for their current list of context items. -```c -*/ -enum km_kbp_context_type { - KM_KBP_CT_END, - KM_KBP_CT_CHAR, - KM_KBP_CT_MARKER -}; - -typedef struct { - uint8_t type; - uint8_t _reserved[3]; - union { - km_kbp_usv character; - uint32_t marker; - }; -} km_kbp_context_item; - -#define KM_KBP_CONTEXT_ITEM_END {KM_KBP_CT_END, {0,}, {0,}} -/* -``` -### `km_kbp_context_items_from_utf16` -##### Description: -Convert a UTF16 encoded Unicode string into an array of `km_kbp_context_item` -structures. Allocates memory as needed. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_NO_MEM`: In the event not enough memory can be allocated for the - output buffer. -- `KM_KBP_STATUS_INVALID_UTF`: In the event the UTF16 string cannot be decoded - because it contains unpaired surrogate codeunits. -##### Parameters: -- __text__: a pointer to a null terminated array of utf16 encoded data. -- __out_ptr__: a pointer to the result variable: - A pointer to the start of the `km_kbp_context_item` array containing the - representation of the input string. - Terminated with a type of `KM_KBP_CT_END`. Must be disposed of with - `km_kbp_context_items_dispose`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_context_items_from_utf16(km_kbp_cp const *text, - km_kbp_context_item **out_ptr); - -/* -``` -### `km_kbp_context_items_from_utf8` -##### Description: -Convert an UTF8 encoded Unicode string into an array of `km_kbp_context_item` -structures. Allocates memory as needed. -##### Status: -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_NO_MEM`: In the event it cannot allocate enough memory for the - output buffer. -- `KM_KBP_STATUS_INVALID_UTF`: In the event the UTF8 string cannot be -decoded. -##### Parameters: -- __text__: a pointer to a null terminated array of utf8 encoded data. -- __out_ptr__: a pointer to the result variable: - A pointer to the start of the `km_kbp_context_item` array containing the - representation of the input string. - Terminated with a type of `KM_KBP_CT_END`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_context_items_from_utf8(char const *text, - km_kbp_context_item **out_ptr); - -/* -``` -### `km_kbp_context_items_to_utf16` -##### Description: -Convert a context item array into a UTF-16 encoded string placing it into -the supplied buffer of specified size, and return the number codepoints -actually used in the conversion. If null is passed as the buffer the -number codeunits required is returned. This will strip markers from the -context during the conversion. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_INSUFFICENT_BUFFER`: If the buffer is not large enough. - `buf_size` will contain the space required. The contents of the buffer are - undefined. -##### Parameters: -- __context_items__: A pointer to the start of an array `km_kbp_context_item`. - Must be terminated with a type of `KM_KBP_CT_END`. -- __buf__: A pointer to the buffer to place the UTF-16 string into. May be be - null to request size calculation. -- __buf_size__: a pointer to the result variable: - A pointer the size of the supplied buffer in codeunits or filled with the - size required if `buf` is null. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_context_items_to_utf16(km_kbp_context_item const *item, - km_kbp_cp *buf, - size_t *buf_size); - -/* -``` -### `km_kbp_context_items_to_utf8` -##### Description: -Convert a context item array into a UTF-8 encoded string placing it into -the supplied buffer of specified size, and return the number codepoints -actually used in the conversion. If null is passed as the buffer the -number codeunits required is returned. This will strip markers from the -context during the conversion. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_INSUFFICENT_BUFFER`: If the buffer is not large enough. - `buf_size` will contain the space required. The contents of the buffer are - undefined. -##### Parameters: -- __context_items__: A pointer to the start of an array `km_kbp_context_item`. - Must be terminated with a type of `KM_KBP_CT_END`. -- __buf__: A pointer to the buffer to place the UTF-8 string into. May be be - null to request size calculation. -- __buf_size__: a pointer to the result variable: - A pointer the size of the supplied buffer in codeunits or filled with the - size required if `buf` is null. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_context_items_to_utf8(km_kbp_context_item const *item, - char *buf, - size_t *buf_size); - -/* -``` -### `km_kbp_context_items_dispose` -##### Description: -Free the allocated memory belonging to a `km_kbp_context_item` array previously -returned by `km_kbp_context_items_from_utf16` or `km_kbp_context_get` -##### Parameters: -- __context_items__: A pointer to the start of the `km_kbp_context_item` array - to be disposed of. - -```c -*/ -KMN_API -void -km_kbp_context_items_dispose(km_kbp_context_item *context_items); - -/* -``` -### `km_kbp_context_set` -##### Description: -Replace the contents of the current context with a new sequence of -`km_kbp_context_item` entries. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_NO_MEM`: In the event not enough memory can be allocated to - grow the context buffer internally. -##### Parameters: -- __context__: A pointer to an opaque context object -- __context_items__: A pointer to the start of the `km_kbp_context_item` - array containing the new context. It must be terminated with an item - of type `KM_KBP_CT_END`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_context_set(km_kbp_context *context, - km_kbp_context_item const *context_items); - -/* -``` -### `km_kbp_context_get` -##### Description: -Copies all items in the context into a new array and returns the new array. -This must be disposed of by caller using `km_kbp_context_items_dispose`. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_NO_MEM`: In the event not enough memory can be allocated for the - output buffer. -##### Parameters: -- __context_items__: A pointer to the start of an array `km_kbp_context_item`. -- __out__: a pointer to the result variable: - A pointer to the start of the `km_kbp_context_item` array containing a - copy of the context. Terminated with a type of `KM_KBP_CT_END`. Must be - disposed of with `km_kbp_context_items_dispose`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_context_get(km_kbp_context const *context_items, - km_kbp_context_item **out); - -/* -``` -### `km_kbp_context_clear` -##### Description: -Removes all context_items from the internal array. If `context` is -null, has no effect. -##### Parameters: -- __context__: A pointer to an opaque context object - -```c -*/ -KMN_API -void -km_kbp_context_clear(km_kbp_context *); - -/* -``` -### `km_kbp_context_length` -##### Description: -Return the number of items in the context. -##### Return: -The number of items in the context, and will return 0 if passed a null `context` -pointer. -##### Parameters: -- __context__: A pointer to an opaque context object - -```c -*/ -KMN_API -size_t -km_kbp_context_length(km_kbp_context *); - -/* -``` -### `km_kbp_context_append` -##### Description: -Add more items to the end (insertion point) of the context. If these exceed the -maximum context length the same number of items will be dropped from the -beginning of the context. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_NO_MEM`: In the event not enough memory can be allocated to - grow the context buffer internally. -##### Parameters: -- __context__: A pointer to an opaque context object. -- __context_items__: A pointer to the start of the `KM_KBP_CT_END` terminated - array of `km_kbp_context_item` to append. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_context_append(km_kbp_context *context, - km_kbp_context_item const *context_items); - -/* -``` -### `km_kbp_context_shrink` -##### Description: -Remove a specified number of items from the end of the context, optionally -add up to the same number of the supplied items to the front of the context. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_NO_MEM`: in the event it cannot allocated enough memory to grow - the context internally. -##### Parameters: -- __context__: A pointer to an opaque context object. -- __num__: The number of items to remove from the end of context. -- __context_items__: Pointer to the start of the `KM_KBP_CT_END` terminated - array of `km_kbp_context_item` to add to the front. Up to `num` items will - be prepended. This may be null if not required. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_context_shrink(km_kbp_context *context, - size_t num, - km_kbp_context_item const *prefix); - -/* -``` -### Action Items -These provide the results of processing a key event to the Platform layer and -should be processed by the Platform layer to issue commands to the os text -services framework to transform the text store in the Client Application, among -other actions. -```c -*/ -typedef struct { - uint8_t type; - uint8_t _reserved[sizeof(void*)-sizeof(uint8_t)]; - union { - uintptr_t marker; // MARKER type - km_kbp_option_item const * option; // OPT types - km_kbp_usv character; // CHAR type - km_kbp_virtual_key vkey; // VKEY types - size_t erased; // BACK type - }; -} km_kbp_action_item; - -enum km_kbp_action_type { - KM_KBP_IT_END = 0, // Marks end of action items list. - KM_KBP_IT_CHAR = 1, // A Unicode character has been generated. - KM_KBP_IT_MARKER = 2, // Correlates to kmn's "deadkey" markers. - KM_KBP_IT_ALERT = 3, // The keyboard has triggered a alert/beep/bell. - KM_KBP_IT_BACK = 4, // Delete the codepoint preceding the insertion point. - KM_KBP_IT_PERSIST_OPT = 5, // The indicated option needs to be stored. - KM_KBP_IT_EMIT_KEYSTROKE = 6, // Emit the current keystroke to the application - KM_KBP_IT_INVALIDATE_CONTEXT = 7, - // The processor requests that the context buffer be cleared; - // for applications where context is cached, this clears the context; - // for applications where context is read from the focused text store, - // the context is just re-read and markers flushed. - KM_KBP_IT_MAX_TYPE_ID -}; - - -/* -``` -### Options -A state’s default options are set from the keyboard at creation time and the -environment. The Platform layer is then is expected to apply any persisted -options it is maintaining. Options are passed into and out of API functions as -simple C arrays of `km_kbp_option_item` terminated with a `KM_KBP_OPTIONS_END` -sentinel value. A state's options are exposed and manipulatable via the -`km_kbp_options` API. All option values are of type C string. - -During processing when the Platform layer finds a PERSIST action type it should -store the updated option in the appropriate place, based on its scope. -For RESET the processor will apply the pristine value from the original scope, -the Platform layer should update that only if it manages a previously persisted -value. -```c -*/ - -enum km_kbp_option_scope { - KM_KBP_OPT_UNKNOWN = 0, - KM_KBP_OPT_KEYBOARD = 1, - KM_KBP_OPT_ENVIRONMENT = 2, - KM_KBP_OPT_MAX_SCOPES -}; - -struct km_kbp_option_item { - km_kbp_cp const * key; - km_kbp_cp const * value; - uint8_t scope; // Scope which an option belongs to. -}; - -#define KM_KBP_OPTIONS_END { 0, 0, 0 } - - -/* -``` -### `km_kbp_options_list_size` -##### Description: -Return the length of a terminated `km_kbp_option_item` array (options -list). -##### Return: -The number of items in the list or 0 if `opts` is null. -##### Parameters: -- __opts__: A pointer to a `KM_KBP_OPTIONS_END` terminated array of - `km_kbp_option_item` values. - -```c -*/ -KMN_API -size_t -km_kbp_options_list_size(km_kbp_option_item const *opts); - -/* -``` -### `km_kbp_options_lookup` -##### Description: -Lookup an option based on its key, in an options list. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null, or - if the scope is invalid. -- `KM_KBP_STATUS_KEY_ERROR`: The key cannot be found. -##### Parameters: -- __state__: An opaque pointer to a state object. -- __scope__: Which key-value store to interrogate. -- __key__: A UTF-16 string that matches the key in the target `km_kbp_option_item`. -- __value__: A pointer to the result variable: - A pointer to a copy of the UTF-16 string value; undefined if return status - is anything other than `KM_KBP_STATUS_OK`. This memory must be disposed of - with `km_kbp_cp_dispose`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_options_lookup(km_kbp_state const *state, - uint8_t scope, - km_kbp_cp const *key, - km_kbp_cp const **value); - -/* -``` -### `km_kbp_options_update` -##### Description: -Adds or updates one or more options from a list of `km_kbp_option_item`s. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_NO_MEM`: In the event an internal memory allocation fails. -- `KM_KBP_STATUS_KEY_ERROR`: The key cannot be found. -##### Parameters: -- __state__: An opaque pointer to a `km_kbp_state`. -- __new_opts__: An array of `km_kbp_option_item` objects to update or add. Must be - terminated with `KM_KBP_OPTIONS_END`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_options_update(km_kbp_state *state, - km_kbp_option_item const *new_opts); - -/* -``` -### `km_kbp_options_to_json` -##### Description: -Export the contents of a `km_kbp_options` array to a JSON formatted document and -place it in the supplied buffer, reporting how much space was used. If null is -passed as the buffer the number of bytes required is returned in `space`. If -there is insufficent space to hold the document the contents of the buffer is -undefined. The returned buffer uses UTF-8 encoding. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -- `KM_KBP_STATUS_NO_MEM`: In the event an internal memory allocation fails. -##### Parameters: -- __opts__: An opaque pointer to an options object. -- __buf__: A pointer to the buffer to place the C string containing the JSON -document into, can be null. -- __space__: A pointer to a size_t variable. This variable must contain the -number of bytes available in the buffer pointed to by `buf`, unless `buf` is -null. On return it will hold how many bytes were used. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_options_to_json(km_kbp_options const *opts, - char *buf, - size_t *space); - - -/* -``` -### Keyboards -A keyboard is a set of rules and transforms in a Processor specific format for -transforming key events into action items. The keyboard is parsed and loaded by -the processsor and made available in an immutable fashion for use with any number -of state objects. -```c -*/ -typedef struct { - km_kbp_cp const * version_string; // Processor specific version string. - km_kbp_cp const * id; // Keyman keyboard ID string. - km_kbp_path_name folder_path; // Path to the unpacked folder containing - // the keyboard and associated resources. - km_kbp_option_item const * default_options; -} km_kbp_keyboard_attrs; - -/* -``` -### `km_kbp_keyboard_load` -##### Description: -Parse and load keyboard from the supplied path and a pointer to the loaded keyboard -into the out paramter. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_NO_MEM`: In the event an internal memory allocation fails. -- `KM_KBP_STATUS_IO_ERROR`: - In the event the keyboard file is unparseable for any reason -- `KM_KBP_STATUS_INVALID_ARGUMENT`: - In the event the file doesn't exist or is inaccesible or `keyboard` is null. -- `KM_KBP_STATUS_OS_ERROR`: Bit 31 (high bit) set, bits 0-30 are an OS-specific - error code. -##### Parameters: -- __kb_path__: On Windows, a UTF-16 string; on other platforms, a C string: - contains a valid path to the keyboard file. -- __keyboard__: A pointer to result variable: - A pointer to the opaque keyboard object returned by the Processor. This - memory must be freed with a call to `km_kbp_keyboard_dispose`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_keyboard_load(km_kbp_path_name kb_path, - km_kbp_keyboard **keyboard); - -/* -``` -### `km_kbp_keyboard_dispose` -##### Description: -Free the allocated memory belonging to an opaque keyboard object previously -returned by `km_kbp_keyboard_load`. -##### Parameters: -- __keyboard__: A pointer to the opaque keyboard object to be - disposed of. - -```c -*/ -KMN_API -void -km_kbp_keyboard_dispose(km_kbp_keyboard *keyboard); - -/* -``` -### `km_kbp_keyboard_get_attrs` -##### Description: -Returns the const internal attributes of the keyboard. This structure is valid -for the lifetime of the opaque keyboard object. Do not modify the returned data. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: If non-optional parameters are null. -##### Parameters: -- __keyboard__: A pointer to the opaque keyboard object to be queried. -- __out__: A pointer to the result: - A pointer to a `km_kbp_keyboard_attrs` structure. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_keyboard_get_attrs(km_kbp_keyboard const *keyboard, - km_kbp_keyboard_attrs const **out); - -/* -``` -### State -A State object maintains all per keyboard related state including context -and dynamic options ("option stores" in kmn format). - -```c -*/ - -/* -``` -### `km_kbp_state_create` -##### Description: -Create a keyboard processor state object, maintaining state for the keyboard in -the environment passed. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_NO_MEM`: - In the event memory is unavailable to allocate a state object. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: - In the event the `keyboard` or `out` pointer are null. -##### Parameters: -- __keyboard__: -A pointer to the opaque keyboard object this object will hold state for. -- __env__: -The array of `km_kbp_option_item` key/value pairs used to initialise the -environment, terminated by `KM_KBP_OPTIONS_END`. -- __out__: -A pointer to result variable: A pointer to the opaque state object -returned by the Processor, initalised to maintain state for `keyboard`. -This must be disposed of by a call to `km_kbp_state_dispose`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_state_create(km_kbp_keyboard *keyboard, - km_kbp_option_item const *env, - km_kbp_state **out); - -/* -``` -### `km_kbp_state_clone` -##### Description: -Clone an existing opaque state object. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_NO_MEM`: -In the event memory is unavailable to allocate a state object. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: -In the event the `state` or `out` pointer are null. -##### Parameters: -- __state__: -A pointer to the opaque statea object to be cloned. -- __out__: -A pointer to result variable: A pointer to the opaque state object -returned by the Processor, cloned from the existing object `state`. This -must be disposed of by a call to `km_kbp_state_dispose`. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_state_clone(km_kbp_state const *state, - km_kbp_state **out); - -/* -``` -### `km_kbp_state_dispose` -##### Description: -Free the allocated resources belonging to a `km_kbp_state` object previously -returned by `km_kbp_state_create` or `km_kbp_state_clone`. After this all -pointers previously returned by any km_kbp_state family of calls will become -invalid. -##### Parameters: -- __state__: A pointer to the opaque state object to be disposed. - -```c -*/ -KMN_API -void -km_kbp_state_dispose(km_kbp_state *state); - -/* -``` -### `km_kbp_state_context` -##### Description: -Get access to the state object's context. -##### Return: -A pointer to an opaque state object. This pointer is valid for the lifetime -of the state object. If null is passed in, then null is returned. -##### Parameters: -- __state__: A pointer to the opaque state object to be queried. - -```c -*/ -KMN_API -km_kbp_context * -km_kbp_state_context(km_kbp_state *state); - -/* -``` -### `km_kpb_state_options` -##### Description: -Get access to the state object's options. -##### Return: -A pointer to an opaque state object. This pointer is valid for the lifetime -of the state object. If null is passed in, then null is returned. -##### Parameters: -- __state__: A pointer to the opaque state object to be queried. - -```c -*/ -KMN_API -km_kbp_options * -km_kbp_state_options(km_kbp_state *state); - -/* -``` -### `km_kbp_state_action_items` -##### Description: -Get the list of action items generated by the last call to -`km_kbp_process_event`. -##### Return: -A pointer to a `km_kbp_action_item` list, of `*num_items` in length. This data -becomes invalid when the state object is destroyed, or after a call to -`km_kbp_process_event`. Do not modify the contents of this data. The returned -array is terminated with a `KM_KBP_IT_END` entry. -##### Parameters: -- __state__: A pointer to the opaque `km_kbp_state` object to be queried. -- __num_items__: -A pointer to a result variable: The number of items in the action item list -including the `KM_KBP_IT_END` terminator. May be null if not that -information is required. - -```c -*/ -KMN_API -km_kbp_action_item const * -km_kbp_state_action_items(km_kbp_state const *state, - size_t *num_items); - -/* -``` -### `km_kpb_state_to_json` -##### Description: -Export the internal state of a `km_kbp_state` object to a JSON format document -and place it in the supplied buffer, reporting how much space was used. If null -is passed as the buffer the number of bytes required is returned. If there is -insufficent space to hold the document, the contents of the buffer is undefined. -The encoding of the returned data is UTF-8. - -__WARNING__: The structure and format of the JSON document while independently -versioned is not part of this API and is intended solely for use in diagnostics -or by development and debugging tools which are aware of processor -implementation details. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_NO_MEM`: In the event an internal memory allocation fails. -##### Parameters: -- __state__: An pointer to an opaque state object. -- __buf__: A pointer to the buffer to place the C string containing the JSON -document into. May be null. -- __space__: A pointer to a size_t variable. This variable must contain the -number of bytes available in the buffer pointed to by `buf`, unless `buf` is -null. On return it will hold how many bytes were used. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_state_to_json(km_kbp_state const *state, - char *buf, - size_t *space); - -/* -``` -### Processor -```c -*/ -typedef struct { - size_t max_context; // Maximum context size supported by processor. - uint16_t current; // Current API number supported. - uint16_t revision; // Implementation number of current API. - uint16_t age; // current - age == Oldest API number supported. - uint16_t technology; // A bit field specifiying which Keyboard - // technologies the engine supports. - char const *vendor; // Implementor of the processor. -} km_kbp_attr; - -enum km_kbp_tech_value { - KM_KBP_TECH_UNSPECIFIED = 0, - KM_KBP_TECH_MOCK = 1 << 0, - KM_KBP_TECH_KMX = 1 << 1, - KM_KBP_TECH_LDML = 1 << 2 -}; - - -/* -``` -### `km_kbp_get_engine_attrs` -##### Description: -Get access processors attributes describing version and technology implemented. -##### Return: -A pointer to a `km_kbp_attr` structure. Do not modify the contents of this -structure. -##### Parameters: -- __state__: An opaque pointer to an `km_kbp_state`. -```c -*/ -KMN_API -km_kbp_attr const * -km_kbp_get_engine_attrs(km_kbp_state const *state); - -/* -``` -### `km_kbp_cp_dispose` -##### Description: -Free the allocated memory belonging to a `km_kbp_cp` array previously -returned by `km_kbp_options_lookup`. -##### Parameters: -- __cp__: A pointer to the start of the `km_kbp_cp` array - to be disposed of. - -```c -*/ -KMN_API -void -km_kbp_cp_dispose(km_kbp_cp const *cp); - -/* -``` -### `km_kbp_process_event` -##### Description: -Run the keyboard on an opaque state object with the provided virtual key and modifer -key state. Updates the state object as appropriate and fills out its action list. - -The action list will be cleared at the start of this call; options and context in -the state may also be modified. -##### Return status: -- `KM_KBP_STATUS_OK`: On success. -- `KM_KBP_STATUS_NO_MEM`: -In the event memory is unavailable to allocate internal buffers. -- `KM_KBP_STATUS_INVALID_ARGUMENT`: -In the event the `state` pointer is null or an invalid virtual key or modifier -state is passed. - -##### Parameters: -- __state__: A pointer to the opaque state object. -- __vk__: A virtual key to be processed. -- __modifier_state__: -The combinations of modifier keys set at the time key `vk` was pressed, bitmask -from the `km_kbp_modifier_state` enum. - -```c -*/ -KMN_API -km_kbp_status -km_kbp_process_event(km_kbp_state *state, - km_kbp_virtual_key vk, - uint16_t modifier_state); - -#if defined(__cplusplus) -} // extern "C" -#endif -/*``` -*/ diff --git a/common/core/desktop/include/keyman/keyboardprocessor.h.in b/common/core/desktop/include/keyman/keyboardprocessor.h.in index 5d1ba0624e538e08909e5778068d7642ae093f26..2f31bb36545c0381b8e786d0ded9595749209c0a 100644 --- a/common/core/desktop/include/keyman/keyboardprocessor.h.in +++ b/common/core/desktop/include/keyman/keyboardprocessor.h.in @@ -256,7 +256,7 @@ km_kbp_context_items_from_utf8(char const *text, ### `km_kbp_context_items_to_utf16` ##### Description: Convert a context item array into a UTF-16 encoded string placing it into -the supplied buffer of specified size, and return the number codepoints +the supplied buffer of specified size, and return the number of code units actually used in the conversion. If null is passed as the buffer the number codeunits required is returned. This will strip markers from the context during the conversion. @@ -269,11 +269,11 @@ context during the conversion. ##### Parameters: - __context_items__: A pointer to the start of an array `km_kbp_context_item`. Must be terminated with a type of `KM_KBP_CT_END`. -- __buf__: A pointer to the buffer to place the UTF-16 string into. May be be - null to request size calculation. +- __buf__: A pointer to the buffer to place the UTF-16 string into. + May be null to request size calculation. - __buf_size__: a pointer to the result variable: - A pointer the size of the supplied buffer in codeunits or filled with the - size required if `buf` is null. + The size of the supplied buffer in codeunits if `buf` is given. + On return will be the size required if `buf` is null. ```c */ @@ -288,7 +288,7 @@ km_kbp_context_items_to_utf16(km_kbp_context_item const *item, ### `km_kbp_context_items_to_utf8` ##### Description: Convert a context item array into a UTF-8 encoded string placing it into -the supplied buffer of specified size, and return the number codepoints +the supplied buffer of specified size, and return the number of code units actually used in the conversion. If null is passed as the buffer the number codeunits required is returned. This will strip markers from the context during the conversion. @@ -301,11 +301,11 @@ context during the conversion. ##### Parameters: - __context_items__: A pointer to the start of an array `km_kbp_context_item`. Must be terminated with a type of `KM_KBP_CT_END`. -- __buf__: A pointer to the buffer to place the UTF-8 string into. May be be - null to request size calculation. +- __buf__: A pointer to the buffer to place the UTF-8 string into. + May be null to request size calculation. - __buf_size__: a pointer to the result variable: - A pointer the size of the supplied buffer in codeunits or filled with the - size required if `buf` is null. + The size of the supplied buffer in codeunits if `buf` is given. + On return will be the size required if `buf` is null. ```c */ diff --git a/common/core/desktop/meson.build b/common/core/desktop/meson.build index 175ce992ec29c47a78ea4e1fe736f06db34b2a6c..60768ca2eb64defa4690213b3b82a238298112e0 100644 --- a/common/core/desktop/meson.build +++ b/common/core/desktop/meson.build @@ -6,10 +6,7 @@ # project('keyboardprocessor', 'cpp', 'c', - # Get version number from file (VERSION.md is in this directory for source package) - # Fallback to "more" for Windows compatbility - version: run_command(find_program('cat', 'more'), - files('VERSION.md')).stdout().strip(), + version: run_command(find_program('getversion.bat', 'getversion.sh')).stdout().strip(), license: 'MIT', default_options : ['buildtype=release', 'cpp_std=c++14']) diff --git a/common/core/desktop/src/kmx/kmx_context.cpp b/common/core/desktop/src/kmx/kmx_context.cpp index 9ee3c5584df8cc47ae02d17c137c977e8a529120..722b1a70812f4826f423be0af345de83bb8c3759 100644 --- a/common/core/desktop/src/kmx/kmx_context.cpp +++ b/common/core/desktop/src/kmx/kmx_context.cpp @@ -16,6 +16,8 @@ KMX_Context::KMX_Context() void KMX_Context::Add(KMX_WCHAR ch) { + DebugLog("KMX_Context::Add(%x): ENTER [%d]: %s", ch, pos, Debug_UnicodeString(CurContext)); + if(pos == MAXCONTEXT - 1) { memmove(CurContext, &CurContext[1], MAXCONTEXT*2 - 2); pos--; @@ -24,7 +26,7 @@ void KMX_Context::Add(KMX_WCHAR ch) CurContext[pos++] = ch; CurContext[pos] = 0; - DebugLog("KMX_Context: Add(%x) [%d]: %s", ch, pos, Debug_UnicodeString(CurContext)); + //DebugLog("KMX_Context::Add(%x): EXIT [%d]: %s", ch, pos, Debug_UnicodeString(CurContext)); } @@ -32,7 +34,7 @@ KMX_WCHAR *KMX_Context::Buf(int n) { KMX_WCHAR *p; - for(p = (KMX_WCHAR *) u16chr(CurContext, 0); n > 0 && p > CurContext; p = decxstr(p), n--); + for(p = (KMX_WCHAR *) u16chr(CurContext, 0); n > 0 && p > CurContext; p = decxstr(p, CurContext), n--); if(n > 0) return NULL; return p; @@ -40,6 +42,7 @@ KMX_WCHAR *KMX_Context::Buf(int n) void KMX_Context::Delete() { + DebugLog("KMX_Context::Delete: ENTER: %s", Debug_UnicodeString(CurContext)); if (CharIsDeadkey()) { pos -= 2; } else if (CharIsSurrogatePair()) { @@ -48,10 +51,12 @@ void KMX_Context::Delete() if(pos > 0) pos--; CurContext[pos] = 0; + //DebugLog("KMX_Context::Delete: EXIT: %s", Debug_UnicodeString(CurContext)); } void KMX_Context::Reset() { + DebugLog("KMX_Context::Reset"); pos = 0; CurContext[0] = 0; } @@ -76,6 +81,7 @@ void KMX_Context::CopyFrom(KMX_Context *source) // I3575 void KMX_Context::Set(const KMX_WCHAR *buf) { + DebugLog("KMX_Context::Set(%s): ENTER: %s", Debug_UnicodeString(buf), Debug_UnicodeString(CurContext, 1)); const KMX_WCHAR *p; KMX_WCHAR *q; @@ -84,14 +90,14 @@ void KMX_Context::Set(const KMX_WCHAR *buf) // of the string, not the start p = u16chr(buf, 0); q = (KMX_WCHAR*)p; - while(p > buf && (int)(q-p) < MAXCONTEXT - 1) { - p = decxstr((KMX_WCHAR*)p); + while(p > buf && (intptr_t)(q-p) < MAXCONTEXT - 1) { + p = decxstr((KMX_WCHAR*)p, (KMX_WCHAR*)buf); } // If the first character in the buffer is a surrogate pair, // or a deadkey, our buffer may be too long, so move to the // next character in the buffer - if ((int)(q-p) > MAXCONTEXT - 1) { + if ((intptr_t)(q-p) > MAXCONTEXT - 1) { p = incxstr((KMX_WCHAR*)p); } @@ -101,15 +107,17 @@ void KMX_Context::Set(const KMX_WCHAR *buf) } *q = 0; - pos = (int)(q-CurContext); - CurContext[MAXCONTEXT-1] = 0; + pos = (intptr_t)(q-CurContext); + CurContext[MAXCONTEXT-1] = 0; + + //DebugLog("KMX_Context::Set(%s): EXIT: %s", Debug_UnicodeString(buf), Debug_UnicodeString(CurContext, 1)); } KMX_BOOL KMX_Context::CharIsDeadkey() { if(pos < 3) return FALSE; - return CurContext[pos-3] == UC_SENTINEL && + return CurContext[pos-3] == UC_SENTINEL && CurContext[pos-2] == CODE_DEADKEY; } diff --git a/common/core/desktop/src/kmx/kmx_context.h b/common/core/desktop/src/kmx/kmx_context.h index 6aa978ce3651e804a117759117cd41ef71234f17..8e3664d82f205787af21dea88a42bb93a8a86550 100644 --- a/common/core/desktop/src/kmx/kmx_context.h +++ b/common/core/desktop/src/kmx/kmx_context.h @@ -28,6 +28,7 @@ public: void Get(KMX_WCHAR *buf, int bufsize); void Set(const KMX_WCHAR *buf); KMX_WCHAR *Buf(int n); + KMX_WCHAR *GetFullContext() { return CurContext; } KMX_BOOL CharIsDeadkey(); KMX_BOOL CharIsSurrogatePair(); }; diff --git a/common/core/desktop/src/kmx/kmx_debug.cpp b/common/core/desktop/src/kmx/kmx_debug.cpp index 05ef1716915a3cb704613a9a3353282c0b77dc42..46d75ac35d3692963d9aa2debf82156ba4c5e9d0 100644 --- a/common/core/desktop/src/kmx/kmx_debug.cpp +++ b/common/core/desktop/src/kmx/kmx_debug.cpp @@ -81,7 +81,7 @@ int km::kbp::kmx::DebugLog_1(const char *file, int line, const char *function, c const char *km::kbp::kmx::Debug_ModifierName(KMX_UINT modifiers) { #ifdef _MSC_VER __declspec(thread) -#endif +#endif static char buf[256]; buf[0] = 0; for(int i = 0; s_modifier_names[i].name; i++) @@ -97,7 +97,7 @@ const char *km::kbp::kmx::Debug_ModifierName(KMX_UINT modifiers) { const char *km::kbp::kmx::Debug_VirtualKey(KMX_WORD vk) { #ifdef _MSC_VER __declspec(thread) -#endif +#endif static char buf[256]; if (!ShouldDebug()) { return ""; @@ -118,7 +118,7 @@ const char *km::kbp::kmx::Debug_UnicodeString(PKMX_WCHAR s, int x) { } #ifdef _MSC_VER __declspec(thread) -#endif +#endif static char bufout[2][128 * 7]; KMX_WCHAR *p; char *q; @@ -137,12 +137,12 @@ const char *km::kbp::kmx::Debug_UnicodeString(std::u16string s, int x) { } #ifdef _MSC_VER __declspec(thread) -#endif +#endif static char bufout[2][128 * 7]; auto p = s.begin(); char *q; bufout[x][0] = 0; - for (q = bufout[x]; (int)(q-bufout[x]) < (128*7) && p != s.end(); p++) + for (q = bufout[x]; (intptr_t)(q-bufout[x]) < (128*7) && p != s.end(); p++) { sprintf(q, "U+%4.4X ", *p); q = strchr(q, 0); } diff --git a/common/core/desktop/src/kmx/kmx_processor.cpp b/common/core/desktop/src/kmx/kmx_processor.cpp index 149cf99129645f92698235e95dcacbe21223c34b..eb189f4ed8645e9b40fdb6c219839543204f6470 100644 --- a/common/core/desktop/src/kmx/kmx_processor.cpp +++ b/common/core/desktop/src/kmx/kmx_processor.cpp @@ -158,6 +158,7 @@ KMX_BOOL KMX_Processor::ProcessGroup(LPGROUP gp, KMX_BOOL *pOutputKeystroke) */ DebugLog("m_state.vkey: %s shiftFlags: %x; charCode: %X", Debug_VirtualKey(m_state.vkey), m_modifiers, m_state.charCode); // I4582 + DebugLog("m_context: %s", Debug_UnicodeString(m_context.GetFullContext())); if(gp) { @@ -264,7 +265,7 @@ KMX_BOOL KMX_Processor::ProcessGroup(LPGROUP gp, KMX_BOOL *pOutputKeystroke) p = kkp->dpOutput; if(*p != UC_SENTINEL || *(p+1) != CODE_CONTEXT) { - for(p = decxstr((KMX_WCHAR *) u16chr(m_miniContext, 0)); p >= m_miniContext; p = decxstr(p)) + for(p = decxstr((KMX_WCHAR *) u16chr(m_miniContext, 0), m_miniContext); p >= m_miniContext; p = decxstr(p, m_miniContext)) { if(*p == UC_SENTINEL) switch(*(p+1)) diff --git a/common/core/desktop/src/kmx/kmx_xstring.cpp b/common/core/desktop/src/kmx/kmx_xstring.cpp index 518e957c580e917b8106681f8077a3cc0cc63717..75f16ed795e2620c9150f41cedb6d301f2526c07 100644 --- a/common/core/desktop/src/kmx/kmx_xstring.cpp +++ b/common/core/desktop/src/kmx/kmx_xstring.cpp @@ -135,22 +135,34 @@ PKMX_WCHAR km::kbp::kmx::incxstr(PKMX_WCHAR p) } } -PKMX_WCHAR km::kbp::kmx::decxstr(PKMX_WCHAR p) +PKMX_WCHAR km::kbp::kmx::decxstr(PKMX_WCHAR p, PKMX_WCHAR pStart) { + if(p <= pStart) { + assert("Attempted to move prior to start of string"); + return NULL; + } + p--; if(*p == UC_SENTINEL_EXTENDEDEND) { int n = 0; while(*p != UC_SENTINEL && n < 10) { p--; n++; } + + if(p < pStart) { + // May be a malformed virtual key + return pStart; + } return p; } + if(p == pStart) return p; // Don't allow test before pStart + if(*p >= 0xDC00 && *p <= 0xDFFF && *(p-1) >= 0xD800 && *(p-1) <= 0xDBFF) { return p-1; } else if(*(p-1) == UC_SENTINEL) return p-1; - else if(*(p-2) == UC_SENTINEL) + else if(p > pStart+1 && *(p-2) == UC_SENTINEL) { switch(*(p-1)) { @@ -166,7 +178,7 @@ PKMX_WCHAR km::kbp::kmx::decxstr(PKMX_WCHAR p) return p-2; } } - else if(*(p-3) == UC_SENTINEL) + else if(p > pStart+2 && *(p-3) == UC_SENTINEL) { switch(*(p-2)) { @@ -176,7 +188,7 @@ PKMX_WCHAR km::kbp::kmx::decxstr(PKMX_WCHAR p) return p-3; } } - else if(*(p-4) == UC_SENTINEL) + else if(p > pStart+3 && *(p-4) == UC_SENTINEL) { switch(*(p-3)) { @@ -215,7 +227,7 @@ int km::kbp::kmx::xstrpos(PKMX_WCHAR p1, PKMX_WCHAR p) PKMX_WCHAR km::kbp::kmx::xstrchr(PKMX_WCHAR buf, PKMX_WCHAR chr) { for(PKMX_WCHAR q = incxstr(buf); *buf; buf = q, q = incxstr(buf)) - if(!u16ncmp(buf, chr, (int)(q-buf))) + if(!u16ncmp(buf, chr, (intptr_t)(q-buf))) return buf; return NULL; } @@ -224,7 +236,7 @@ int km::kbp::kmx::xchrcmp(PKMX_WCHAR ch1, PKMX_WCHAR ch2) { PKMX_WCHAR nch1 = incxstr(ch1); if(nch1 == ch1) return *ch2 - *ch1; /* comparing *ch2 to nul */ - return u16ncmp(ch1, ch2, (int)(nch1-ch1)); + return u16ncmp(ch1, ch2, (intptr_t)(nch1-ch1)); } PKMX_WCHAR km::kbp::kmx::strtowstr(PKMX_CHAR in) diff --git a/common/core/desktop/src/kmx/kmx_xstring.h b/common/core/desktop/src/kmx/kmx_xstring.h index 3c425e16bec360b5f0220cc9d248ab918dc0da44..c7461b026a254a44b825d94b710da8dd62fb1005 100644 --- a/common/core/desktop/src/kmx/kmx_xstring.h +++ b/common/core/desktop/src/kmx/kmx_xstring.h @@ -16,7 +16,7 @@ namespace kmx { #define Uni_UTF32ToSurrogate2(ch) (((ch) - 0x10000) % 0x400 + 0xDC00) PKMX_WCHAR incxstr(PKMX_WCHAR p); -PKMX_WCHAR decxstr(PKMX_WCHAR p); +PKMX_WCHAR decxstr(PKMX_WCHAR p, PKMX_WCHAR pStart); int xstrlen(PKMX_WCHAR p); int xstrlen_ignoreifopt(PKMX_WCHAR p); int xstrpos(PKMX_WCHAR p1, PKMX_WCHAR p); diff --git a/common/core/desktop/tests/unit/kmx/043 - output and keystroke.kmn b/common/core/desktop/tests/unit/kmx/043 - output and keystroke.kmn new file mode 100644 index 0000000000000000000000000000000000000000..6a5d0c6085efec54b141b3780adc34119ca0c8d3 --- /dev/null +++ b/common/core/desktop/tests/unit/kmx/043 - output and keystroke.kmn @@ -0,0 +1,26 @@ +c Description: Tests the 'emit default key' function by having an empty 'using keys' final group +c keys: [K_1][K_2][K_3] +c expected: abd3 +c context: + +store(&version) '10.0' + +begin Unicode > use(Main) + +group(Main) using keys + ++ [K_1] > 'a' +'b' + [K_2] > context use(b) +'abc' + [K_3] > context(1) context(2) 'd' use(emit) + +match > use(a) + +group(a) + +'a' > 'b' + +group(b) + +'b' > 'abc' + +group(emit) using keys diff --git a/common/core/desktop/tests/unit/kmx/043 - output and keystroke.kmx b/common/core/desktop/tests/unit/kmx/043 - output and keystroke.kmx new file mode 100644 index 0000000000000000000000000000000000000000..9cfa4295743210da5f472ff7df972bcc0185501d Binary files /dev/null and b/common/core/desktop/tests/unit/kmx/043 - output and keystroke.kmx differ diff --git a/common/core/desktop/tests/unit/kmx/kmx.cpp b/common/core/desktop/tests/unit/kmx/kmx.cpp index bb7c2557328f99b862ea535294b94f101f124ad7..588b3dcef22c83c7097b1ab566ed0d665cb43bad 100644 --- a/common/core/desktop/tests/unit/kmx/kmx.cpp +++ b/common/core/desktop/tests/unit/kmx/kmx.cpp @@ -3,6 +3,8 @@ Description: Tests for kmx integration Create Date: 30 Oct 2018 Authors: Marc Durdin (MD), Tim Eves (TSE) + + Note: Exit codes will be 100*LINE + ERROR CODE, e.g. 25005 is code 5 on line 250 */ #include #include @@ -206,8 +208,8 @@ void apply_action(km_kbp_state const *, km_kbp_action_item const & act, std::u16 << "=" << act.option->value << " persistence requested" << std::endl; if (!found) { - std::cout << "option " - << act.option->key + std::cout << "option " + << act.option->key << " saved but no expected output found. Suggestion: update test to include saved option value." << std::endl; } } @@ -319,7 +321,7 @@ int run_test(const km::kbp::path & source, const km::kbp::path & compiled) { std::cout << "expected : " << expected << std::endl; std::cout << "text store: " << text_store << std::endl; - std::cout << "result : " << buf << std::endl; + std::cout << "context : " << buf << std::endl; // Compare internal context with expected result if (buf != expected) return __LINE__; diff --git a/common/core/desktop/tests/unit/kmx/meson.build b/common/core/desktop/tests/unit/kmx/meson.build index 05f66f38e179e38762f5683285c8cf4a95969e2a..bf41ad3b16e3f6e3275d31225f764eaf949a21a2 100644 --- a/common/core/desktop/tests/unit/kmx/meson.build +++ b/common/core/desktop/tests/unit/kmx/meson.build @@ -57,7 +57,8 @@ tests = [ '039 - generic ctrlalt', '040 - long context', '041 - long context and deadkeys', - '042 - long context and split deadkeys' + '042 - long context and split deadkeys', + '043 - output and keystroke' ] if build_machine.system() == 'windows' diff --git a/common/core/web/input-processor/.gitignore b/common/core/web/input-processor/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c613a78f7dc4ebef65a0845ab2bd378d31784f56 --- /dev/null +++ b/common/core/web/input-processor/.gitignore @@ -0,0 +1,18 @@ +# Build products +src/environment.inc.ts + +# Legacy build folders. +output/ +build/ +embedded/ + +# Current build output folder (matches standard node publish location). +dist/ + +# Other local files. +node_modules/ +unit_tests/modernizr.js +source/environment.inc.ts +.idea/**/*.xml +*.iml +*.kpj.user \ No newline at end of file diff --git a/common/core/web/input-processor/README.md b/common/core/web/input-processor/README.md new file mode 100644 index 0000000000000000000000000000000000000000..825c2bcceef51cc45725c7292b459a280f3b8ffc --- /dev/null +++ b/common/core/web/input-processor/README.md @@ -0,0 +1,21 @@ +# Keyman: Keyboard Processor Module +The Original Code is (C) 2017-2020 SIL International + +The Keyboard Processor module is an internal component of KeymanWeb, seen within this repo at /web/. + +## Minimum Compilation Requirements + +* A local installation of [Node.js](https://nodejs.org/) v8.9+. + * Builds will call `npm install` to automatically install further necessary build dependencies. + + * Linux users can run the following to update to LTS version of nodejs + +``` +sudo apt-get install python-software-properties +curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - +sudo apt-get install nodejs +``` + +********************************************************************** + +The build script may be found at src/build.sh. \ No newline at end of file diff --git a/common/core/web/input-processor/package-lock.json b/common/core/web/input-processor/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..c375971e9355ac488eab5f99575f35022a4106ee --- /dev/null +++ b/common/core/web/input-processor/package-lock.json @@ -0,0 +1,312 @@ +{ + "name": "@keymanapp/input-processor", + "version": "14.0.144", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/node": { + "version": "11.15.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-11.15.10.tgz", + "integrity": "sha512-FHli7aK/ViA02vbWKmiNejJW4BCJxCVb6macS5gi71fST+UrrdqcES6Lh5rx23hU1QCBeUNXfPquYr9jJv7FuA==" + }, + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==" + }, + "assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "browser-stdout": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", + "dev": true + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" + }, + "chai": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.2.0.tgz", + "integrity": "sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw==", + "dev": true, + "requires": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^3.0.1", + "get-func-name": "^2.0.0", + "pathval": "^1.1.0", + "type-detect": "^4.0.5" + } + }, + "check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", + "dev": true + }, + "commander": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz", + "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-eql": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", + "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "dev": true, + "requires": { + "type-detect": "^4.0.0" + } + }, + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==" + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "eventemitter3": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.0.tgz", + "integrity": "sha512-qerSRB0p+UDEssxTtm6EDKcE7W4OaoisfIMl4CngyEhjpYglocpNg6UEqCvemdGhosAsg4sO2dXJOdyBifPGCg==" + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "get-func-name": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", + "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "growl": { + "version": "1.10.5", + "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", + "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "he": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "mocha": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-5.2.0.tgz", + "integrity": "sha512-2IUgKDhc3J7Uug+FxMXuqIyYzH7gJjXECKe/w43IGgQHTSj3InJi+yAA7T24L9bQMRKiUEHxEX37G5JpVUGLcQ==", + "dev": true, + "requires": { + "browser-stdout": "1.3.1", + "commander": "2.15.1", + "debug": "3.1.0", + "diff": "3.5.0", + "escape-string-regexp": "1.0.5", + "glob": "7.1.2", + "growl": "1.10.5", + "he": "1.1.1", + "minimatch": "3.0.4", + "mkdirp": "0.5.1", + "supports-color": "5.4.0" + }, + "dependencies": { + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + } + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "pathval": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz", + "integrity": "sha1-uULm1L3mUwBe9rcTYd74cn0GReA=", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" + }, + "source-map-support": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.16.tgz", + "integrity": "sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ==", + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "ts-node": { + "version": "8.8.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-8.8.2.tgz", + "integrity": "sha512-duVj6BpSpUpD/oM4MfhO98ozgkp3Gt9qIp3jGxwU2DFvl/3IRaEAvbLa8G60uS7C77457e/m5TMowjedeRxI1Q==", + "requires": { + "arg": "^4.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "source-map-support": "^0.5.6", + "yn": "3.1.1" + } + }, + "type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==" + } + } +} diff --git a/common/core/web/input-processor/package.json b/common/core/web/input-processor/package.json new file mode 100644 index 0000000000000000000000000000000000000000..aa3533490d4383618d9bca6ba220b057eb7e0e17 --- /dev/null +++ b/common/core/web/input-processor/package.json @@ -0,0 +1,41 @@ +{ + "name": "@keymanapp/input-processor", + "version": "14.0.144", + "description": "The core text and prediction processing engine for KeymanWeb", + "repository": { + "type": "git", + "url": "git+https://github.com/keymanapp/keyman.git" + }, + "keywords": [ + "input", + "languages", + "keyboards" + ], + "author": "SIL International", + "license": "MIT", + "bugs": { + "url": "https://github.com/keymanapp/keyman/issues" + }, + "homepage": "https://github.com/keymanapp/keyman#readme", + "devDependencies": { + "@keymanapp/resources-gosh": "^14.0.144", + "chai": "^4.2.0", + "mocha": "^5.2.0", + "typescript": "^3.8.3" + }, + "scripts": { + "lerna": "cd ../ && npm run lerna --", + "tsc": "tsc", + "test": "gosh ./unit_tests/test.sh" + }, + "dependencies": { + "@keymanapp/keyboard-processor": "^14.0.144", + "@keymanapp/lexical-model-layer": "^14.0.144", + "@keymanapp/models-types": "^14.0.144", + "@keymanapp/web-environment": "^14.0.144", + "@keymanapp/web-utils": "^14.0.144", + "@types/node": "^11.9.4", + "eventemitter3": "^4.0.0", + "ts-node": "^8.0.2" + } +} diff --git a/common/core/web/input-processor/src/build.sh b/common/core/web/input-processor/src/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..858a6670b3da09e73b5782b133adca43ad6aa372 --- /dev/null +++ b/common/core/web/input-processor/src/build.sh @@ -0,0 +1,88 @@ +#! /bin/bash +# +# Compile KeymanWeb's 'keyboard-processor' module, one of the components of Web's 'core' module. +# + +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../../../../resources/build/build-utils.sh" +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +# This script runs from its own folder +cd "$(dirname "$THIS_SCRIPT")" + +display_usage ( ) { + echo "build.sh [-skip-package-install | -S] [-test]" + echo + echo " -test to compile for testing without re-fetching external dependencies" + echo " or recompiling the lm-layer module." + echo " -skip-package-install (or -S) skips the `lerna bootstrap` dependency check." + echo "" + echo " If more than one target is specified, the last one will take precedence." + exit 1 +} + +# Establish default build parameters +set_default_vars ( ) { + BUILD_LMLAYER=true + BUILD_CORE=true + FETCH_DEPS=true +} + +set_default_vars + +# Parse args +while [[ $# -gt 0 ]] ; do + key="$1" + case $key in + -test) + set_default_vars + BUILD_LMLAYER=false + FETCH_DEPS=false + ;; + -skip-package-install|-S) + set_default_vars + FETCH_DEPS=false + ;; + esac + shift # past argument +done + +if [ $FETCH_DEPS = true ]; then + verify_npm_setup +fi + +if [ $BUILD_LMLAYER = true ]; then + FLAGS="-skip-package-install" + + # Ensure that the LMLayer compiles properly, readying the build product for comsumption by KMW. + cd ../../../../predictive-text/ + echo "" + echo "Compiling the Language Modeling layer module..." + ./build.sh $FLAGS || fail "Failed to compile the language modeling layer module." + cd ../core/web/input-processor/src + # TODO: Move this back to KMW's main build script. Consider it part of the dependency update. + echo "Language Modeling layer compilation successful." + echo "" +fi + +if [ $BUILD_CORE = true ]; then + FLAGS="-skip-package-install" + + # Ensure that the KeyboardProcessor module compiles properly. + cd ../../keyboard-processor/src + echo "" + echo "Compiling Keyboard Processor module..." + ./build.sh $FLAGS || fail "Dependency build failed; aborting" + cd ../../input-processor/src + echo "Keyboard Processor module compilation successful." + echo "" +fi + +# Compile web's `keyboard-processor` module. +echo "Compiling Input Processor module..." +npm run tsc -- -p src/tsconfig.json || fail "Failed to compile the core/web/input-processor module." +echo "Input Processor module compilation successful." +echo "" \ No newline at end of file diff --git a/web/source/includes/events.ts b/common/core/web/input-processor/src/includes/events.ts similarity index 100% rename from web/source/includes/events.ts rename to common/core/web/input-processor/src/includes/events.ts diff --git a/web/source/text/inputProcessor.ts b/common/core/web/input-processor/src/text/inputProcessor.ts similarity index 96% rename from web/source/text/inputProcessor.ts rename to common/core/web/input-processor/src/text/inputProcessor.ts index 727f4c7bf1a0256d06b5c3e7aa4838f5e806e916..dd48308060ed5c44d542341784f50a2a3d8b64f3 100644 --- a/web/source/text/inputProcessor.ts +++ b/common/core/web/input-processor/src/text/inputProcessor.ts @@ -1,7 +1,6 @@ // Defines a 'polyfill' of sorts for NPM's events module /// -/// -/// +/// /// namespace com.keyman.text { @@ -67,7 +66,7 @@ namespace com.keyman.text { // The default OSK layout for desktop devices does not include nextlayer info, relying on modifier detection here. // It's the OSK equivalent to doModifierPress on 'desktop' form factors. - if((formFactor == FormFactor.Desktop || !this.activeKeyboard || this.activeKeyboard.usesDesktopLayoutOnDevice(keyEvent.device)) && fromOSK) { + if((formFactor == utils.FormFactor.Desktop || !this.activeKeyboard || this.activeKeyboard.usesDesktopLayoutOnDevice(keyEvent.device)) && fromOSK) { // If it's a desktop OSK style and this triggers a layer change, // a modifier key was clicked. No output expected, so it's safe to instantly exit. if(this.keyboardProcessor.selectLayer(keyEvent)) { diff --git a/web/source/text/prediction/languageProcessor.ts b/common/core/web/input-processor/src/text/prediction/languageProcessor.ts similarity index 95% rename from web/source/text/prediction/languageProcessor.ts rename to common/core/web/input-processor/src/text/prediction/languageProcessor.ts index 1f2b07ac3e0df9305e13445ceb2cadcbb4c67165..44a75dea98170b5fce80cb141902f4beb1f5b8e5 100644 --- a/web/source/text/prediction/languageProcessor.ts +++ b/common/core/web/input-processor/src/text/prediction/languageProcessor.ts @@ -1,3 +1,8 @@ +/// +/// +/// +/// + namespace com.keyman.text.prediction { export interface ModelSpec { /** @@ -87,7 +92,7 @@ namespace com.keyman.text.prediction { private _mayPredict: boolean = true; private _mayCorrect: boolean = true; - private static readonly TRANSCRIPTION_BUFFER: 10; + private static readonly TRANSCRIPTION_BUFFER: 10 = 10; public init(supportsRightDeletions: boolean = false) { // Establishes KMW's platform 'capabilities', which limit the range of context a LMLayer diff --git a/common/core/web/input-processor/src/tsconfig.json b/common/core/web/input-processor/src/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..b7728c814709b267a0f63dfd48f5d7038047c479 --- /dev/null +++ b/common/core/web/input-processor/src/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "allowJs": true, + "module": "none", + "outDir": "../dist/", + "inlineSources": true, + "sourceMap": true, + "sourceRoot": "/keyman/", + "target": "es5", + "types": ["node"], + "lib": ["es6"], + "outFile": "../dist/index.js" + }, + "files": [ + "../node_modules/@keymanapp/web-environment/environment.inc.ts", + "../node_modules/@keymanapp/web-utils/src/index.ts", + "../node_modules/@keymanapp/lexical-model-layer/node-defaultWorker.ts", + "text/inputProcessor.ts" + ] +} diff --git a/common/core/web/keyboard-processor/.gitignore b/common/core/web/keyboard-processor/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c613a78f7dc4ebef65a0845ab2bd378d31784f56 --- /dev/null +++ b/common/core/web/keyboard-processor/.gitignore @@ -0,0 +1,18 @@ +# Build products +src/environment.inc.ts + +# Legacy build folders. +output/ +build/ +embedded/ + +# Current build output folder (matches standard node publish location). +dist/ + +# Other local files. +node_modules/ +unit_tests/modernizr.js +source/environment.inc.ts +.idea/**/*.xml +*.iml +*.kpj.user \ No newline at end of file diff --git a/common/core/web/keyboard-processor/README.md b/common/core/web/keyboard-processor/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3a2e7ae83fcce11e3e8358f2b0b32cab77fbee71 --- /dev/null +++ b/common/core/web/keyboard-processor/README.md @@ -0,0 +1,21 @@ +# Keyman: Keyboard Processor Module +The Original Code is (C) 2017-2020 SIL International + +The Keyboard Processor module is an internal component of KeymanWeb, seen within this repo at /web/. + +## Minimum Compilation Requirements + +* A local installation of [Node.js](https://nodejs.org/) v8.9+. + * Builds will call `npm install` to automatically install further necessary build dependencies. + + * Linux users can run the following to update to LTS version of nodejs + +``` +sudo apt-get install python-software-properties +curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - +sudo apt-get install nodejs +``` + +********************************************************************** + +The build script may be found at src/build.sh. diff --git a/common/core/web/keyboard-processor/package-lock.json b/common/core/web/keyboard-processor/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..8ada6d5505bda7d7a7cfbde50e5dc7426eabf3d2 --- /dev/null +++ b/common/core/web/keyboard-processor/package-lock.json @@ -0,0 +1,313 @@ +{ + "name": "@keymanapp/keyboard-processor", + "version": "14.0.144", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/node": { + "version": "11.15.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-11.15.10.tgz", + "integrity": "sha512-FHli7aK/ViA02vbWKmiNejJW4BCJxCVb6macS5gi71fST+UrrdqcES6Lh5rx23hU1QCBeUNXfPquYr9jJv7FuA==" + }, + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==" + }, + "assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "browser-stdout": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", + "dev": true + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" + }, + "chai": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.2.0.tgz", + "integrity": "sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw==", + "dev": true, + "requires": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^3.0.1", + "get-func-name": "^2.0.0", + "pathval": "^1.1.0", + "type-detect": "^4.0.5" + } + }, + "check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", + "dev": true + }, + "commander": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz", + "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-eql": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", + "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "dev": true, + "requires": { + "type-detect": "^4.0.0" + } + }, + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==" + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "get-func-name": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", + "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "growl": { + "version": "1.10.5", + "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", + "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "he": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "mocha": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-5.2.0.tgz", + "integrity": "sha512-2IUgKDhc3J7Uug+FxMXuqIyYzH7gJjXECKe/w43IGgQHTSj3InJi+yAA7T24L9bQMRKiUEHxEX37G5JpVUGLcQ==", + "dev": true, + "requires": { + "browser-stdout": "1.3.1", + "commander": "2.15.1", + "debug": "3.1.0", + "diff": "3.5.0", + "escape-string-regexp": "1.0.5", + "glob": "7.1.2", + "growl": "1.10.5", + "he": "1.1.1", + "minimatch": "3.0.4", + "mkdirp": "0.5.1", + "supports-color": "5.4.0" + }, + "dependencies": { + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + } + } + }, + "mocha-teamcity-reporter": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mocha-teamcity-reporter/-/mocha-teamcity-reporter-3.0.0.tgz", + "integrity": "sha512-FyGgmtFfW2nDwEZU3mrjQShAAK/zhGivwY4HCsqoDoyeS8vV8HGdq1Dn2P+SFaIoCeXTQ0Z+5xVRyikYaKrW5w==", + "dev": true + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "pathval": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz", + "integrity": "sha1-uULm1L3mUwBe9rcTYd74cn0GReA=", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" + }, + "source-map-support": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.16.tgz", + "integrity": "sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ==", + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "ts-node": { + "version": "8.8.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-8.8.2.tgz", + "integrity": "sha512-duVj6BpSpUpD/oM4MfhO98ozgkp3Gt9qIp3jGxwU2DFvl/3IRaEAvbLa8G60uS7C77457e/m5TMowjedeRxI1Q==", + "requires": { + "arg": "^4.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "source-map-support": "^0.5.6", + "yn": "3.1.1" + } + }, + "type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==" + } + } +} diff --git a/common/core/web/keyboard-processor/package.json b/common/core/web/keyboard-processor/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4b6ca300b04aa0094b2a4c3919853ab273b4d454 --- /dev/null +++ b/common/core/web/keyboard-processor/package.json @@ -0,0 +1,40 @@ +{ + "name": "@keymanapp/keyboard-processor", + "version": "14.0.144", + "description": "Core module for Keyman keyboard support in KeymanWeb.", + "repository": { + "type": "git", + "url": "git+https://github.com/keymanapp/keyman.git" + }, + "keywords": [ + "input", + "languages", + "keyboards" + ], + "author": "SIL International", + "license": "MIT", + "bugs": { + "url": "https://github.com/keymanapp/keyman/issues" + }, + "homepage": "https://github.com/keymanapp/keyman#readme", + "devDependencies": { + "@keymanapp/resources-gosh": "^14.0.144", + "chai": "^4.2.0", + "mocha": "^5.2.0", + "mocha-teamcity-reporter": "^3.0.0", + "typescript": "^3.8.3" + }, + "scripts": { + "lerna": "cd ../ && npm run lerna --", + "tsc": "tsc", + "test": "gosh ./test.sh", + "mocha": "mocha" + }, + "dependencies": { + "@keymanapp/models-types": "^14.0.144", + "@keymanapp/web-environment": "^14.0.144", + "@keymanapp/web-utils": "^14.0.144", + "@types/node": "^11.9.4", + "ts-node": "^8.0.2" + } +} diff --git a/common/core/web/keyboard-processor/src/build.sh b/common/core/web/keyboard-processor/src/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..4bcd7f468817c68d4f0ae928152691b0c25a05c9 --- /dev/null +++ b/common/core/web/keyboard-processor/src/build.sh @@ -0,0 +1,50 @@ +#! /bin/bash +# +# Compile KeymanWeb's 'keyboard-processor' module, one of the components of Web's 'core' module. +# + +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../../../../resources/build/build-utils.sh" +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +# This script runs from its own folder +cd "$(dirname "$THIS_SCRIPT")" + +display_usage ( ) { + echo "build.sh [-skip-package-install | -S] [-test]" + echo + echo " -skip-package-install (or -S) skips the `lerna bootstrap` dependency check." + echo " Intended for use when this script is called by another build script." + echo "" + echo " If more than one target is specified, the last one will take precedence." + exit 1 +} + +# Establish default build parameters +set_default_vars ( ) { + FETCH_DEPS=true +} + +set_default_vars + +# Parse args +while [[ $# -gt 0 ]] ; do + key="$1" + case $key in + -skip-package-install|-S) + set_default_vars + FETCH_DEPS=false + ;; + esac + shift # past argument +done + +if [ $FETCH_DEPS = true ]; then + verify_npm_setup +fi + +# Compile web's `keyboard-processor` module. +npm run tsc -- -p src/tsconfig.json || fail "Failed to compile the core/web/keyboard-processor module." diff --git a/web/source/keyboards/activeLayout.ts b/common/core/web/keyboard-processor/src/keyboards/activeLayout.ts similarity index 99% rename from web/source/keyboards/activeLayout.ts rename to common/core/web/keyboard-processor/src/keyboards/activeLayout.ts index 64ff4381ad19eb0b9c5546923a26838b53527a4d..3ef946f5cc66cad70774a51f21c9cdc69c77c01e 100644 --- a/web/source/keyboards/activeLayout.ts +++ b/common/core/web/keyboard-processor/src/keyboards/activeLayout.ts @@ -107,7 +107,7 @@ namespace com.keyman.keyboards { this.baseKeyEvent = Lkc; } - constructKeyEvent(keyboardProcessor: text.KeyboardProcessor, target: text.OutputTarget, device: text.EngineDeviceSpec): text.KeyEvent { + constructKeyEvent(keyboardProcessor: text.KeyboardProcessor, target: text.OutputTarget, device: utils.DeviceSpec): text.KeyEvent { // Make a deep copy of our preconstructed key event, filling it out from there. let Lkc = utils.deepCopy(this.baseKeyEvent); Lkc.Ltarg = target; @@ -466,7 +466,7 @@ namespace com.keyman.keyboards { keyLabels: boolean; isDefault?: boolean; keyboard: Keyboard; - formFactor: text.FormFactor; + formFactor: utils.FormFactor; /** * Facilitates mapping layer id strings to their specification objects. @@ -486,7 +486,7 @@ namespace com.keyman.keyboards { * @param layout * @param formFactor */ - static polyfill(layout: LayoutFormFactor, keyboard: Keyboard, formFactor: text.FormFactor): ActiveLayout { + static polyfill(layout: LayoutFormFactor, keyboard: Keyboard, formFactor: utils.FormFactor): ActiveLayout { if(layout == null) { throw new Error("Cannot build an ActiveLayout for a null specification."); } diff --git a/web/source/keyboards/defaultLayouts.ts b/common/core/web/keyboard-processor/src/keyboards/defaultLayouts.ts similarity index 99% rename from web/source/keyboards/defaultLayouts.ts rename to common/core/web/keyboard-processor/src/keyboards/defaultLayouts.ts index 67116ea1ae8add815e7f7cbf62cb5c2ad6ff4d48..859e870bb22cdee0a151fa3ea6ebb29b79367d0a 100644 --- a/web/source/keyboards/defaultLayouts.ts +++ b/common/core/web/keyboard-processor/src/keyboards/defaultLayouts.ts @@ -3,8 +3,7 @@ Copyright 2017 SIL International ***/ -/// -/// +// Relies on web-utils for version and deep-copy functionality. namespace com.keyman.keyboards { let Codes = com.keyman.text.Codes; @@ -420,8 +419,12 @@ namespace com.keyman.keyboards { if(layerId.indexOf('shift') != -1) { key['sp'] = buttonClasses['SHIFT-ON']; } - if((formFactor != 'desktop') && (layerId != 'default')) { - key['nextlayer']='default'; + if(formFactor != 'desktop') { + if(layerId != 'default') { + key['nextlayer']='default'; + } else { + key['nextlayer']='shift'; + } } break; case 'K_LCTRL': diff --git a/web/source/keyboards/keyboard.ts b/common/core/web/keyboard-processor/src/keyboards/keyboard.ts similarity index 93% rename from web/source/keyboards/keyboard.ts rename to common/core/web/keyboard-processor/src/keyboards/keyboard.ts index 231cdafc99d75fb4faeac7077f7e1d4fe1afac2a..9afaf366a163c86f4692798cf638d68737c1b112 100644 --- a/web/source/keyboards/keyboard.ts +++ b/common/core/web/keyboard-processor/src/keyboards/keyboard.ts @@ -251,10 +251,10 @@ namespace com.keyman.keyboards { return true; } - usesDesktopLayoutOnDevice(device: text.EngineDeviceSpec) { + usesDesktopLayoutOnDevice(device: utils.DeviceSpec) { if(this.scriptObject['KVKL']) { // A custom mobile layout is defined... but are we using it? - return device.formFactor == text.FormFactor.Desktop; + return device.formFactor == utils.FormFactor.Desktop; } else { return true; } @@ -273,16 +273,16 @@ namespace com.keyman.keyboards { } } - private findOrConstructLayout(formFactor: text.FormFactor): LayoutFormFactor { + private findOrConstructLayout(formFactor: utils.FormFactor): LayoutFormFactor { if(this._layouts) { // Search for viable layouts. `null` is allowed for desktop form factors when help text is available, // so we check explicitly against `undefined`. if(this._layouts[formFactor] !== undefined) { return this._layouts[formFactor]; - } else if(formFactor == text.FormFactor.Phone && this._layouts[text.FormFactor.Tablet]) { - return this._layouts[text.FormFactor.Phone] = this._layouts[text.FormFactor.Tablet]; - } else if(formFactor == text.FormFactor.Tablet && this._layouts[text.FormFactor.Phone]) { - return this._layouts[text.FormFactor.Tablet] = this._layouts[text.FormFactor.Phone]; + } else if(formFactor == utils.FormFactor.Phone && this._layouts[utils.FormFactor.Tablet]) { + return this._layouts[utils.FormFactor.Phone] = this._layouts[utils.FormFactor.Tablet]; + } else if(formFactor == utils.FormFactor.Tablet && this._layouts[utils.FormFactor.Phone]) { + return this._layouts[utils.FormFactor.Tablet] = this._layouts[utils.FormFactor.Phone]; } } @@ -304,7 +304,7 @@ namespace com.keyman.keyboards { // If we don't have key definitions to use for a layout but also lack help text or are a touch-based layout, // we make a default layout anyway. We have to show display something usable. - if(!rawSpecifications && (this.helpText == '' || formFactor != text.FormFactor.Desktop)) { + if(!rawSpecifications && (this.helpText == '' || formFactor != utils.FormFactor.Desktop)) { rawSpecifications = {'F':'Tahoma', 'BK': Layouts.dfltText}; } @@ -333,7 +333,7 @@ namespace com.keyman.keyboards { * In such cases, please use either `helpText` or `insertHelpHTML` instead. * @param formFactor {string} The desired form factor for the layout. */ - public layout(formFactor: text.FormFactor): ActiveLayout { + public layout(formFactor: utils.FormFactor): ActiveLayout { let rawLayout = this.findOrConstructLayout(formFactor); if(rawLayout) { @@ -349,13 +349,13 @@ namespace com.keyman.keyboards { } } - public markLayoutCalibrated(formFactor: text.FormFactor) { + public markLayoutCalibrated(formFactor: utils.FormFactor) { if(this.layoutStates[formFactor] != LayoutState.NOT_LOADED) { this.layoutStates[formFactor] = LayoutState.CALIBRATED; } } - public getLayoutState(formFactor: text.FormFactor) { + public getLayoutState(formFactor: utils.FormFactor) { return this.layoutStates[formFactor]; } } diff --git a/web/source/text/codes.ts b/common/core/web/keyboard-processor/src/text/codes.ts similarity index 100% rename from web/source/text/codes.ts rename to common/core/web/keyboard-processor/src/text/codes.ts diff --git a/web/source/text/deadkeys.ts b/common/core/web/keyboard-processor/src/text/deadkeys.ts similarity index 100% rename from web/source/text/deadkeys.ts rename to common/core/web/keyboard-processor/src/text/deadkeys.ts diff --git a/web/source/text/defaultOutput.ts b/common/core/web/keyboard-processor/src/text/defaultOutput.ts similarity index 100% rename from web/source/text/defaultOutput.ts rename to common/core/web/keyboard-processor/src/text/defaultOutput.ts diff --git a/web/source/text/kbdInterface.ts b/common/core/web/keyboard-processor/src/text/kbdInterface.ts similarity index 94% rename from web/source/text/kbdInterface.ts rename to common/core/web/keyboard-processor/src/text/kbdInterface.ts index 560477f7d2e6a5dd6b6f9d1324b011802ed5d090..20bce0e22ed657df88e34da71fa361c734e7237d 100644 --- a/web/source/text/kbdInterface.ts +++ b/common/core/web/keyboard-processor/src/text/kbdInterface.ts @@ -184,8 +184,8 @@ namespace com.keyman.text { _AnyIndices: number[] = []; // AnyIndex - array of any/index match indices // Must be accessible to some of the keyboard API methods. - activeKeyboard: any; - activeDevice: EngineDeviceSpec; + activeKeyboard: keyboards.Keyboard; + activeDevice: utils.DeviceSpec; variableStoreSerializer?: VariableStoreSerializer; @@ -958,5 +958,52 @@ namespace com.keyman.text { return behavior; } + + /** + * Publishes the KeyboardInterface's shorthand API names. As this assigns the current functions + * held by the longform versions, note that this should be called after replacing any of them via + * JS method extension. + * + * DOM-aware KeymanWeb should call this after its domKbdInterface.ts code is loaded, as it replaces + * a few. (This is currently done within its kmwapi.ts.) + */ + static __publishShorthandAPI() { + // Keyboard callbacks + let prototype = this.prototype; + + var exportKBCallback = function(miniName: string, longName: string) { + prototype[miniName] = prototype[longName]; + } + + exportKBCallback('KSF', 'saveFocus'); + exportKBCallback('KBR', 'beepReset'); + exportKBCallback('KT', 'insertText'); + exportKBCallback('KR', 'registerKeyboard'); + exportKBCallback('KRS', 'registerStub'); + exportKBCallback('KC', 'context'); + exportKBCallback('KN', 'nul'); + exportKBCallback('KCM', 'contextMatch'); + exportKBCallback('KFCM', 'fullContextMatch'); + exportKBCallback('KIK', 'isKeypress'); + exportKBCallback('KKM', 'keyMatch'); + exportKBCallback('KSM', 'stateMatch'); + exportKBCallback('KKI', 'keyInformation'); + exportKBCallback('KDM', 'deadkeyMatch'); + exportKBCallback('KB', 'beep'); + exportKBCallback('KA', 'any'); + exportKBCallback('KDC', 'deleteContext'); + exportKBCallback('KO', 'output'); + exportKBCallback('KDO', 'deadkeyOutput'); + exportKBCallback('KIO', 'indexOutput'); + exportKBCallback('KIFS', 'ifStore'); + exportKBCallback('KSETS', 'setStore'); + exportKBCallback('KLOAD', 'loadStore'); + exportKBCallback('KSAVE', 'saveStore'); + } } + + (function() { + // This will be the only call within the keyboard-processor module. + KeyboardInterface.__publishShorthandAPI(); + }()); } \ No newline at end of file diff --git a/web/source/text/keyEvent.ts b/common/core/web/keyboard-processor/src/text/keyEvent.ts similarity index 94% rename from web/source/text/keyEvent.ts rename to common/core/web/keyboard-processor/src/text/keyEvent.ts index 32acad605709f9429d835e46407d95bc9c3d3738..525d24fdb68e9f5e4cd97e4f44a17d974a65be09 100644 --- a/web/source/text/keyEvent.ts +++ b/common/core/web/keyboard-processor/src/text/keyEvent.ts @@ -1,4 +1,3 @@ -/// /// namespace com.keyman.text { @@ -31,7 +30,7 @@ namespace com.keyman.text { /** * The device model for web-core to follow when processing the keystroke. */ - device: EngineDeviceSpec; + device: utils.DeviceSpec; /** * `true` if this event was produced by sources other than a DOM-based KeyboardEvent. diff --git a/web/source/text/keyMapping.ts b/common/core/web/keyboard-processor/src/text/keyMapping.ts similarity index 100% rename from web/source/text/keyMapping.ts rename to common/core/web/keyboard-processor/src/text/keyMapping.ts diff --git a/web/source/text/keyboardProcessor.ts b/common/core/web/keyboard-processor/src/text/keyboardProcessor.ts similarity index 97% rename from web/source/text/keyboardProcessor.ts rename to common/core/web/keyboard-processor/src/text/keyboardProcessor.ts index a59512a4276df830e30460b4cee175643ea00550..9b65f38bde4bebb40be8b140cd1432925abb3847 100644 --- a/web/source/text/keyboardProcessor.ts +++ b/common/core/web/keyboard-processor/src/text/keyboardProcessor.ts @@ -10,10 +10,8 @@ /// // Defines built-in keymapping. /// -// Defines a core-compatible 'Device' analogue for use in keyEvent processing -/// -// Defines the getGlobalObject() utility method. -/// + +// Also relies on @keymanapp/web-utils, which is included via tsconfig.json. namespace com.keyman.text { export type BeepHandler = (outputTarget: OutputTarget) => void; @@ -61,7 +59,7 @@ namespace com.keyman.text { options = KeyboardProcessor.DEFAULT_OPTIONS; } - this.baseLayout = options.baseLayout || 'us'; // default BaseLayout + this.baseLayout = options.baseLayout || KeyboardProcessor.DEFAULT_OPTIONS.baseLayout; this.keyboardInterface = new KeyboardInterface(options.variableStoreSerializer); this.installInterface(); } @@ -534,14 +532,14 @@ namespace com.keyman.text { var s = activeLayer; // Do not change layer unless needed (27/08/2015) - if(id == activeLayer && keyEvent.device.formFactor != FormFactor.Desktop) { + if(id == activeLayer && keyEvent.device.formFactor != utils.FormFactor.Desktop) { return false; } var idx=id; var i; - if(keyEvent.device.formFactor == FormFactor.Desktop) { + if(keyEvent.device.formFactor == utils.FormFactor.Desktop) { // Need to test if target layer is a standard layer (based on the plain 'default') var replacements= ['leftctrl', 'rightctrl', 'ctrl', 'leftalt', 'rightalt', 'alt', 'shift']; @@ -670,11 +668,22 @@ namespace com.keyman.text { this._UpdateVKShift(null, 15, 0); }; - setNumericLayer(device: EngineDeviceSpec) { + setNumericLayer(device: utils.DeviceSpec) { let layout = this.activeKeyboard.layout(device.formFactor); if(layout.getLayer('numeric')) { this.layerId = 'numeric'; } }; } -} \ No newline at end of file +} + +(function () { + let ns = com.keyman.text; + + // Let LMLayer be available both in the browser and in Node. + if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { + module.exports = ns.KeyboardProcessor; + //@ts-ignore + ns.KeyboardProcessor.com = com; // Export the root namespace so that all KeyboardProcessor classes are accessible by unit tests. + } +}()); \ No newline at end of file diff --git a/web/source/text/outputTarget.ts b/common/core/web/keyboard-processor/src/text/outputTarget.ts similarity index 98% rename from web/source/text/outputTarget.ts rename to common/core/web/keyboard-processor/src/text/outputTarget.ts index c4d73513f5e152094e3e85438af2b6ec27f75cec..87c0382ab62608baa0653b40ca2d5a05a27807bf 100644 --- a/web/source/text/outputTarget.ts +++ b/common/core/web/keyboard-processor/src/text/outputTarget.ts @@ -1,12 +1,10 @@ -// Defines KMW's string extension functions. -/// // Defines deadkey management in a manner attachable to each element interface. /// -// Defines relevant LMLayer-related interfaces. -/// // Defines the KeyEvent type. /// +// Also relies on string-extensions provided by the web-utils package. + namespace com.keyman.text { export class TextTransform implements Transform { readonly insert: string; diff --git a/web/source/text/ruleBehavior.ts b/common/core/web/keyboard-processor/src/text/ruleBehavior.ts similarity index 100% rename from web/source/text/ruleBehavior.ts rename to common/core/web/keyboard-processor/src/text/ruleBehavior.ts diff --git a/web/source/text/systemStores.ts b/common/core/web/keyboard-processor/src/text/systemStores.ts similarity index 98% rename from web/source/text/systemStores.ts rename to common/core/web/keyboard-processor/src/text/systemStores.ts index 176c2e114f7e88498907a02b72003593ca1dace9..2e8dbc39d470d90ec37c389be2651e9418536603 100644 --- a/web/source/text/systemStores.ts +++ b/common/core/web/keyboard-processor/src/text/systemStores.ts @@ -1,5 +1,3 @@ -/// - namespace com.keyman.text { /** * Defines common behaviors associated with system stores. diff --git a/web/source/keyboard-processor.tsconfig.json b/common/core/web/keyboard-processor/src/tsconfig.json similarity index 50% rename from web/source/keyboard-processor.tsconfig.json rename to common/core/web/keyboard-processor/src/tsconfig.json index 4ee525337867c795ef545141bd3811d99159fcf8..a6d7dabf646361352fb41f004520eb722e854725 100644 --- a/web/source/keyboard-processor.tsconfig.json +++ b/common/core/web/keyboard-processor/src/tsconfig.json @@ -2,16 +2,19 @@ "compilerOptions": { "allowJs": true, "module": "none", - "outDir": "../intermediate/", + "outDir": "../dist/", "inlineSources": true, "sourceMap": true, "sourceRoot": "/keyman/", "target": "es5", "types": ["node"], "lib": ["es6"], - "outFile": "../intermediate/keyboard-processor/index.js" + "outFile": "../dist/index.js" }, "files": [ + "../node_modules/@keymanapp/models-types/index.d.ts", + "../node_modules/@keymanapp/web-environment/environment.inc.ts", + "../node_modules/@keymanapp/web-utils/src/index.ts", "text/keyboardProcessor.ts" ] } diff --git a/common/core/web/keyboard-processor/test.sh b/common/core/web/keyboard-processor/test.sh new file mode 100755 index 0000000000000000000000000000000000000000..13b651fd0313b19a115279e16ac0d96831a3e453 --- /dev/null +++ b/common/core/web/keyboard-processor/test.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +# We should work within the script's directory, not the one we were called in. +cd $(dirname "$BASH_SOURCE") + +# Include useful testing resource functions +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../../../resources/build/build-utils.sh" +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +# A simple utility script to facilitate unit-testing for the LM Layer. +# It's rigged to be callable by NPM to facilitate testing during development when in other folders. + +display_usage ( ) { + echo "test.sh [-skip-package-install] [-CI] [ -? | -h | -help]" + echo " -CI to perform continuous-integration friendly tests and reporting formatted for TeamCity" + echo " -? | -h | -help to display this help information" + echo " -skip-package-install to bypass refreshing dependencies. Useful when called by scripts that pre-fetch" + echo "" + exit 0 +} + +# Defaults +FLAGS= +CI_REPORTING=0 +FETCH_DEPS=true + +# Parse args +while [[ $# -gt 0 ]] ; do + key="$1" + case $key in + -h|-help|-?) + display_usage + exit + ;; + -CI) + CI_REPORTING=1 + ;; + -skip-package-install) + FETCH_DEPS=false + esac + shift # past argument +done + +if [ $FETCH_DEPS = true ]; then + verify_npm_setup +fi + +test-headless ( ) { + if (( CI_REPORTING )); then + FLAGS="$FLAGS --reporter mocha-teamcity-reporter" + fi + + npm run mocha -- --recursive $FLAGS ./tests/cases/ +} + +# Build test dependency +pushd "$KEYMAN_ROOT/common/core/web/tools/recorder/src" +./build.sh -skip-package-install || fail "recorder-core compilation failed." +popd + +# Run headless (browserless) tests. +test-headless || fail "Keyboard Processor tests failed!" + diff --git a/common/core/web/keyboard-processor/tests/cases/basic-engine.js b/common/core/web/keyboard-processor/tests/cases/basic-engine.js new file mode 100644 index 0000000000000000000000000000000000000000..b04b1619bbe633f922ad13f7c0732fb917aff381 --- /dev/null +++ b/common/core/web/keyboard-processor/tests/cases/basic-engine.js @@ -0,0 +1,55 @@ +var assert = require('chai').assert; +let fs = require('fs'); +let vm = require('vm'); + +let KeyboardProcessor = require('../../dist'); +let KMWRecorder = require('../../../tools/recorder/dist/nodeProctor'); + +// Required initialization setup. +global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing. + +describe('Engine - Basic Simulation', function() { + let testJSONtext = fs.readFileSync('../tests/resources/json/engine_tests/basic_lao_simulation.json'); + // Common test suite setup. + let testSuite = new KMWRecorder.KeyboardTest(JSON.parse(testJSONtext)); + + var keyboard; + let device = { + formFactor: 'desktop', + OS: 'windows', + browser: 'native' + } + + before(function() { + // -- START: Standard Recorder-based unit test loading boilerplate -- + // Load the keyboard. We'll need a KeyboardProcessor instance as an intermediary. + let kp = new KeyboardProcessor(); + + // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will + // automatically set the keyboard as active. + var script = new vm.Script(fs.readFileSync('../tests/' + testSuite.keyboard.filename)); + script.runInThisContext(); + + keyboard = kp.activeKeyboard; + assert.equal(keyboard.id, "Keyboard_" + testSuite.keyboard.id); + // -- END: Standard Recorder-based unit test loading boilerplate -- + + // This part provides extra assurance that the keyboard properly loaded. + assert.equal(keyboard.id, "Keyboard_lao_2008_basic"); + }); + + // Converts each test set into its own Mocha-level test. + for(let set of testSuite.inputTestSets) { + let proctor = new KMWRecorder.NodeProctor(keyboard, device, assert.equal); + + if(!proctor.compatibleWithSuite(testSuite)) { + it.skip(set.toTestName() + " - Cannot run this test suite on Node."); + } else { + it(set.toTestName(), function() { + // Refresh the proctor instance at runtime. + let proctor = new KMWRecorder.NodeProctor(keyboard, device, assert.equal); + set.test(proctor); + }); + } + } +}); \ No newline at end of file diff --git a/common/core/web/keyboard-processor/tests/cases/basic-init.js b/common/core/web/keyboard-processor/tests/cases/basic-init.js new file mode 100644 index 0000000000000000000000000000000000000000..c1ed7f6f07ea3a007d2bd6eb9f903130b175d14b --- /dev/null +++ b/common/core/web/keyboard-processor/tests/cases/basic-init.js @@ -0,0 +1,45 @@ +var assert = require('chai').assert; +var fs = require("fs"); +var vm = require("vm"); + +let KeyboardProcessor = require('../../dist'); + +// Required initialization setup. +global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing. +global.keyman = {}; // So that keyboard-based checks against the global `keyman` succeed. + // 10.0+ dependent keyboards, like khmer_angkor, will otherwise fail to load. + +// Initialize supplementary plane string extensions +String.kmwEnableSupplementaryPlane(false); + +// Test the KeyboardProcessor interface. +describe('KeyboardProcessor', function() { + describe('[[constructor]]', function () { + it('should initialize without errors', function () { + let kp = new KeyboardProcessor(); + assert.isNotNull(kp); + }); + + it('has expected default values after initialization', function () { + let kp = new KeyboardProcessor(); + assert.equal('us', kp.baseLayout, 'KeyboardProcessor has unexpected base layout') + assert.isNotNull(global.KeymanWeb, 'KeymanWeb global was not automatically installed'); + assert.equal('default', kp.layerId, 'Default layer is not set to "default"'); + assert.isUndefined(kp.activeKeyboard, 'Initialized with already-active keyboard'); + }); + }); + + describe('activeKeyboard', function() { + it('is automatically set (in headless) on keyboard load', function () { + let kp = new KeyboardProcessor(); + + // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will + // automatically set the keyboard as active. + var script = new vm.Script(fs.readFileSync('../tests/resources/keyboards/khmer_angkor.js')); + script.runInThisContext(); + + assert.isDefined(kp.activeKeyboard, 'Keyboard failed to register on script load'); + assert.equal('Keyboard_khmer_angkor', kp.activeKeyboard.id, 'Unexpected keyboard id found after script load'); + }); + }); +}); diff --git a/common/core/web/keyboard-processor/tests/cases/chirality.js b/common/core/web/keyboard-processor/tests/cases/chirality.js new file mode 100644 index 0000000000000000000000000000000000000000..251ef39d03538590c58277158f1bdb818452b159 --- /dev/null +++ b/common/core/web/keyboard-processor/tests/cases/chirality.js @@ -0,0 +1,57 @@ +var assert = require('chai').assert; +let fs = require('fs'); +let vm = require('vm'); + +let KeyboardProcessor = require('../../dist'); +let KMWRecorder = require('../../../tools/recorder/dist/nodeProctor'); + +// Required initialization setup. +global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing. + +describe('Engine - Chirality', function() { + let testJSONtext = fs.readFileSync('../tests/resources/json/engine_tests/chirality.json'); + // Common test suite setup. + let testSuite = new KMWRecorder.KeyboardTest(JSON.parse(testJSONtext)); + + var keyboard; + let device = { + formFactor: 'desktop', + OS: 'windows', + browser: 'native' + } + + before(function() { + // -- START: Standard Recorder-based unit test loading boilerplate -- + // Load the keyboard. We'll need a KeyboardProcessor instance as an intermediary. + let kp = new KeyboardProcessor(); + + // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will + // automatically set the keyboard as active. + var script = new vm.Script(fs.readFileSync('../tests/' + testSuite.keyboard.filename)); + script.runInThisContext(); + + keyboard = kp.activeKeyboard; + assert.equal(keyboard.id, "Keyboard_" + testSuite.keyboard.id); + // -- END: Standard Recorder-based unit test loading boilerplate -- + + // This part provides extra assurance that the keyboard properly loaded. + assert.equal(keyboard.id, "Keyboard_test_chirality"); + }); + + // Converts each test set into its own Mocha-level test. + for(let set of testSuite.inputTestSets) { + let proctor = new KMWRecorder.NodeProctor(keyboard, device, assert.equal); + + if(!proctor.compatibleWithSuite(testSuite)) { + it.skip(set.toTestName() + " - Cannot run this test suite on Node."); + } else if(set.constraint.target == 'hardware') { + it(set.toTestName(), function() { + // Refresh the proctor instance at runtime. + let proctor = new KMWRecorder.NodeProctor(keyboard, device, assert.equal); + set.test(proctor); + }); + } else { + it.skip(set.toTestName() + " - modifier state simulation for OSK not yet supported in headless KeyboardProcessor"); + } + } +}); \ No newline at end of file diff --git a/common/core/web/keyboard-processor/tests/cases/deadkeys.js b/common/core/web/keyboard-processor/tests/cases/deadkeys.js new file mode 100644 index 0000000000000000000000000000000000000000..c77300983d801dd9e292e64196a4b9fee4764a52 --- /dev/null +++ b/common/core/web/keyboard-processor/tests/cases/deadkeys.js @@ -0,0 +1,55 @@ +var assert = require('chai').assert; +let fs = require('fs'); +let vm = require('vm'); + +let KeyboardProcessor = require('../../dist'); +let KMWRecorder = require('../../../tools/recorder/dist/nodeProctor'); + +// Required initialization setup. +global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing. + +describe('Engine - Deadkeys', function() { + let testJSONtext = fs.readFileSync('../tests/resources/json/engine_tests/deadkeys.json'); + // Common test suite setup. + let testSuite = new KMWRecorder.KeyboardTest(JSON.parse(testJSONtext)); + + var keyboard; + let device = { + formFactor: 'desktop', + OS: 'windows', + browser: 'native' + } + + before(function() { + // -- START: Standard Recorder-based unit test loading boilerplate -- + // Load the keyboard. We'll need a KeyboardProcessor instance as an intermediary. + let kp = new KeyboardProcessor(); + + // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will + // automatically set the keyboard as active. + var script = new vm.Script(fs.readFileSync('../tests/' + testSuite.keyboard.filename)); + script.runInThisContext(); + + keyboard = kp.activeKeyboard; + assert.equal(keyboard.id, "Keyboard_" + testSuite.keyboard.id); + // -- END: Standard Recorder-based unit test loading boilerplate -- + + // This part provides extra assurance that the keyboard properly loaded. + assert.equal(keyboard.id, "Keyboard_test_deadkeys"); + }); + + // Converts each test set into its own Mocha-level test. + for(let set of testSuite.inputTestSets) { + let proctor = new KMWRecorder.NodeProctor(keyboard, device, assert.equal); + + if(!proctor.compatibleWithSuite(testSuite)) { + it.skip(set.toTestName() + " - Cannot run this test suite on Node."); + } else { + it(set.toTestName(), function() { + // Refresh the proctor instance at runtime. + let proctor = new KMWRecorder.NodeProctor(keyboard, device, assert.equal); + set.test(proctor); + }); + } + } +}); \ No newline at end of file diff --git a/common/core/web/keyboard-processor/tests/cases/engine/context.js b/common/core/web/keyboard-processor/tests/cases/engine/context.js new file mode 100644 index 0000000000000000000000000000000000000000..1b884ad9422a028c3196a4a9b52fb6b1eb84dc0d --- /dev/null +++ b/common/core/web/keyboard-processor/tests/cases/engine/context.js @@ -0,0 +1,858 @@ +var assert = require('chai').assert; +let fs = require('fs'); +let vm = require('vm'); + +let KeyboardProcessor = require('../../../dist'); +let KMWRecorder = require('../../../../tools/recorder/dist/nodeProctor'); + +// Required initialization setup. +global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing. + +let device = { + formFactor: 'desktop', + OS: 'windows', + browser: 'native' +} + +var keyboard; + +var toSupplementaryPairString = function(code){ + var H = Math.floor((code - 0x10000) / 0x400) + 0xD800; + var L = (code - 0x10000) % 0x400 + 0xDC00; + + return String.fromCharCode(H, L); +} + +function runEngineRuleSet(ruleSet, defaultNoun) { + defaultNoun = defaultNoun ? defaultNoun : "Rule"; + + for(var i = 0; i < ruleSet.length; i++) { + var ruleDef = ruleSet[i]; // for example, DEADKEY_TEST_1. + + var matchDefs = [{ + sequence: ruleDef.baseSequence, + result: true, + msg: "Rule " + ruleDef.id + ": basic application of rule failed."} + ].concat(ruleDef.fullMatchDefs ? ruleDef.fullMatchDefs : []); + + for(var j = 0; j < matchDefs.length; j++) { + // Prepare the context! + var matchTest = matchDefs[j]; + var ruleSeq = new KMWRecorder.RecordedKeystrokeSequence(matchTest.sequence); + let proctor = new KMWRecorder.NodeProctor(keyboard, device, assert.equal); + + // We want to specify the OutputTarget for this test; our actual concern is the resulting context. + var target = new com.keyman.text.Mock(); + ruleSeq.test(proctor, target); + + // Now for the real test! + let processor = new KeyboardProcessor(); + processor.activeKeyboard = keyboard; + var res = processor.keyboardInterface.fullContextMatch(ruleDef.n, target, ruleDef.rule); + + var msg = matchTest.msg; + if(!msg) { + msg = defaultNoun + " incorrectly reported as " + (matchTest.result ? "unmatched!" : "matched!"); + } + assert.equal(res, matchTest.result, msg); + } + } +} + +// Unfortunately, at present, this is all handwritten stuff crafted from partial Recorder use. Might should make +// a page that writes this format instead. Note that I've omitted the eventSpec part here, since these tests are +// Node-only. + +/* + * Start definition of isolated rule tests for validity of `fullContextMatch` (KFCM) components. + */ +var DEADKEY_TEST_1 = { + id: 1, + // Match condition for rule + rule: [{t:'d', d: 1}], + // Start of context relative to cursor + n: 1, + ln: 1, + // Resulting context map + contextCache: [1], + baseSequence: { "output": "", "inputs": [ + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} + ]}, + fullMatchDefs: [{ + sequence: { "output": "", "inputs": [ + // Does it fail with a different deadkey in the position? + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} + ]}, + result: false, + msg: "Rule 1: did not fail when incorrect deadkey was present." + }, { + sequence: { "output": "", "inputs": [ + // Slightly out-of-context deadkey shouldn't affect the match. + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} + ]}, + result: true, + msg: "Rule 1: failed when extra deadkey context exists in history." + }, { + sequence: { "output": "", "inputs": [ + // Slightly out-of-context deadkey shouldn't affect the match. + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} + ]}, + result: false, + msg: "Rule 1: did not fail upon incorrect deadkey ordering at top of context." + }] +}; + +var DEADKEY_TEST_2 = { + id: 2, + // Match condition for rule + rule: ['a', {t:'d', d: 0}, {t:'d', d: 1}, 'b'], + // Start of context relative to cursor + n: 5, + ln: 4, + // Resulting context map + contextCache: ['a', 0, 1, 'b'], + baseSequence: { "output": "abc", "inputs": [ + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + // The test has an extra character appended that's not part of the check. + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //c + ]}, + fullMatchDefs: [{ + sequence: { "output": "abc", "inputs": [ + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, + // Should fail with inverted deadkey ordering at same KC_ position. + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, + // The test has an extra character appended that's not part of the check. + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} + ]}, + result: false, + msg: "Rule 2: did not fail when deadkey ordering was inverted." + }, { + sequence: { "output": "cabc", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + // The test has an extra character appended that's not part of the check. + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //c + ]}, + result: true, + msg: "Rule 2: failed when extra character context exists in history." + }, { + sequence: { "output": "ab", "inputs": [ + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + // The test has an extra deadkey appended that's not part of the check. + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //1 + ]}, + result: true, + msg: "Rule 2: out-of-context deadkey caused rule match failure." + }, { + sequence: { "output": "abc", "inputs": [ + // Should not fail with a deadkey prepended to the context. + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + // The test has an extra character appended that's not part of the check. + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //c + ]}, + result: true, + msg: "Rule 2: prepended (out of context) deadkey caused rule match failure." + }] +}; + +var DEADKEY_TEST_3 = { + id: 3, + // Match condition for rule + rule: [{t:'d', d: 0}, 'a', {t:'d', d: 0}, {t:'d', d: 0}, 'b'], + // Start of context relative to cursor + n: 5, + ln: 5, + // Resulting context map + contextCache: [0, 'a', 0, 0, 'b'], + baseSequence: { "output": "ab", "inputs": [ + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + fullMatchDefs: [{ + sequence: { "output": "ab", "inputs": [ + // Omission of the first deadkey should result in failure. + //{"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: false, + msg: "Rule 3: required prepended deadkey omission did not prevent a rule match." + }, { + sequence: { "output": "ab", "inputs": [ + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + // Omission of the one of the duplicated deadkeys should result in failure. + //{"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: false, + msg: "Rule 3: omitting one copy of a required duplicated deadkey did not prevent a rule match." + }, { + sequence: { "output": "ab", "inputs": [ + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + // Triplifying deadkeys in the center should result in failure. + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: false, + msg: "Rule 3: triple matching deadkeys where only two required did not prevent a rule match." + }, { + sequence: { "output": "ab", "inputs": [ + // Should not fail with a duplicate deadkey prepended to the context. + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: true, + msg: "Rule 3: duplicate prepended deadkey prevented a rule match when only one was required." + }, { + sequence: { "output": "ab", "inputs": [ + // Should not fail with an unrelated deadkey prepended to the context before the required one. + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: true, + msg: "Rule 3: prepended deadkey placed before rule's deadkey prevented a rule match." + }, { + sequence: { "output": "ab", "inputs": [ + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + // Should fail when unrelated, prepended deadkey actually comes after the required one. + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: false, + msg: "Rule 3: prepended deadkey after rule's required deadkey failed to prevent a rule match." + }] +}; + +var DEADKEY_TEST_4 = { + id: 4, + // Match condition for rule + rule: ['a', {t:'d', d: 0}, {t:'d', d: 0}, 'b', {t:'d', d: 0}], + // Start of context relative to cursor + n: 6, + ln: 5, + // Resulting context map + contextCache: ['a', 0, 0, 'b', 0], + + baseSequence: { "output": "abc", "inputs": [ + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + // The test has an extra character appended that's not part of the check. + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //c + ]} + // No specialized fullMatchDefs here, as any appended deadkeys are automatically 'in context' for rules. +}; + +var DEADKEY_TEST_5 = { + id: 5, + // Match condition for rule + rule: ['a', 'b', 'b', 'a'], + // Start of context relative to cursor + n: 5, + ln: 4, + // Resulting context map + contextCache: ['a', 'b', 'b', 'a'], + + baseSequence: { "output": "abbac", "inputs": [ + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + // The test has an extra character appended that's not part of the check. + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //c + ]} +}; + +var DEADKEY_TEST_6 = { + id: 6, + // Match condition for rule + rule: [{t:'d', d: 1}, {t:'d', d: 2}, {t:'d', d: 0}, {t:'d', d: 1}, {t:'d', d: 2}], + // Start of context relative to cursor + n: 5, + ln: 5, + // Resulting context map + contextCache: [1, 2, 0, 1, 2], + + baseSequence: { "output": "", "inputs": [ + // Testing with an extra deadkey at the start. + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":51,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //3 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":51,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //3 + ]} +}; + +var ANY_CONTEXT_TEST_1 = { + id: 1, + // Match condition for rule + rule: ['c', "a", "b", {t:'c', c:3}, {t:'c', c:2}], + // Start of context relative to cursor + n: 5, + ln: 5, + // Resulting context map + contextCache: ['c', 'a', 'b', 'b', 'a'], + + baseSequence: { "output": "cabba", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + fullMatchDefs: [{ + sequence: { "output": "cacca", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: false, + msg: "Rule 1: Plain text mismatch with successful context() statements is matching the rule." + }, { + sequence: { "output": "cabaa", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: false, + msg: "Rule 1: mismatched context() rule component is not failing the rule." + }] +}; + +var ANY_CONTEXT_TEST_2 = { + id: 2, + // Match condition for rule + rule: ['c', 'a', {t:'a', a: "bc"}, {t:'c', c:3}, 'a'], + // Start of context relative to cursor + n: 5, + ln: 5, + // Resulting context map + contextCache: ['c', 'a', 'b', 'b', 'a'], + + baseSequence: { "output": "cabba", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + fullMatchDefs: [{ + sequence: { "output": "cacca", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: true, + msg: "Rule 2: Alternate 'any' store character failed to match the rule." + }, { + sequence: { "output": "cabca", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: false, + msg: "Rule 2: 'any' and 'context' correspond to mismatching characters, but matched the rule." + }] +}; + +var ANY_CONTEXT_TEST_3 = { + id: 3, + // Match condition for rule + rule: ['c', {t:'a', a: "ac"}, {t:'a', a: "bc"}, {t:'c', c:3}, {t:'c', c:2}], + // Start of context relative to cursor + n: 5, + ln: 5, + // Resulting context map + contextCache: ['c', 'a', 'b', 'b', 'a'], + + baseSequence: { "output": "cabba", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + fullMatchDefs: [{ + sequence: { "output": "cacca", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: true, + msg: "Rule 3: Alternate 'any' store character failed to match the rule." + }, { + sequence: { "output": "ccccc", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //c + ]}, + result: true, + msg: "Rule 3: Alternate 'any' store character failed to match the rule." + }, { + sequence: { "output": "cabab", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: false, + msg: "Rule 3: context() rule component is matching the incorrect any() component." + }] +}; + +var ANY_INDEX_TEST_1 = { + id: 1, + // Match condition for rule + rule: ['c', 'a', {t:'a', a: "bc"}, {t:'i', i:"bc", o:3}, 'a'], + // Start of context relative to cursor + n: 5, + ln: 5, + // Resulting context map + contextCache: ['c', 'a', 'b', 'b', 'a'], + + baseSequence: { "output": "cabba", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + fullMatchDefs: [{ + sequence: { "output": "cacca", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: true, + msg: "Rule 1: Alternate 'any' store character failed to match the rule." + }, { + sequence: { "output": "cabca", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: false, + msg: "Rule 1: 'any' and 'output' correspond to mismatching characters, but matched the rule." + }] +}; + +var ANY_INDEX_TEST_2 = { + id: 2, + // Match condition for rule + rule: ['c', {t:'a', a:"ab"}, {t:'i', i:"bc", o:2}, {t:'i', i:"bc", o:2}, {t:'i', i:"ab", o:2}], + // Start of context relative to cursor + n: 5, + ln: 5, + // Resulting context map + contextCache: ['c', 'a', 'b', 'b', 'a'], + + baseSequence: { "output": "cabba", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + fullMatchDefs: [{ + sequence: { "output": "cacca", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: false, + msg: "Rule 2: Mismatch with secondary output store did not fail the rule." + }, { + sequence: { "output": "cbccb", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: true, + msg: "Rule 2: Alternate 'any' store character failed to match the rule." + }] +}; + +var ANY_INDEX_TEST_3 = { + id: 3, + // Match condition for rule + rule: ['c', {t:'a', a:"ab"}, {t:'a', a:"bc"}, {t:'i', i:"bc", o:3}, {t:'i', i:"ab", o:2}], + // Start of context relative to cursor + n: 5, + ln: 5, + // Resulting context map + contextCache: ['c', 'a', 'b', 'b', 'a'], + + baseSequence: { "output": "cabba", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + fullMatchDefs: [{ + sequence: { "output": "cacca", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //a + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: true, + msg: "Rule 3a: Error with index() when a rule has multiple any() checks." + }, { + sequence: { "output": "cbccb", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: true, + msg: "Rule 3b: Error with index() when a rule has multiple any() checks." + }, { + sequence: { "output": "cbbbb", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: true, + msg: "Rule 3c: Error with index() when a rule has multiple any() checks." + }, { + sequence: { "output": "cbccc", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //c + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //c + ]}, + result: false, + msg: "Rule 3: index() rule check matched the incorrect any()." + }] +}; + +var DEADKEY_STORE_TEST_1 = { + id: 1, + // Match condition for rule + rule: [{t:'a',a:[{d:0},{d:1},{d:2}]}], + // Start of context relative to cursor + n: 1, + ln: 1, + // Resulting context map + contextCache: [0], + + baseSequence: { "output": "", "inputs": [ + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //1 + ]}, + fullMatchDefs: [{ + sequence: { "output": "", "inputs": [ + {"type":"key","keyCode":51,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //3 + ]}, + result: true, + msg: "Rule 1: Alternate 'any' store deadkey character failed to match the rule." + }, { + sequence: { "output": "c", "inputs": [ + {"type":"key","keyCode":67,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //c + ]}, + result: false, + msg: "Rule 1: standard character mysteriously matched a deadkey from a store." + }] +}; + +var DEADKEY_STORE_TEST_2 = { + id: 2, + // Match condition for rule + rule: [{t:'a',a:[{d:0},'b',{d:2}]}], + // Start of context relative to cursor + n: 1, + ln: 1, + // Resulting context map + contextCache: [0], + + baseSequence: { "output": "", "inputs": [ + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //1 + ]}, + fullMatchDefs: [{ + sequence: { "output": "", "inputs": [ + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //2 + ]}, + result: false, + msg: "Rule 2: deadkey not in store mysteriously matched within an any(store) op." + }, { + sequence: { "output": "", "inputs": [ + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: true, + msg: "Rule 2: standard character in store failed to match within an any(store) op." + }] +}; + +var DEADKEY_STORE_TEST_3 = { + id: 3, + // Match condition for rule + rule: [{t:'a',a:[{d:0},{d:1},{d:2}]},{t:'i',i:"abc", o:1}], + // Start of context relative to cursor + n: 2, + ln: 2, + // Resulting context map + contextCache: [0,'a'], + + baseSequence: { "output": "a", "inputs": [ + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //1 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + fullMatchDefs: [{ + sequence: { "output": "b", "inputs": [ + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //a + ]}, + result: false, + msg: "Rule 3a: index in deadkey store not properly tracked by indexOutput." + }, { + sequence: { "output": "b", "inputs": [ + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: true, + msg: "Rule 3a: index in deadkey store not properly tracked by indexOutput." + }, { + sequence: { "output": "b", "inputs": [ + {"type":"key","keyCode":65,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //2 + ]}, + result: false, + msg: "Rule 3: incorrectly matched rule when deadkey and character were incorrectly ordered." + }, { + sequence: { "output": "bb", "inputs": [ + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: false, + msg: "Rule 3: triggered when rule is one regular character out of context." + }, { + sequence: { "output": "b", "inputs": [ + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //b + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //2 + ]}, + result: false, + msg: "Rule 3: triggered when rule is one deadkey out of context." + }] +}; + +var DEADKEY_STORE_TEST_4 = { + id: 4, + // Match condition for rule + rule: [{t:'a',a:[{d:0},{d:1},{d:2}]},{t:'c',c:1}], + // Start of context relative to cursor + n: 2, + ln: 2, + // Resulting context map + contextCache: [1,1], + + baseSequence: { "output": "", "inputs": [ + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //2 + ]}, + fullMatchDefs: [{ + sequence: { "output": "", "inputs": [ + {"type":"key","keyCode":50,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //2 + {"type":"key","keyCode":49,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //1 + ]}, + result: false, + msg: "Rule 4: context matched to alternate (not selected) any(store) option erroneously." + }, { + sequence: { "output": "b", "inputs": [ + {"type":"key","keyCode":51,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //3 + {"type":"key","keyCode":51,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true}, //3 + {"type":"key","keyCode":66,"states":10752,"modifiers":0,"modifierChanged":false,"isVirtualKey":true} //b + ]}, + result: false, + msg: "Rule 4: triggered when rule is slightly out of context." + }] +}; + +var DEADKEY_RULE_SET = [ DEADKEY_TEST_1, DEADKEY_TEST_2, DEADKEY_TEST_3, DEADKEY_TEST_4, + DEADKEY_TEST_5, DEADKEY_TEST_6 +]; +var ANY_CONTEXT_RULE_SET = [ ANY_CONTEXT_TEST_1, ANY_CONTEXT_TEST_2, ANY_CONTEXT_TEST_3 ]; + var ANY_INDEX_RULE_SET = [ ANY_INDEX_TEST_1, ANY_INDEX_TEST_2, ANY_INDEX_TEST_3 ]; + var DEADKEY_STORE_RULE_SET = [ DEADKEY_STORE_TEST_1, DEADKEY_STORE_TEST_2, DEADKEY_STORE_TEST_3, + DEADKEY_STORE_TEST_4 ]; + + var FULL_RULE_SET = [].concat(DEADKEY_RULE_SET, ANY_CONTEXT_RULE_SET, ANY_INDEX_RULE_SET, + DEADKEY_STORE_RULE_SET); + + // ----------- + +describe('Engine - Context Matching', function() { + before(function() { + let kp = new KeyboardProcessor(); + + // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will + // automatically set the keyboard as active. + var script = new vm.Script(fs.readFileSync('../tests/resources/keyboards/test_simple_deadkeys.js')); + script.runInThisContext(); + + keyboard = kp.activeKeyboard; + }); + + // Tests "stage 1" of fullContextMatch - ensuring that a proper context index map is built. + it('properly generates extended context data needed by context-matching checks below', function() { + let matchDefs = FULL_RULE_SET; + + for(var j = 0; j < matchDefs.length; j++) { + // Prepare the context! + var ruleDef = matchDefs[j]; + var ruleSeq = new KMWRecorder.RecordedKeystrokeSequence(ruleDef.baseSequence); + let proctor = new KMWRecorder.NodeProctor(keyboard, device, assert.equal); + + // We want to specify the OutputTarget for this test; our actual concern is the resulting context. + var target = new com.keyman.text.Mock(); + ruleSeq.test(proctor, target); + + // Now for the real test! + let processor = new KeyboardProcessor(); + processor.activeKeyboard = keyboard; + var res = processor.keyboardInterface._BuildExtendedContext(ruleDef.n, ruleDef.ln, target); + + assert.sameOrderedMembers(res.valContext, ruleDef.contextCache); + } + }); + + describe('handles simple deadkey contexts', function() { + it('for the most basic cases: DEADKEY_TEST_1', function() { + runEngineRuleSet(DEADKEY_TEST_1, "Deadkeys"); + }); + + it('with deadkey ordering: DEADKEY_TEST_2', function() { + runEngineRuleSet(DEADKEY_TEST_2, "Deadkeys"); + }); + + it('with repeated deadkeys: DEADKEY_TEST_3', function() { + runEngineRuleSet(DEADKEY_TEST_3, "Deadkeys"); + }); + + it('with caret after deadkey: DEADKEY_TEST_4', function() { + runEngineRuleSet(DEADKEY_TEST_4, "Deadkeys"); + }); + + it('with no deadkeys, mid-text: DEADKEY_TEST_5', function() { + runEngineRuleSet(DEADKEY_TEST_5, "Deadkeys"); + }); + + it('with long sequence of only deadkeys: DEADKEY_TEST_6', function() { + runEngineRuleSet(DEADKEY_TEST_6, "Deadkeys"); + }); + }); + + describe('handles any + context rule interactions', function() { + it('for basic context matches, no any: ANY_CONTEXT_TEST_1', function() { + runEngineRuleSet(ANY_CONTEXT_TEST_1); + }); + + it('for any + context-of-any matches: ANY_CONTEXT_TEST_2', function() { + runEngineRuleSet(ANY_CONTEXT_TEST_2); + }); + + it('for rules with multiple any + context-of-any pairs: ANY_CONTEXT_TEST_3', function() { + runEngineRuleSet(ANY_CONTEXT_TEST_3); + }); + }); + + describe('handles any + index context interactions', function() { + it('for basic any + index matches in context: ANY_INDEX_TEST_1', function() { + runEngineRuleSet(ANY_INDEX_TEST_1); + }); + + it('for one-any to many-index matches in context: ANY_INDEX_TEST_2', function() { + runEngineRuleSet(ANY_INDEX_TEST_2); + }); + + it('for two any + index pairs in rule: ANY_INDEX_TEST_3', function() { + runEngineRuleSet(ANY_INDEX_TEST_3); + }); + }); + + describe('handles interactions with deadkeys in stores', function() { + it('for any on pure deadkey store: DEADKEY_STORE_TEST_1', function() { + runEngineRuleSet(DEADKEY_STORE_TEST_1); + }); + + it('for any on mixed char+deadkey store: DEADKEY_STORE_TEST_2', function() { + runEngineRuleSet(DEADKEY_STORE_TEST_2); + }); + + it('for index matching any on pure deadkey store: DEADKEY_STORE_TEST_3', function() { + runEngineRuleSet(DEADKEY_STORE_TEST_3); + }); + + it('for context matching any on pure deadkey store: DEADKEY_STORE_TEST_4', function() { + runEngineRuleSet(DEADKEY_STORE_TEST_4); + }); + }); +}); \ No newline at end of file diff --git a/common/core/web/keyboard-processor/tests/cases/engine/stores.js b/common/core/web/keyboard-processor/tests/cases/engine/stores.js new file mode 100644 index 0000000000000000000000000000000000000000..66f0a57b208c824e3469d24676d7a1c4b9e3f5d3 --- /dev/null +++ b/common/core/web/keyboard-processor/tests/cases/engine/stores.js @@ -0,0 +1,49 @@ +var assert = require('chai').assert; +let fs = require('fs'); +let vm = require('vm'); + +let KeyboardProcessor = require('../../../dist'); +let KMWRecorder = require('../../../../tools/recorder/dist/nodeProctor'); + +// Required initialization setup. +global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing. + +describe('Engine - Stores', function() { + var toSupplementaryPairString = function(code){ + var H = Math.floor((code - 0x10000) / 0x400) + 0xD800; + var L = (code - 0x10000) % 0x400 + 0xDC00; + + return String.fromCharCode(H, L); + } + + it('Store \'Explosion\'', function() { + let processor = new KeyboardProcessor(); + // A 'hollow' Keyboard that only follows default rules. That said, we need a Keyboard + // instance to host cache data for our exploded store tests. + processor.activeKeyboard = new com.keyman.keyboards.Keyboard(); + + // Function defined at top of file; creates supplementary pairs for extended Unicode codepoints. + var u = toSupplementaryPairString; + + var STORES = [ + {smp: false, in: "apple", out: ['a','p','p','l','e']}, + //In JS-escaped form: "\\ud804\\udd12\\ud804\\udd0d\\ud804\\udd0f\\ud804\\udd10\\ud804\\udd0a\\ud804\\udd05" + //(Supplementary pairs, copied from the easy_chakma keyboard.) + {smp: true, in: "𑄒𑄍𑄏𑄐𑄊𑄅", out: ["𑄒","𑄍","𑄏","𑄐","𑄊","𑄅"]}, + // Built in-line via function. Looks functionally equivalent to "apple", but with SMP characters. + {smp: true, in: (u(0x1d5ba)+u(0x1d5c9)+u(0x1d5c9)+u(0x1d5c5)+u(0x1d5be)), + out: [u(0x1d5ba), u(0x1d5c9), u(0x1d5c9), u(0x1d5c5), u(0x1d5be)]} + ]; + + for(var i=0; i < STORES.length; i++) { + var s = STORES[i]; + + String.kmwEnableSupplementaryPlane(s.smp); + var result = processor.keyboardInterface._ExplodeStore(s.in); + assert.sameOrderedMembers(result, s.out, "Failure exploding " + (s.smp ? "SMP" : "non-SMP") + " string value \"" + s.in + "\""); + } + String.kmwEnableSupplementaryPlane(false); + }); + + // TODO: Migrate a Node-based copy of the variable store tests here as well. +}); \ No newline at end of file diff --git a/web/unit_tests/cases/transcriptions.js b/common/core/web/keyboard-processor/tests/cases/transcriptions.js similarity index 97% rename from web/unit_tests/cases/transcriptions.js rename to common/core/web/keyboard-processor/tests/cases/transcriptions.js index 3c5cb3662ec9f7b2625a5ec9b650dec073d53caf..9e9f04df1f748a75fd5bb68872837bb498d6c79f 100644 --- a/web/unit_tests/cases/transcriptions.js +++ b/common/core/web/keyboard-processor/tests/cases/transcriptions.js @@ -1,13 +1,12 @@ -var assert = chai.assert; +var assert = require('chai').assert; +let KeyboardProcessor = require('../../dist'); -describe("Transcriptions and Transforms", function() { - this.timeout(kmwconfig.timeouts.standard); +// Required initialization setup. +global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing. - before(function() { - // Make sure the basic SMP extension hooks exist to prevent errors later. - String.kmwEnableSupplementaryPlane(false); - }); +String.kmwEnableSupplementaryPlane(false); +describe("Transcriptions and Transforms", function() { it("does not store an alias for related OutputTargets", function() { var Mock = com.keyman.text.Mock; diff --git a/web/unit_tests/cases/versions.js b/common/core/web/keyboard-processor/tests/cases/versions.js similarity index 85% rename from web/unit_tests/cases/versions.js rename to common/core/web/keyboard-processor/tests/cases/versions.js index bd77a9039df97510fd529ff2a4773f587f25fa1c..2345602de39fe0597f00ce418a3d71f464fc5e3e 100644 --- a/web/unit_tests/cases/versions.js +++ b/common/core/web/keyboard-processor/tests/cases/versions.js @@ -1,17 +1,10 @@ -var assert = chai.assert; +var assert = require('chai').assert; +let KeyboardProcessor = require('../../dist'); -describe('Version Logic', function() { - this.timeout(kmwconfig.timeouts.standard); +// Required initialization setup. +global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing. - before(function(done) { - this.timeout(kmwconfig.timeouts.scriptLoad); - setupKMW(null, done, kmwconfig.timeouts.scriptLoad); - }); - - after(function() { - teardownKMW(); - }); - +describe('Version Logic', function() { it('Should provide a default, fallback value when nothing is specified', function() { var fallback = new com.keyman.utils.Version(undefined); assert.isTrue(fallback.equals(com.keyman.utils.Version.DEVELOPER_VERSION_FALLBACK)); diff --git a/web/unit_tests/fixtures/eventTestConfig.html b/common/core/web/tests/resources/fixtures/eventTestConfig.html similarity index 100% rename from web/unit_tests/fixtures/eventTestConfig.html rename to common/core/web/tests/resources/fixtures/eventTestConfig.html diff --git a/web/unit_tests/fixtures/robustAttachment.html b/common/core/web/tests/resources/fixtures/robustAttachment.html similarity index 100% rename from web/unit_tests/fixtures/robustAttachment.html rename to common/core/web/tests/resources/fixtures/robustAttachment.html diff --git a/web/unit_tests/fixtures/singleInput.html b/common/core/web/tests/resources/fixtures/singleInput.html similarity index 100% rename from web/unit_tests/fixtures/singleInput.html rename to common/core/web/tests/resources/fixtures/singleInput.html diff --git a/web/unit_tests/resources/html/editableFrame.html b/common/core/web/tests/resources/html/editableFrame.html similarity index 100% rename from web/unit_tests/resources/html/editableFrame.html rename to common/core/web/tests/resources/html/editableFrame.html diff --git a/web/unit_tests/resources/html/iframe.html b/common/core/web/tests/resources/html/iframe.html similarity index 100% rename from web/unit_tests/resources/html/iframe.html rename to common/core/web/tests/resources/html/iframe.html diff --git a/web/unit_tests/json/engine_tests/basic_lao_simulation.json b/common/core/web/tests/resources/json/engine_tests/basic_lao_simulation.json similarity index 71% rename from web/unit_tests/json/engine_tests/basic_lao_simulation.json rename to common/core/web/tests/resources/json/engine_tests/basic_lao_simulation.json index d59a61c0529bc274e15be36c7fd52ebe3d120ad1..1a840bca4bae4a000e305be1510bc10e31d84355 100644 --- a/web/unit_tests/json/engine_tests/basic_lao_simulation.json +++ b/common/core/web/tests/resources/json/engine_tests/basic_lao_simulation.json @@ -1,4 +1,5 @@ { + "specVersion": "14.0", "keyboard": { "id": "lao_2008_basic", "name": "Lao Basic", @@ -23,11 +24,19 @@ "inputs": [ { "type": "key", - "key": "s", - "code": "KeyS", "keyCode": 83, - "modifierSet": 0, - "location": 0 + "states": 10752, + "modifiers": 0, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "s", + "code": "KeyS", + "keyCode": 83, + "location": 0, + "modifierSet": 0 + } } ], "output": "ຫ" @@ -45,7 +54,8 @@ "inputs": [ { "type": "osk", - "keyID": "default-K_S" + "layer": "default", + "keyName": "K_S" } ], "output": "ຫ" @@ -63,7 +73,8 @@ "inputs": [ { "type": "osk", - "keyID": "default-K_S" + "layer": "default", + "keyName": "K_S" } ], "output": "ຫ" @@ -81,7 +92,8 @@ "inputs": [ { "type": "osk", - "keyID": "default-K_S" + "layer": "default", + "keyName": "K_S" } ], "output": "ຫ" diff --git a/common/core/web/tests/resources/json/engine_tests/chirality.json b/common/core/web/tests/resources/json/engine_tests/chirality.json new file mode 100644 index 0000000000000000000000000000000000000000..f46ab5399ddb4f94005f7245f063d929fe907a3b --- /dev/null +++ b/common/core/web/tests/resources/json/engine_tests/chirality.json @@ -0,0 +1,639 @@ +{ + "specVersion": "14.0", + "keyboard": { + "id": "test_chirality", + "name": "KeymanWeb Chirality Tester", + "filename": "resources/keyboards/test_chirality.js", + "languages": {} + }, + "inputTestSets": [ + { + "constraint": { + "target": "hardware", + "validOSList": null, + "validBrowsers": null + }, + "testSet": [ + { + "inputs": [ + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "DF_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 17, + "states": 10752, + "modifiers": 1, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Control", + "code": "ControlLeft", + "keyCode": 17, + "location": 1, + "modifierSet": 2 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 1, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 2 + } + } + ], + "output": "LC_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 18, + "states": 10752, + "modifiers": 4, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Alt", + "code": "AltLeft", + "keyCode": 18, + "location": 1, + "modifierSet": 4 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 4, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 4 + } + } + ], + "output": "LA_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 18, + "states": 10752, + "modifiers": 8, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Alt", + "code": "AltRight", + "keyCode": 18, + "location": 2, + "modifierSet": 4 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 8, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 4 + } + } + ], + "output": "RA_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 17, + "states": 10752, + "modifiers": 2, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Control", + "code": "ControlRight", + "keyCode": 17, + "location": 2, + "modifierSet": 2 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 2, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 2 + } + } + ], + "output": "RC_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 17, + "states": 10752, + "modifiers": 1, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Control", + "code": "ControlLeft", + "keyCode": 17, + "location": 1, + "modifierSet": 2 + } + }, + { + "type": "key", + "keyCode": 16, + "states": 10752, + "modifiers": 17, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Shift", + "code": "ShiftLeft", + "keyCode": 16, + "location": 1, + "modifierSet": 3 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 17, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "A", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 3 + } + } + ], + "output": "LC_CAP_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 17, + "states": 10752, + "modifiers": 1, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Control", + "code": "ControlLeft", + "keyCode": 17, + "location": 1, + "modifierSet": 2 + } + }, + { + "type": "key", + "keyCode": 18, + "states": 10752, + "modifiers": 8, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Alt", + "code": "AltLeft", + "keyCode": 18, + "location": 1, + "modifierSet": 6 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 8, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 6 + } + } + ], + "msg": "AltGr emulation failed!", + "output": "RA_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 17, + "states": 10752, + "modifiers": 1, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Control", + "code": "ControlLeft", + "keyCode": 17, + "location": 1, + "modifierSet": 2 + } + }, + { + "type": "key", + "keyCode": 18, + "states": 10752, + "modifiers": 8, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Alt", + "code": "AltLeft", + "keyCode": 18, + "location": 1, + "modifierSet": 6 + } + }, + { + "type": "key", + "keyCode": 16, + "states": 10752, + "modifiers": 24, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Shift", + "code": "ShiftLeft", + "keyCode": 16, + "location": 1, + "modifierSet": 7 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 24, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "A", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 7 + } + } + ], + "msg": "AltGr emulation failed!", + "output": "RA_CAP_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 18, + "states": 10752, + "modifiers": 4, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Alt", + "code": "AltLeft", + "keyCode": 18, + "location": 1, + "modifierSet": 4 + } + }, + { + "type": "key", + "keyCode": 16, + "states": 10752, + "modifiers": 20, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Shift", + "code": "ShiftLeft", + "keyCode": 16, + "location": 1, + "modifierSet": 5 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 20, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "A", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 5 + } + } + ], + "output": "LA_CAP_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 20, + "states": 10496, + "modifiers": 0, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "CapsLock", + "code": "CapsLock", + "keyCode": 20, + "location": 0, + "modifierSet": 16 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10496, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "A", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 16 + } + } + ], + "output": "CAPSLOCK_DF_a" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 66, + "states": 10496, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "B", + "code": "KeyB", + "keyCode": 66, + "location": 0, + "modifierSet": 16 + } + } + ], + "output": "b" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 66, + "states": 10752, + "modifiers": 0, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "b", + "code": "KeyB", + "keyCode": 66, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "b" + } + ] + }, + { + "constraint": { + "target": "desktop", + "validOSList": null, + "validBrowsers": null + }, + "testSet": [ + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + } + ], + "output": "DF_a" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_LCONTROL" + }, + { + "type": "osk", + "layer": "leftctrl", + "keyName": "K_LALT" + }, + { + "type": "osk", + "layer": "leftctrl-leftalt", + "keyName": "K_A" + } + ], + "output": "RA_a", + "msg": "OSK-based AltGr emulation failed!" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_LCONTROL" + }, + { + "type": "osk", + "layer": "leftctrl", + "keyName": "K_LALT" + }, + { + "type": "osk", + "layer": "leftctrl-leftalt", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "leftctrl-leftalt-shift", + "keyName": "K_A" + } + ], + "output": "RA_CAP_a", + "msg": "OSK-based AltGr emulation failed!" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_RALT" + }, + { + "type": "osk", + "layer": "rightalt", + "keyName": "K_A" + } + ], + "output": "RA_a" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_RCONTROL" + }, + { + "type": "osk", + "layer": "rightctrl", + "keyName": "K_A" + } + ], + "output": "RC_a" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_RALT" + }, + { + "type": "osk", + "layer": "rightalt", + "keyName": "K_RCONTROL" + }, + { + "type": "osk", + "layer": "rightctrl-rightalt", + "keyName": "K_A" + } + ], + "output": "RCA_a" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_CAPS" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_RCONTROL" + }, + { + "type": "osk", + "layer": "rightctrl", + "keyName": "K_RSHIFT" + }, + { + "type": "osk", + "layer": "rightctrl-shift", + "keyName": "K_A" + } + ], + "output": "CAPSLOCK_RC_CAP_a" + } + ] + } + ] +} \ No newline at end of file diff --git a/common/core/web/tests/resources/json/engine_tests/deadkeys.json b/common/core/web/tests/resources/json/engine_tests/deadkeys.json new file mode 100644 index 0000000000000000000000000000000000000000..1764915605bda0c7fe2b229d4dc992d69265f233 --- /dev/null +++ b/common/core/web/tests/resources/json/engine_tests/deadkeys.json @@ -0,0 +1,1835 @@ +{ + "specVersion": "14.0", + "keyboard": { + "id": "test_deadkeys", + "name": "Keyman Deadkey Stress-Tester", + "filename": "resources/keyboards/test_deadkeys.js", + "languages": {} + }, + "inputTestSets": [ + { + "constraint": { + "target": "hardware", + "validOSList": null, + "validBrowsers": null + }, + "testSet": [ + { + "inputs": [ + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 66, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "b", + "code": "KeyB", + "keyCode": 66, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(a)(b)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 66, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "b", + "code": "KeyB", + "keyCode": 66, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(b)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 66, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "b", + "code": "KeyB", + "keyCode": 66, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 66, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "b", + "code": "KeyB", + "keyCode": 66, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(b)+(b)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 66, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "b", + "code": "KeyB", + "keyCode": 66, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 66, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "b", + "code": "KeyB", + "keyCode": 66, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(b)+(a)+(b)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 67, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "c", + "code": "KeyC", + "keyCode": 67, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "x" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 68, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "d", + "code": "KeyD", + "keyCode": 68, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 69, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "e", + "code": "KeyE", + "keyCode": 69, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(a)(d)(e)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 70, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "f", + "code": "KeyF", + "keyCode": 70, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 68, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "d", + "code": "KeyD", + "keyCode": 68, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 69, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "e", + "code": "KeyE", + "keyCode": 69, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(f)-(a)-(d)-(e)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 83, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "s", + "code": "KeyS", + "keyCode": 83, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 190, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": ".", + "code": "Period", + "keyCode": 190, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(a)-(s)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 83, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "s", + "code": "KeyS", + "keyCode": 83, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 190, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": ".", + "code": "Period", + "keyCode": 190, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(s)+(a)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 77, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "m", + "code": "KeyM", + "keyCode": 77, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 190, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": ".", + "code": "Period", + "keyCode": 190, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "dk(m)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 78, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "n", + "code": "KeyN", + "keyCode": 78, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 190, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": ".", + "code": "Period", + "keyCode": 190, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "dk(n)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 79, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "o", + "code": "KeyO", + "keyCode": 79, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 190, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": ".", + "code": "Period", + "keyCode": 190, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "dk(o)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 79, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "o", + "code": "KeyO", + "keyCode": 79, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(o)(o)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 80, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "p", + "code": "KeyP", + "keyCode": 80, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 81, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "q", + "code": "KeyQ", + "keyCode": 81, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 82, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "r", + "code": "KeyR", + "keyCode": 82, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(p)(q)(r)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 16, + "states": 10752, + "modifiers": 16, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Shift", + "code": "ShiftRight", + "keyCode": 16, + "location": 2, + "modifierSet": 1 + } + }, + { + "type": "key", + "keyCode": 80, + "states": 10752, + "modifiers": 16, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "P", + "code": "KeyP", + "keyCode": 80, + "location": 0, + "modifierSet": 1 + } + }, + { + "type": "key", + "keyCode": 16, + "states": 10752, + "modifiers": 16, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Shift", + "code": "ShiftLeft", + "keyCode": 16, + "location": 1, + "modifierSet": 1 + } + }, + { + "type": "key", + "keyCode": 16, + "states": 10752, + "modifiers": 16, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Shift", + "code": "ShiftLeft", + "keyCode": 16, + "location": 1, + "modifierSet": 1 + } + }, + { + "type": "key", + "keyCode": 16, + "states": 10752, + "modifiers": 16, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Shift", + "code": "ShiftLeft", + "keyCode": 16, + "location": 1, + "modifierSet": 1 + } + }, + { + "type": "key", + "keyCode": 81, + "states": 10752, + "modifiers": 16, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Q", + "code": "KeyQ", + "keyCode": 81, + "location": 0, + "modifierSet": 1 + } + }, + { + "type": "key", + "keyCode": 82, + "states": 10752, + "modifiers": 16, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "R", + "code": "KeyR", + "keyCode": 82, + "location": 0, + "modifierSet": 1 + } + } + ], + "output": "(P)(Q)(R)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 51, + "states": 10752, + "modifiers": 0, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "3", + "code": "Digit3", + "keyCode": 51, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 190, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": ".", + "code": "Period", + "keyCode": 190, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "#3" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 81, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "q", + "code": "KeyQ", + "keyCode": 81, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 16, + "states": 10752, + "modifiers": 16, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "Shift", + "code": "ShiftLeft", + "keyCode": 16, + "location": 1, + "modifierSet": 1 + } + }, + { + "type": "key", + "keyCode": 49, + "states": 10752, + "modifiers": 16, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "!", + "code": "Digit1", + "keyCode": 49, + "location": 0, + "modifierSet": 1 + } + }, + { + "type": "key", + "keyCode": 190, + "states": 10752, + "modifiers": 0, + "modifierChanged": true, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": ".", + "code": "Period", + "keyCode": 190, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(qq)" + }, + { + "inputs": [ + { + "type": "key", + "keyCode": 51, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "3", + "code": "Digit3", + "keyCode": 51, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 51, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "3", + "code": "Digit3", + "keyCode": 51, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "(3)(3)" + } + ] + }, + { + "constraint": { + "target": "desktop", + "validOSList": null, + "validBrowsers": null + }, + "testSet": [ + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(a)(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)+(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)+(a)+(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_C" + } + ], + "output": "x" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_D" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_E" + } + ], + "output": "(a)(d)(e)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_F" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_D" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_E" + } + ], + "output": "(f)-(a)-(d)-(e)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_S" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(a)-(s)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_S" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(s)+(a)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_M" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(m)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_N" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(n)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_O" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(o)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_P" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_Q" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_R" + } + ], + "output": "(p)(q)(r)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_RSHIFT" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_P" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_Q" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_R" + } + ], + "output": "(P)(Q)(R)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_3" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "#3" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_W" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_1" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(ww)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_4" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_4" + } + ], + "output": "(4)(4)" + } + ] + }, + { + "constraint": { + "target": "phone", + "validOSList": null, + "validBrowsers": null + }, + "testSet": [ + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(a)(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)+(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)+(a)+(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_C" + } + ], + "output": "x" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_D" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_E" + } + ], + "output": "(a)(d)(e)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_F" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_D" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_E" + } + ], + "output": "(f)-(a)-(d)-(e)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_S" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(a)-(s)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_S" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(s)+(a)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_M" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(m)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_N" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(n)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_O" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(o)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_P" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_Q" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_R" + } + ], + "output": "(p)(q)(r)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_P" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_Q" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_R" + } + ], + "output": "(P)(Q)(R)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_7" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "#7" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_R" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_1" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(rr)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_0" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_0" + } + ], + "output": "(0)(0)" + } + ] + }, + { + "constraint": { + "target": "tablet", + "validOSList": null, + "validBrowsers": null + }, + "testSet": [ + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(a)(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)+(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_B" + } + ], + "output": "(b)+(a)+(b)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_C" + } + ], + "output": "x" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_D" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_E" + } + ], + "output": "(a)(d)(e)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_F" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_D" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_E" + } + ], + "output": "(f)-(a)-(d)-(e)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_S" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(a)-(s)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_S" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_A" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(s)+(a)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_M" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(m)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_N" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(n)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_O" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "dk(o)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_P" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_Q" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_R" + } + ], + "output": "(p)(q)(r)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_P" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_Q" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_R" + } + ], + "output": "(P)(Q)(R)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_7" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "#7" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_R" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_1" + }, + { + "type": "osk", + "layer": "shift", + "keyName": "K_SHIFT" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_PERIOD" + } + ], + "output": "(rr)" + }, + { + "inputs": [ + { + "type": "osk", + "layer": "default", + "keyName": "K_0" + }, + { + "type": "osk", + "layer": "default", + "keyName": "K_0" + } + ], + "output": "(0)(0)" + } + ] + } + ] +} \ No newline at end of file diff --git a/common/core/web/tests/resources/json/engine_tests/options_with_save_1.json b/common/core/web/tests/resources/json/engine_tests/options_with_save_1.json new file mode 100644 index 0000000000000000000000000000000000000000..fd2d2fdaa02545143a43c5651723fc20c05a679e --- /dev/null +++ b/common/core/web/tests/resources/json/engine_tests/options_with_save_1.json @@ -0,0 +1,79 @@ +{ + "specVersion": "14.0", + "keyboard": { + "id": "options_with_save", + "name": "Variable-store test kbd: options_with_save", + "filename": "resources/keyboards/options_with_save.js", + "languages": [ + { + "id": "en", + "name": "English", + "region": "World" + } + ] + }, + "inputTestSets": [ + { + "constraint": { + "target": "hardware", + "validOSList": null, + "validBrowsers": null + }, + "testSet": [ + { + "inputs": [ + { + "type": "key", + "keyCode": 65, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 48, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "0", + "code": "Digit0", + "keyCode": 48, + "location": 0, + "modifierSet": 0 + } + }, + { + "type": "key", + "keyCode": 50, + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "2", + "code": "Digit2", + "keyCode": 50, + "location": 0, + "modifierSet": 0 + } + } + ], + "output": "foo." + } + ] + } + ] +} \ No newline at end of file diff --git a/web/unit_tests/json/engine_tests/options_with_save_2.json b/common/core/web/tests/resources/json/engine_tests/options_with_save_2.json similarity index 61% rename from web/unit_tests/json/engine_tests/options_with_save_2.json rename to common/core/web/tests/resources/json/engine_tests/options_with_save_2.json index 9485aca16655c60e5cdbd91ed3857ad71b290414..3d5380582422c9867136dc912544c17d99c939c7 100644 --- a/web/unit_tests/json/engine_tests/options_with_save_2.json +++ b/common/core/web/tests/resources/json/engine_tests/options_with_save_2.json @@ -1,4 +1,5 @@ { + "specVersion": "14.0", "keyboard": { "id": "options_with_save", "name": "Variable-store test kbd: options_with_save", @@ -23,11 +24,19 @@ "inputs": [ { "type": "key", - "key": "a", - "code": "KeyA", "keyCode": 65, - "modifierSet": 0, - "location": 0 + "states": 10752, + "modifiers": 0, + "modifierChanged": false, + "isVirtualKey": true, + "eventSpec": { + "type": "key", + "key": "a", + "code": "KeyA", + "keyCode": 65, + "location": 0, + "modifierSet": 0 + } } ], "output": "no foo." diff --git a/web/unit_tests/json/keyboards/khmer_angkor.json b/common/core/web/tests/resources/json/keyboards/khmer_angkor.json similarity index 100% rename from web/unit_tests/json/keyboards/khmer_angkor.json rename to common/core/web/tests/resources/json/keyboards/khmer_angkor.json diff --git a/web/unit_tests/json/keyboards/lao_2008_basic.json b/common/core/web/tests/resources/json/keyboards/lao_2008_basic.json similarity index 100% rename from web/unit_tests/json/keyboards/lao_2008_basic.json rename to common/core/web/tests/resources/json/keyboards/lao_2008_basic.json diff --git a/web/unit_tests/json/keyboards/options_with_save.json b/common/core/web/tests/resources/json/keyboards/options_with_save.json similarity index 100% rename from web/unit_tests/json/keyboards/options_with_save.json rename to common/core/web/tests/resources/json/keyboards/options_with_save.json diff --git a/web/unit_tests/json/keyboards/test_chirality.json b/common/core/web/tests/resources/json/keyboards/test_chirality.json similarity index 100% rename from web/unit_tests/json/keyboards/test_chirality.json rename to common/core/web/tests/resources/json/keyboards/test_chirality.json diff --git a/web/unit_tests/json/keyboards/test_deadkeys.json b/common/core/web/tests/resources/json/keyboards/test_deadkeys.json similarity index 100% rename from web/unit_tests/json/keyboards/test_deadkeys.json rename to common/core/web/tests/resources/json/keyboards/test_deadkeys.json diff --git a/web/unit_tests/json/keyboards/test_simple_deadkeys.json b/common/core/web/tests/resources/json/keyboards/test_simple_deadkeys.json similarity index 100% rename from web/unit_tests/json/keyboards/test_simple_deadkeys.json rename to common/core/web/tests/resources/json/keyboards/test_simple_deadkeys.json diff --git a/web/unit_tests/resources/keyboards/khmer_angkor.js b/common/core/web/tests/resources/keyboards/khmer_angkor.js similarity index 100% rename from web/unit_tests/resources/keyboards/khmer_angkor.js rename to common/core/web/tests/resources/keyboards/khmer_angkor.js diff --git a/web/unit_tests/resources/keyboards/lao_2008_basic.js b/common/core/web/tests/resources/keyboards/lao_2008_basic.js similarity index 100% rename from web/unit_tests/resources/keyboards/lao_2008_basic.js rename to common/core/web/tests/resources/keyboards/lao_2008_basic.js diff --git a/web/unit_tests/resources/keyboards/options_with_save.js b/common/core/web/tests/resources/keyboards/options_with_save.js similarity index 100% rename from web/unit_tests/resources/keyboards/options_with_save.js rename to common/core/web/tests/resources/keyboards/options_with_save.js diff --git a/web/unit_tests/resources/keyboards/test_chirality.js b/common/core/web/tests/resources/keyboards/test_chirality.js similarity index 100% rename from web/unit_tests/resources/keyboards/test_chirality.js rename to common/core/web/tests/resources/keyboards/test_chirality.js diff --git a/web/unit_tests/resources/keyboards/test_chirality.kmn b/common/core/web/tests/resources/keyboards/test_chirality.kmn similarity index 100% rename from web/unit_tests/resources/keyboards/test_chirality.kmn rename to common/core/web/tests/resources/keyboards/test_chirality.kmn diff --git a/web/unit_tests/resources/keyboards/test_chirality.kmx b/common/core/web/tests/resources/keyboards/test_chirality.kmx similarity index 100% rename from web/unit_tests/resources/keyboards/test_chirality.kmx rename to common/core/web/tests/resources/keyboards/test_chirality.kmx diff --git a/web/unit_tests/resources/keyboards/test_chirality.kvk b/common/core/web/tests/resources/keyboards/test_chirality.kvk similarity index 100% rename from web/unit_tests/resources/keyboards/test_chirality.kvk rename to common/core/web/tests/resources/keyboards/test_chirality.kvk diff --git a/web/unit_tests/resources/keyboards/test_chirality.kvks b/common/core/web/tests/resources/keyboards/test_chirality.kvks similarity index 100% rename from web/unit_tests/resources/keyboards/test_chirality.kvks rename to common/core/web/tests/resources/keyboards/test_chirality.kvks diff --git a/web/unit_tests/resources/keyboards/test_deadkeys.js b/common/core/web/tests/resources/keyboards/test_deadkeys.js similarity index 100% rename from web/unit_tests/resources/keyboards/test_deadkeys.js rename to common/core/web/tests/resources/keyboards/test_deadkeys.js diff --git a/web/unit_tests/resources/keyboards/test_deadkeys.kmn b/common/core/web/tests/resources/keyboards/test_deadkeys.kmn similarity index 100% rename from web/unit_tests/resources/keyboards/test_deadkeys.kmn rename to common/core/web/tests/resources/keyboards/test_deadkeys.kmn diff --git a/web/unit_tests/resources/keyboards/test_deadkeys.kmx b/common/core/web/tests/resources/keyboards/test_deadkeys.kmx similarity index 100% rename from web/unit_tests/resources/keyboards/test_deadkeys.kmx rename to common/core/web/tests/resources/keyboards/test_deadkeys.kmx diff --git a/web/unit_tests/resources/keyboards/test_deadkeys.kvk b/common/core/web/tests/resources/keyboards/test_deadkeys.kvk similarity index 100% rename from web/unit_tests/resources/keyboards/test_deadkeys.kvk rename to common/core/web/tests/resources/keyboards/test_deadkeys.kvk diff --git a/web/unit_tests/resources/keyboards/test_deadkeys.kvks b/common/core/web/tests/resources/keyboards/test_deadkeys.kvks similarity index 100% rename from web/unit_tests/resources/keyboards/test_deadkeys.kvks rename to common/core/web/tests/resources/keyboards/test_deadkeys.kvks diff --git a/web/unit_tests/resources/keyboards/test_simple_deadkeys.js b/common/core/web/tests/resources/keyboards/test_simple_deadkeys.js similarity index 100% rename from web/unit_tests/resources/keyboards/test_simple_deadkeys.js rename to common/core/web/tests/resources/keyboards/test_simple_deadkeys.js diff --git a/web/unit_tests/resources/keyboards/test_simple_deadkeys.kmn b/common/core/web/tests/resources/keyboards/test_simple_deadkeys.kmn similarity index 100% rename from web/unit_tests/resources/keyboards/test_simple_deadkeys.kmn rename to common/core/web/tests/resources/keyboards/test_simple_deadkeys.kmn diff --git a/web/unit_tests/resources/keyboards/test_simple_deadkeys.kmx b/common/core/web/tests/resources/keyboards/test_simple_deadkeys.kmx similarity index 100% rename from web/unit_tests/resources/keyboards/test_simple_deadkeys.kmx rename to common/core/web/tests/resources/keyboards/test_simple_deadkeys.kmx diff --git a/web/unit_tests/resources/keyboards/unit_test_keyboards.kpj b/common/core/web/tests/resources/keyboards/unit_test_keyboards.kpj similarity index 100% rename from web/unit_tests/resources/keyboards/unit_test_keyboards.kpj rename to common/core/web/tests/resources/keyboards/unit_test_keyboards.kpj diff --git a/common/core/web/tools/recorder/.gitignore b/common/core/web/tools/recorder/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a9e0c255148b412ebdd55ddba4bc67f7322f814f --- /dev/null +++ b/common/core/web/tools/recorder/.gitignore @@ -0,0 +1,18 @@ +# Build products +src/environment.inc.ts + +# Legacy build folders. +output/ +build/ +embedded/ + +# Current build output folder (matches standard node publish location). +dist/ + +# Other local files. +node_modules/ +unit_tests/modernizr.js +source/environment.inc.ts +**/.idea/**/*.xml +**/*.iml +**/*.kpj.user \ No newline at end of file diff --git a/common/core/web/tools/recorder/package-lock.json b/common/core/web/tools/recorder/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..9dbe6686c05f066392fd83bce9b758b7add875de --- /dev/null +++ b/common/core/web/tools/recorder/package-lock.json @@ -0,0 +1,14 @@ +{ + "name": "@keymanapp/recorder-core", + "version": "14.0.144", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "typescript": { + "version": "3.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.8.3.tgz", + "integrity": "sha512-MYlEfn5VrLNsgudQTVJeNaQFUAI7DkhnOjdpAp4T+ku1TfQClewlbSuTVHiA+8skNBgaf02TL/kLOvig4y3G8w==", + "dev": true + } + } +} diff --git a/common/core/web/tools/recorder/package.json b/common/core/web/tools/recorder/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ef6dcd7a3f9d3099454bdc9a2a430e57ab936063 --- /dev/null +++ b/common/core/web/tools/recorder/package.json @@ -0,0 +1,28 @@ +{ + "name": "@keymanapp/recorder-core", + "version": "14.0.144", + "description": "Core classes used to develop KeymanWeb test cases based on keystrokes", + "main": "index.js", + "scripts": { + "tsc": "tsc" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/keymanapp/keyman.git" + }, + "author": "SIL International", + "license": "MIT", + "bugs": { + "url": "https://github.com/keymanapp/keyman/issues" + }, + "homepage": "https://github.com/keymanapp/keyman#readme", + "dependencies": { + "@keymanapp/keyboard-processor": "^14.0.144", + "@keymanapp/models-types": "^14.0.144", + "@keymanapp/web-environment": "^14.0.144", + "@keymanapp/web-utils": "^14.0.144" + }, + "devDependencies": { + "typescript": "^3.8.3" + } +} diff --git a/common/core/web/tools/recorder/src/build.sh b/common/core/web/tools/recorder/src/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..579bc3c5de01c5b6a0d45a21f7da150b33106609 --- /dev/null +++ b/common/core/web/tools/recorder/src/build.sh @@ -0,0 +1,68 @@ +#! /bin/bash +# +# Compiles development-related KeymanWeb resources for use with developing/running tests. +# - the Recorder module (for engine tests) +# - the DOM module (for touch-alias and element-interface tests) + +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +SCRIPT_DIR="$(dirname "$THIS_SCRIPT")" +KEYMAN_ROOT="$(dirname "$THIS_SCRIPT")/../../../../../.." +. "$KEYMAN_ROOT/resources/build/build-utils.sh" +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +display_usage ( ) { + echo "build.sh [-skip-package-install]" + echo + echo " -skip-package-install skips the `lerna bootstrap` dependency check." + echo " (or -S) Intended for use when this script is called by another build script." + echo "" + echo " If more than one target is specified, the last one will take precedence." + exit 1 +} + +# Establish default build parameters +set_default_vars ( ) { + FETCH_DEPS=true +} + +set_default_vars + +# Parse args +while [[ $# -gt 0 ]] ; do + key="$1" + case $key in + -skip-package-install|-S) + set_default_vars + FETCH_DEPS=false + ;; + esac + shift # past argument +done + +if [ $FETCH_DEPS = true ]; then + verify_npm_setup +fi + +# Definition of global compile constants +OUTPUT_DIR="dist" +OUTPUT="index.js" + +# Ensures that we rely first upon the local npm-based install of Typescript. +# (Facilitates automated setup for build agents.) +PATH="../node_modules/.bin:$PATH" + +compiler="npm run tsc --" +compilecmd="$compiler" + +$compilecmd -p "$SCRIPT_DIR/tsconfig.json" +if [ $? -ne 0 ]; then + fail "KeymanWeb recorder-core compilation failed." +fi + +$compilecmd -p "$SCRIPT_DIR/nodeProctor.tsconfig.json" +if [ $? -ne 0 ]; then + fail "Node-based unit-test Proctor compilation failed." +fi diff --git a/common/core/web/tools/recorder/src/index.ts b/common/core/web/tools/recorder/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..60cf7ad0b1ee3aeda21bf763acae9bc7b3e8496a --- /dev/null +++ b/common/core/web/tools/recorder/src/index.ts @@ -0,0 +1,775 @@ +/// +/// + +namespace KMWRecorder { + //#region Defines the InputEventSpec set, used to reconstruct DOM-based events for browser-based simulation + export abstract class InputEventSpec { + type: "key" | "osk"; + static fromJSONObject(obj: any): InputEventSpec { + if(obj && obj.type) { + if(obj.type == "key") { + return new PhysicalInputEventSpec(obj); + } else if(obj.type == "osk") { + return new OSKInputEventSpec(obj); + } + } else { + throw new SyntaxError("Error in JSON format corresponding to an InputEventSpec!"); + } + } + + toPrettyJSON(): string { + // We want the default, non-spaced JSON for this class, even when otherwise adding whitespace. + var str = JSON.stringify(this); + return str; + } + } + + export class PhysicalInputEventSpec extends InputEventSpec { + static readonly modifierCodes: { [mod:string]: number } = { + "Shift":0x0001, + "Control":0x0002, + "Alt":0x0004, + "Meta":0x0008, + "CapsLock":0x0010, + "NumLock":0x0020, + "ScrollLock":0x0040 + }; + + // KeyboardEvent properties + type: "key" = "key"; + key: string; + code: string; + keyCode: number; + modifierSet: number; + location: number; + + constructor(e?: PhysicalInputEventSpec) { // parameter is used to reconstruct from JSON. + super(); + + if(e) { + this.key = e.key; + this.code = e.code; + this.keyCode = e.keyCode; + this.modifierSet = e.modifierSet; + this.location = e.location; + } + } + + getModifierState(key: string): boolean { + return (PhysicalInputEventSpec.modifierCodes[key] & this.modifierSet) != 0; + } + + generateModifierString(): string { + var list: string = ""; + + for(var key in PhysicalInputEventSpec.modifierCodes) { + if(this.getModifierState(key)) { + list += ((list != "" ? " " : "") + key); + } + } + + return list; + } + } + + export class OSKInputEventSpec extends InputEventSpec { + type: "osk" = "osk"; + keyID: string; + + // The parameter may be used to reconstruct the item from raw JSON. + constructor(e?: OSKInputEventSpec) { + super(); + if(e) { + this.keyID = e.keyID; + } + } + } + //#endregion + + export abstract class RecordedKeystroke { + type: "key" | "osk"; + + static fromJSONObject(obj: any): RecordedKeystroke { + if(obj && obj.type) { + if(obj.type == "key") { + return new RecordedPhysicalKeystroke(obj as RecordedPhysicalKeystroke); + } else if(obj && obj.type) { + return new RecordedSyntheticKeystroke(obj as RecordedSyntheticKeystroke); + } + } else { + throw new SyntaxError("Error in JSON format corresponding to a RecordedKeystroke!"); + } + } + + toPrettyJSON(): string { + // We want the default, non-spaced JSON for this class, even when otherwise adding whitespace. + var str = JSON.stringify(this); + return str; + } + + /** + * Returns an InputEventSpec that may be used to simulate the keystroke within a browser-based environment. + */ + abstract get inputEventSpec(): InputEventSpec; + } + + export class RecordedPhysicalKeystroke extends RecordedKeystroke { + // KeyboardEvent properties + type: "key" = "key"; + + keyCode: number; // may be different from eventSpec's value b/c keymapping + states: number; + modifiers: number; + modifierChanged: boolean; + isVirtualKey: boolean; + vkCode: number; // may be possible to eliminate; differences arise from mnemonics. + + eventSpec: PhysicalInputEventSpec; + + constructor(keystroke: RecordedPhysicalKeystroke) + constructor(keystroke: com.keyman.text.KeyEvent, eventSpec: PhysicalInputEventSpec) + constructor(keystroke: RecordedPhysicalKeystroke|com.keyman.text.KeyEvent, eventSpec?: PhysicalInputEventSpec) { + super(); + + if(keystroke instanceof com.keyman.text.KeyEvent || typeof keystroke.type === 'undefined') { + // Store what is necessary for headless event reconstruction. + keystroke = keystroke as com.keyman.text.KeyEvent; + this.keyCode = keystroke.Lcode; + this.states = keystroke.Lstates; + this.modifiers = keystroke.Lmodifiers; + this.modifierChanged = !!keystroke.LmodifierChange; + this.isVirtualKey = keystroke.LisVirtualKey; + this.vkCode = keystroke.vkCode; + + // Also store the DOM-based event spec for use in integrated testing. + this.eventSpec = eventSpec; + } else { + // It might be a raw object, from JSON. + this.keyCode = keystroke.keyCode; + this.states = keystroke.states; + this.modifiers = keystroke.modifiers; + this.modifierChanged = keystroke.modifierChanged; + this.isVirtualKey = keystroke.isVirtualKey; + this.vkCode = keystroke.vkCode; + + this.eventSpec = new PhysicalInputEventSpec(keystroke.eventSpec); // must also be reconstructed. + } + } + + get inputEventSpec(): InputEventSpec { + return this.eventSpec; + } + } + + export class RecordedSyntheticKeystroke extends RecordedKeystroke { + // KeyboardEvent properties + type: "osk" = "osk"; + + keyName: string; + layer: string; + + keyDistribution?: com.keyman.text.KeyDistribution; + + constructor(keystroke: RecordedSyntheticKeystroke) + constructor(keystroke: com.keyman.text.KeyEvent) + constructor(keystroke: RecordedSyntheticKeystroke|com.keyman.text.KeyEvent) { + super(); + + if(keystroke instanceof com.keyman.text.KeyEvent || typeof keystroke.type === 'undefined') { + keystroke = keystroke as com.keyman.text.KeyEvent; + // Store what is necessary for headless event reconstruction. + + // Also store the DOM-based event spec for use in integrated testing. + this.layer = keystroke.kbdLayer; + this.keyName = keystroke.kName; + this.keyDistribution = keystroke.keyDistribution; + } else { + // It might be a raw object, from JSON. + this.layer = keystroke.layer; + this.keyName = keystroke.keyName; + this.keyDistribution = keystroke.keyDistribution; + } + } + + get inputEventSpec(): InputEventSpec { + let eventSpec = new OSKInputEventSpec(); + eventSpec.keyID = this.layer + '-' + this.keyName; + + return eventSpec; + } + } + + export abstract class TestSequence { + inputs: KeyRecord[]; + output: string; + msg?: string; + + abstract hasOSKInteraction(): boolean; + + test(proctor: Proctor, target?: com.keyman.text.OutputTarget): {success: boolean, result: string} { + // Start with an empty OutputTarget and a fresh KeyboardProcessor. + if(!target) { + target = new com.keyman.text.Mock(); + } + + proctor.before(); + + let result = proctor.simulateSequence(this, target); + proctor.assertEquals(result, this.output, this.msg); + + return {success: (result == this.output), result: result}; + } + + toPrettyJSON(): string { + var str = "{ "; + if(this.output) { + str += "\"output\": \"" + this.output + "\", "; + } + str += "\"inputs\": [\n"; + for(var i = 0; i < this.inputs.length; i++) { + str += " " + this.inputs[i].toPrettyJSON() + ((i == this.inputs.length-1) ? "\n" : ",\n"); + } + if(this.msg) { + str += "], \"message\": \"" + this.msg + "\" }"; + } else { + str += "]}"; + } + return str; + } + } + + export class InputEventSpecSequence extends TestSequence { + inputs: InputEventSpec[]; + output: string; + msg?: string; + + constructor(ins?: InputEventSpec[] | InputEventSpecSequence, outs?: string, msg?: string) { + super(); + + if(ins) { + if(ins instanceof Array) { + this.inputs = [].concat(ins); + } else { + // We're constructing from existing JSON. + this.inputs = []; + + for(var ie=0; ie < ins.inputs.length; ie++) { + this.inputs.push(InputEventSpec.fromJSONObject(ins.inputs[ie])); + } + + this.output = ins.output; + this.msg = ins.msg; + return; + } + } else { + this.inputs = []; + } + + if(outs) { + this.output = outs; + } + + if(msg) { + this.msg = msg; + } + } + + addInput(event: InputEventSpec, output: string) { + this.inputs.push(event); + this.output = output; + } + + hasOSKInteraction(): boolean { + for(var i=0; i < this.inputs.length; i++) { + if(this.inputs[i] instanceof OSKInputEventSpec) { + return true; + } + } + + return false; + } + } + + export class RecordedKeystrokeSequence extends TestSequence { + inputs: RecordedKeystroke[]; + output: string; + msg?: string; + + constructor(ins?: RecordedKeystroke[], outs?: string, msg?: string) + constructor(sequence: RecordedKeystrokeSequence) + constructor(ins?: RecordedKeystroke[] | RecordedKeystrokeSequence, outs?: string, msg?: string) { + super(); + + if(ins) { + if(ins instanceof Array) { + this.inputs = [].concat(ins); + } else { + // We're constructing from existing JSON. + this.inputs = []; + + for(var ie=0; ie < ins.inputs.length; ie++) { + this.inputs.push(RecordedKeystroke.fromJSONObject(ins.inputs[ie])); + } + + this.output = ins.output; + this.msg = ins.msg; + return; + } + } else { + this.inputs = []; + } + + if(outs) { + this.output = outs; + } + + if(msg) { + this.msg = msg; + } + } + + addInput(event: RecordedKeystroke, output: string) { + this.inputs.push(event); + this.output = output; + } + + hasOSKInteraction(): boolean { + for(var i=0; i < this.inputs.length; i++) { + if(this.inputs[i] instanceof RecordedSyntheticKeystroke) { + return true; + } + } + + return false; + } + } + + class FontStubForLanguage { + family: string; + source: string[]; + + constructor(activeStubEntry: any) { + this.family = activeStubEntry.family; + + var src = activeStubEntry.files; + if(!(src instanceof Array)) { + src = [ src ]; + } + + this.source = []; + for(var i=0; i < src.length; i++) { + this.source.push(activeStubEntry.path + src[i]); + } + } + } + + export class LanguageStubForKeyboard { + id: string; + name: string; + region: string; + font?: FontStubForLanguage; + oskFont?: FontStubForLanguage; + + constructor(activeStub: any) { + if(activeStub.KLC) { + this.id = activeStub.KLC; + this.name = activeStub.KL; + this.region = activeStub.KR; + + // Fonts. + if(activeStub.KFont) { + this.font = new FontStubForLanguage(activeStub.KFont); + } + if(activeStub.KOskFont) { + this.oskFont = new FontStubForLanguage(activeStub.KOskFont); + } + } else { + this.id = activeStub.id; + this.name = activeStub.name; + this.region = activeStub.region; + + // If we end up adding functionality to FontStubForLanguage, we'll need to properly reconstruct these. + this.font = activeStub.font; + this.oskFont = activeStub.oskFont; + } + } + } + + export class KeyboardStub { + id: string; + name: string; + filename: string; + languages: LanguageStubForKeyboard | LanguageStubForKeyboard[]; + + // Constructs a stub usable with KeymanWeb's addKeyboards() API function from + // the internally-tracked ActiveStub value for that keyboard. + constructor(json?: KeyboardStub) { + if(json) { + this.id = json.id; + this.name = json.name; + this.filename = json.filename; + + if(!Array.isArray(json.languages)) { + this.languages = new LanguageStubForKeyboard(json.languages); + } else { + this.languages = []; + for(var i=0; i < json.languages.length; i++) { + this.languages.push(new LanguageStubForKeyboard(json.languages[i])); + } + } + } + } + + getFirstLanguage() { + if(this.languages instanceof LanguageStubForKeyboard) { + return this.languages.id; + } else { + return this.languages[0].id; + } + } + } + + type TARGET = 'hardware'|'desktop'|'phone'|'tablet'; + type OS = 'windows'|'android'|'ios'|'macosx'|'linux'; + type BROWSER = 'ie'|'chrome'|'firefox'|'safari'|'opera'; // ! no 'edge' detection in KMW! + + export class Constraint { + target: TARGET; + validOSList?: OS[]; + validBrowsers?: BROWSER[]; + + constructor(target: TARGET|Constraint, validOSList?: OS[], validBrowsers?: BROWSER[]) { + if(typeof(target) == 'string') { + this.target = target; + this.validOSList = validOSList; + this.validBrowsers = validBrowsers; + } else { + var json = target; + this.target = json.target; + this.validOSList = json.validOSList; + this.validBrowsers = json.validBrowsers; + } + } + + matchesClient(device: com.keyman.utils.DeviceSpec, usingOSK?: boolean) { + // #1: Platform check. + if(usingOSK === true) { + if(this.target != device.formFactor) { + return false; + } + } else if(usingOSK === false) { + if(this.target != 'hardware') { + return false; + } + } else if(this.target != device.formFactor && this.target != 'hardware') { + return false; + } + + if(this.validOSList) { + if(this.validOSList.indexOf(device.OS as OS) == -1) { + return false; + } + } + + if(this.validBrowsers) { + if(this.validBrowsers.indexOf(device.browser as BROWSER) == -1) { + return false; + } + } + + return true; + } + + // Checks if another Constraint instance is functionally identical to this one. + equals(other: Constraint) { + if(this.target != other.target) { + return false; + } + + var list1 = this.validOSList ? this.validOSList : ['any']; + var list2 = other.validOSList ? other.validOSList : ['any']; + + if(list1.sort().join(',') != list2.sort().join(',')) { + return false; + } + + list1 = this.validBrowsers ? this.validBrowsers : ['web']; + list2 = other.validBrowsers ? other.validBrowsers : ['web']; + + if(list1.sort().join(',') != list2.sort().join(',')) { + return false; + } + + return true; + } + } + + export class TestFailure { + constraint: Constraint; + test: InputEventSpecSequence; + result: string; + + constructor(constraint: Constraint, test: InputEventSpecSequence, output: string) { + this.constraint = constraint; + this.test = test; + this.result = output; + } + } + + export interface TestSet> { + constraint: Constraint; + + addTest(seq: Sequence): void; + isValidForDevice(device: com.keyman.utils.DeviceSpec, usingOSK?: boolean): boolean; + test(proctor: Proctor): TestFailure[]; + } + + /** + * The core constraint-specific test set definition used for testing versions 10.0 to 13.0. + */ + export class EventSpecTestSet implements TestSet { + constraint: Constraint; + testSet: InputEventSpecSequence[]; + + constructor(constraint: Constraint|EventSpecTestSet) { + if("target" in constraint) { + this.constraint = constraint as Constraint; + this.testSet = []; + } else { + var json = constraint as EventSpecTestSet; + this.constraint = new Constraint(json.constraint); + this.testSet = []; + + // Clone each test sequence / reconstruct from methodless JSON object. + for(var i=0; i < json.testSet.length; i++) { + this.testSet.push(new InputEventSpecSequence(json.testSet[i])); + } + } + } + + addTest(seq: InputEventSpecSequence) { + this.testSet.push(seq); + } + + // Used to determine if the current EventSpecTestSet is applicable to be run on a device. + isValidForDevice(device: com.keyman.utils.DeviceSpec, usingOSK?: boolean) { + return this.constraint.matchesClient(device, usingOSK); + } + + // Validity should be checked before calling this method. + test(proctor: Proctor): TestFailure[] { + var failures: TestFailure[] = []; + let testSet = this.testSet; + + for(var i=0; i < testSet.length; i++) { + var testSeq = this[i]; + var simResult = testSet[i].test(proctor); + if(!simResult.success) { + // Failed test! + failures.push(new TestFailure(this.constraint, testSeq, simResult.result)); + } + } + + return failures.length > 0 ? failures : null; + } + } + + /** + * The core constraint-specific test set definition used for testing versions 10.0 to 13.0. + */ + export class RecordedSequenceTestSet implements TestSet { + constraint: Constraint; + testSet: RecordedKeystrokeSequence[]; + + constructor(constraint: Constraint|RecordedSequenceTestSet) { + if("target" in constraint) { + this.constraint = constraint as Constraint; + this.testSet = []; + } else { + var json = constraint as RecordedSequenceTestSet; + this.constraint = new Constraint(json.constraint); + this.testSet = []; + + // Clone each test sequence / reconstruct from methodless JSON object. + for(var i=0; i < json.testSet.length; i++) { + this.testSet.push(new RecordedKeystrokeSequence(json.testSet[i])); + } + } + } + + addTest(seq: RecordedKeystrokeSequence) { + this.testSet.push(seq); + } + + // Used to determine if the current EventSpecTestSet is applicable to be run on a device. + isValidForDevice(device: com.keyman.utils.DeviceSpec, usingOSK?: boolean) { + return this.constraint.matchesClient(device, usingOSK); + } + + // Validity should be checked before calling this method. + test(proctor: Proctor): TestFailure[] { + var failures: TestFailure[] = []; + let testSet = this.testSet; + + for(var i=0; i < testSet.length; i++) { + var testSeq = this[i]; + var simResult = testSet[i].test(proctor); + if(!simResult.success) { + // Failed test! + failures.push(new TestFailure(this.constraint, testSeq, simResult.result)); + } + } + + return failures.length > 0 ? failures : null; + } + + toTestName(): string { + let name = "constraint: for " + this.constraint.target; + + if(this.constraint.target == 'hardware') { + name += " keyboard"; + } else { + name += " OSK"; + } + if(this.constraint.validOSList) { + name += " on OS of " + JSON.stringify(this.constraint.validOSList); + } + if(this.constraint.validBrowsers) { + name += " in browser of " + JSON.stringify(this.constraint.validBrowsers); + } + + return name; + } + } + + export class KeyboardTest { + /** + * Indicates what version of KMW's recorder the spec conforms to. + */ + public specVersion: com.keyman.utils.Version = KeyboardTest.CURRENT_VERSION; + + /** + * The version of KMW in which the Recorder was first written. Worked from 10.0 to 13.0 with + * only backward-compatible changes and minor tweaks to conform to internal API shifts. + */ + public static readonly FALLBACK_VERSION = new com.keyman.utils.Version("10.0"); + public static readonly CURRENT_VERSION = new com.keyman.utils.Version("14.0"); + + /** + * The stub information to be passed into keyman.addKeyboards() in order to run the test. + */ + keyboard: KeyboardStub; + + /** + * The master array of test sets, each of which specifies constraints a client must fulfill for + * the tests contained therein to be valid. + */ + inputTestSets: TestSet[]; + + /** + * Reconstructs a KeyboardTest object from its JSON representation, restoring its methods. + * @param fromJSON + */ + constructor(fromJSON?: string|KeyboardStub|KeyboardTest) { + if(!fromJSON) { + this.keyboard = null; + this.inputTestSets = []; + return; + } else if(typeof(fromJSON) == 'string') { + fromJSON = JSON.parse(fromJSON) as KeyboardTest; + } else if(fromJSON instanceof KeyboardStub) { + this.keyboard = fromJSON; + this.inputTestSets = []; + return; + } + + if(!fromJSON.specVersion) { + fromJSON.specVersion = KeyboardTest.FALLBACK_VERSION; + } else { + // Is serialized to a String when saved. + fromJSON.specVersion = new com.keyman.utils.Version(fromJSON.specVersion as unknown as string); + } + + this.keyboard = new KeyboardStub(fromJSON.keyboard); + this.inputTestSets = []; + this.specVersion = fromJSON.specVersion; + + if(this.specVersion.equals(KeyboardTest.FALLBACK_VERSION)) { + // Top-level test spec: EventSpecTestSet, based entirely on browser events. + for(var i=0; i < fromJSON.inputTestSets.length; i++) { + this.inputTestSets[i] = new EventSpecTestSet(fromJSON.inputTestSets[i] as EventSpecTestSet); + } + } else { + for(var i=0; i < fromJSON.inputTestSets.length; i++) { + this.inputTestSets[i] = new RecordedSequenceTestSet(fromJSON.inputTestSets[i] as RecordedSequenceTestSet); + } + } + } + + addTest(constraint: Constraint, seq: RecordedKeystrokeSequence) { + if(!this.specVersion.equals(KeyboardTest.CURRENT_VERSION)) { + throw new Error("The currently-loaded test was built to an outdated specification and may not be altered."); + } + + for(var i=0; i < this.inputTestSets.length; i++) { + if(this.inputTestSets[i].constraint.equals(constraint)) { + this.inputTestSets[i].addTest(seq); + return; + } + } + + var newSet = new RecordedSequenceTestSet(new Constraint(constraint)); + this.inputTestSets.push(newSet); + newSet.addTest(seq); + } + + test(proctor: Proctor) { + var setHasRun = false; + var failures: TestFailure[] = []; + + proctor.beforeAll(); + + // The original test spec requires a browser environment and thus requires its own `.run` implementation. + if(!(proctor.compatibleWithSuite(this))) { + throw Error("Cannot perform version " + KeyboardTest.FALLBACK_VERSION + "-based testing outside of browser-based environments."); + } + + // Otherwise, the test spec instances will know how to run in any currently-supported environment. + for(var i = 0; i < this.inputTestSets.length; i++) { + var testSet = this.inputTestSets[i]; + + if(proctor.matchesTestSet(testSet)) { + var testFailures = testSet.test(proctor); + if(testFailures) { + failures = failures.concat(testFailures); + } + setHasRun = true; + } + } + + if(!setHasRun) { + // The sets CAN be empty, allowing silent failure if/when we actually want that. + console.warn("No test sets for this keyboard were applicable for this device!"); + } + + // Allow the method's caller to trigger a 'fail'. + if(failures.length > 0) { + return failures; + } else { + return null; + } + } + + isEmpty() { + return this.inputTestSets.length == 0; + } + + toPrettyJSON() { + return JSON.stringify(this, null, ' '); + } + + get isLegacy(): boolean { + return !this.specVersion.equals(KeyboardTest.CURRENT_VERSION); + } + } +} \ No newline at end of file diff --git a/common/core/web/tools/recorder/src/nodeProctor.ts b/common/core/web/tools/recorder/src/nodeProctor.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce1fcff43b5b75e8aaf0d1cf3d6af75e09711da6 --- /dev/null +++ b/common/core/web/tools/recorder/src/nodeProctor.ts @@ -0,0 +1,98 @@ +/// +/// + +namespace KMWRecorder { + export class NodeProctor extends Proctor { + private keyboard: com.keyman.keyboards.Keyboard; + public __debug = false; + + constructor(keyboard: com.keyman.keyboards.Keyboard, device: com.keyman.utils.DeviceSpec, assert: AssertCallback) { + super(device, assert); + + this.keyboard = keyboard; + } + + beforeAll() { + // + } + + before() { + // + } + + compatibleWithSuite(testSuite: KeyboardTest): boolean { + // Original-version tests did not supply core-compatible KeyEvent data. + return !testSuite.specVersion.equals(KeyboardTest.FALLBACK_VERSION); + } + + get debugMode(): boolean { + return this.__debug; + } + + set debugMode(value: boolean) { + this.__debug = value; + } + + matchesTestSet(testSet: TestSet) { + // KeyboardProcessor is abstract enough to run tests aimed at any platform. + return true; + } + + simulateSequence(sequence: TestSequence, target?: com.keyman.text.OutputTarget): string { + // Start with an empty OutputTarget and a fresh KeyboardProcessor. + if(!target) { + target = new com.keyman.text.Mock(); + } + + // Establish a fresh processor, setting its keyboard appropriately for the test. + let processor = new com.keyman.text.KeyboardProcessor(); + processor.activeKeyboard = this.keyboard; + + if(sequence instanceof RecordedKeystrokeSequence) { + for(let keystroke of sequence.inputs) { + let keyEvent: com.keyman.text.KeyEvent; + if(keystroke instanceof RecordedPhysicalKeystroke) { + // Use the keystroke's stored data to reconstruct the KeyEvent. + keyEvent = { + Lcode: keystroke.keyCode, + Ltarg: target, + Lmodifiers: keystroke.modifiers, + LmodifierChange: keystroke.modifierChanged, + vkCode: keystroke.vkCode, + Lstates: keystroke.states, + kName: '', + device: this.device, + isSynthetic: false, + LisVirtualKey: this.keyboard.definesPositionalOrMnemonic // Only false for 1.0 keyboards. + } + } else if(keystroke instanceof RecordedSyntheticKeystroke) { + let key = this.keyboard.layout(this.device.formFactor).getLayer(keystroke.layer).getKey(keystroke.keyName); + keyEvent = key.constructKeyEvent(processor, target, this.device); + } + + // Fill in the final details of the KeyEvent... + keyEvent.Ltarg = target; + keyEvent.device = this.device; + + // And now, execute the keystroke! + // We don't care too much about particularities of per-keystroke behavior yet. + // ... we _could_ if we wanted to, though. The framework is mostly in place; + // it's a matter of actually adding the feature. + let ruleBehavior = processor.processKeystroke(keyEvent, target); + + if(this.debugMode) { + console.log(JSON.stringify(target, null, ' ')); + console.log(JSON.stringify(ruleBehavior, null, ' ')); + } + } + } else { + throw new Error("NodeProctor only supports RecordedKeystrokeSequences for testing at present."); + } + return target.getText(); + } + + } +} + +// Export the namespace itself, giving access to all contained classes. +module.exports = KMWRecorder; \ No newline at end of file diff --git a/common/core/web/tools/recorder/src/nodeProctor.tsconfig.json b/common/core/web/tools/recorder/src/nodeProctor.tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d13317335d33dbc8c9512041eb44fc4acbcabf9f --- /dev/null +++ b/common/core/web/tools/recorder/src/nodeProctor.tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "allowJs": true, + "module": "none", + "outDir": "../dist/", + "inlineSources": true, + "inlineSourceMap": true, + "target": "es5", + "types": ["node"], + "lib": ["es6"], + "outFile": "../dist/nodeProctor.js" + }, + "files": [ + "../node_modules/@keymanapp/models-types/index.d.ts", + "../node_modules/@keymanapp/web-environment/environment.inc.ts", + "../node_modules/@keymanapp/web-utils/src/index.ts", + "nodeProctor.ts" + ] +} diff --git a/common/core/web/tools/recorder/src/proctor.ts b/common/core/web/tools/recorder/src/proctor.ts new file mode 100644 index 0000000000000000000000000000000000000000..38ffd9997aa295993c7ef79d93af285a97beb1e3 --- /dev/null +++ b/common/core/web/tools/recorder/src/proctor.ts @@ -0,0 +1,50 @@ +namespace KMWRecorder { + export type AssertCallback = (s1: any, s2: any, msg?: string) => void; + + /** + * Facilitates running Recorder-generated tests on various platforms. + * + * Note that DOM-aware KeymanWeb will implement a Browser-based version, while + * keyboard-processor and input-processor will use a Node-based version instead. + */ + export abstract class Proctor { + device: com.keyman.utils.DeviceSpec; + + _assert: AssertCallback; + + constructor(device: com.keyman.utils.DeviceSpec, assert: AssertCallback) { + this.device = device; + + this._assert = assert; + } + + assertEquals(s1: unknown, s2: unknown, msg?: string) { + if(this._assert) { + this._assert(s1, s2, msg); + } + } + + // Performs global test prep. + abstract beforeAll(); + + // Performs per-test setup + abstract before(); + + /** + * Allows the proctor to indicate if is capable of executing a suite of tests or not. + * @param testSuite + */ + abstract compatibleWithSuite(testSuite: KeyboardTest): boolean; + + /** + * Indicates whether or not this Proctor is capable of running the specified set of tests. + */ + abstract matchesTestSet(testSet: TestSet); + + /** + * Simulates the specified test sequence for use in testing. + * @param sequence The recorded sequence, generally provided by a test set. + */ + abstract simulateSequence(sequence: TestSequence, target?: com.keyman.text.OutputTarget); + } +} \ No newline at end of file diff --git a/common/core/web/tools/recorder/src/tsconfig.json b/common/core/web/tools/recorder/src/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..6a1816e05225a6dd3a9d52942d711073354fa6b9 --- /dev/null +++ b/common/core/web/tools/recorder/src/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "allowJs": true, + "module": "none", + "outDir": "../dist/", + "inlineSources": true, + "inlineSourceMap": true, + "target": "es5", + "types": ["node"], + "lib": ["es6"], + "outFile": "../dist/index.js" + }, + "files": [ + "../node_modules/@keymanapp/models-types/index.d.ts", + "../node_modules/@keymanapp/web-environment/environment.inc.ts", + "../node_modules/@keymanapp/web-utils/src/index.ts", + "index.ts" + ] +} diff --git a/common/core/web/tools/sentry-manager/.gitignore b/common/core/web/tools/sentry-manager/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a5025863e33226d526f162068e56e3a63d0895ad --- /dev/null +++ b/common/core/web/tools/sentry-manager/.gitignore @@ -0,0 +1,17 @@ +# Build products +src/environment.inc.ts + +# Legacy build folders. +output/ +build/ +embedded/ + +# Current build output folder (matches standard node publish location). +dist/ + +# Other local files. +node_modules/ +unit_tests/modernizr.js +**/.idea/**/*.xml +**/*.iml +**/*.kpj.user \ No newline at end of file diff --git a/common/core/web/tools/sentry-manager/package-lock.json b/common/core/web/tools/sentry-manager/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..ba1feeed5545254ccc296ff3062978fa688a89d2 --- /dev/null +++ b/common/core/web/tools/sentry-manager/package-lock.json @@ -0,0 +1,70 @@ +{ + "name": "@keymanapp/web-sentry-manager", + "version": "14.0.144", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@sentry/browser": { + "version": "5.15.5", + "resolved": "https://registry.npmjs.org/@sentry/browser/-/browser-5.15.5.tgz", + "integrity": "sha512-rqDvjk/EvogfdbZ4TiEpxM/lwpPKmq23z9YKEO4q81+1SwJNua53H60dOk9HpRU8nOJ1g84TMKT2Ov8H7sqDWA==", + "requires": { + "@sentry/core": "5.15.5", + "@sentry/types": "5.15.5", + "@sentry/utils": "5.15.5", + "tslib": "^1.9.3" + } + }, + "@sentry/core": { + "version": "5.15.5", + "resolved": "https://registry.npmjs.org/@sentry/core/-/core-5.15.5.tgz", + "integrity": "sha512-enxBLv5eibBMqcWyr+vApqeix8uqkfn0iGsD3piKvoMXCgKsrfMwlb/qo9Ox0lKr71qIlZVt+9/A2vZohdgnlg==", + "requires": { + "@sentry/hub": "5.15.5", + "@sentry/minimal": "5.15.5", + "@sentry/types": "5.15.5", + "@sentry/utils": "5.15.5", + "tslib": "^1.9.3" + } + }, + "@sentry/hub": { + "version": "5.15.5", + "resolved": "https://registry.npmjs.org/@sentry/hub/-/hub-5.15.5.tgz", + "integrity": "sha512-zX9o49PcNIVMA4BZHe//GkbQ4Jx+nVofqU/Il32/IbwKhcpPlhGX3c1sOVQo4uag3cqd/JuQsk+DML9TKkN0Lw==", + "requires": { + "@sentry/types": "5.15.5", + "@sentry/utils": "5.15.5", + "tslib": "^1.9.3" + } + }, + "@sentry/minimal": { + "version": "5.15.5", + "resolved": "https://registry.npmjs.org/@sentry/minimal/-/minimal-5.15.5.tgz", + "integrity": "sha512-zQkkJ1l9AjmU/Us5IrOTzu7bic4sTPKCatptXvLSTfyKW7N6K9MPIIFeSpZf9o1yM2sRYdK7GV08wS2eCT3JYw==", + "requires": { + "@sentry/hub": "5.15.5", + "@sentry/types": "5.15.5", + "tslib": "^1.9.3" + } + }, + "@sentry/types": { + "version": "5.15.5", + "resolved": "https://registry.npmjs.org/@sentry/types/-/types-5.15.5.tgz", + "integrity": "sha512-F9A5W7ucgQLJUG4LXw1ZIy4iLevrYZzbeZ7GJ09aMlmXH9PqGThm1t5LSZlVpZvUfQ2rYA8NU6BdKJSt7B5LPw==" + }, + "@sentry/utils": { + "version": "5.15.5", + "resolved": "https://registry.npmjs.org/@sentry/utils/-/utils-5.15.5.tgz", + "integrity": "sha512-Nl9gl/MGnzSkuKeo3QaefoD/OJrFLB8HmwQ7HUbTXb6E7yyEzNKAQMHXGkwNAjbdYyYbd42iABP6Y5F/h39NtA==", + "requires": { + "@sentry/types": "5.15.5", + "tslib": "^1.9.3" + } + }, + "tslib": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", + "integrity": "sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA==" + } + } +} diff --git a/common/core/web/tools/sentry-manager/package.json b/common/core/web/tools/sentry-manager/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b4eef7d15e6d74c4559738ebb1c97c4633f588cb --- /dev/null +++ b/common/core/web/tools/sentry-manager/package.json @@ -0,0 +1,26 @@ +{ + "name": "@keymanapp/web-sentry-manager", + "version": "14.0.144", + "description": "Common setup for KeymanWeb's Sentry-based error reporting", + "main": "dist/index.js", + "scripts": { + "tsc": "tsc" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/keymanapp/keyman.git" + }, + "author": "SIL International", + "license": "MIT", + "bugs": { + "url": "https://github.com/keymanapp/keyman/issues" + }, + "homepage": "https://github.com/keymanapp/keyman#readme", + "devDependencies": { + "typescript": "^3.8.3" + }, + "dependencies": { + "@keymanapp/web-environment": "^14.0.144", + "@sentry/browser": "^5.15.5" + } +} diff --git a/common/core/web/tools/sentry-manager/src/build.sh b/common/core/web/tools/sentry-manager/src/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..18a7a6696cbc915da514b9d0dae30114672fcda9 --- /dev/null +++ b/common/core/web/tools/sentry-manager/src/build.sh @@ -0,0 +1,63 @@ +#! /bin/bash +# +# Compiles development-related KeymanWeb resources for use with developing/running tests. +# - the Recorder module (for engine tests) +# - the DOM module (for touch-alias and element-interface tests) + +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../../../../../resources/build/build-utils.sh" +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +SCRIPT_DIR="$(dirname "$THIS_SCRIPT")" + +display_usage ( ) { + echo "build.sh [-skip-package-install]" + echo + echo " -skip-package-install skips the `lerna bootstrap` dependency check." + echo " (or -S) Intended for use when this script is called by another build script." + echo "" + echo " If more than one target is specified, the last one will take precedence." + exit 1 +} + +# Establish default build parameters +set_default_vars ( ) { + FETCH_DEPS=true +} + +set_default_vars + +# Parse args +while [[ $# -gt 0 ]] ; do + key="$1" + case $key in + -skip-package-install|-S) + set_default_vars + FETCH_DEPS=false + ;; + esac + shift # past argument +done + +if [ $FETCH_DEPS = true ]; then + verify_npm_setup +fi + +# Definition of global compile constants +OUTPUT_DIR="dist" +OUTPUT="index.js" + +# Ensures that we rely first upon the local npm-based install of Typescript. +# (Facilitates automated setup for build agents.) +PATH="../node_modules/.bin:$PATH" + +compiler="npm run tsc --" +compilecmd="$compiler" + +$compilecmd -p "$SCRIPT_DIR/tsconfig.json" +if [ $? -ne 0 ]; then + fail "Compilation of package for Sentry integration with KeymanWeb failed." +fi \ No newline at end of file diff --git a/common/core/web/tools/sentry-manager/src/index.ts b/common/core/web/tools/sentry-manager/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf86a5db74e9b27735b83a8b67219d516b15f32d --- /dev/null +++ b/common/core/web/tools/sentry-manager/src/index.ts @@ -0,0 +1,156 @@ +/// + +namespace com.keyman { + /** + * Controls whether or not the generated Sentry event is logged to the console (true) + * or sent to our Sentry server (false). + */ + let DEBUG = false; + + type Options = { + hostPlatform: "native-web" | "ios" | "android" + }; + + export class KeymanSentryManager { + keymanPlatform: string; + + static STANDARD_ALIASABLE_FILES = { + 'keymanweb.js': 'keymanweb.js', + 'keymanios.js': 'keyman.js', // iOS's embedded name -> embedded compilation + 'kmwuibutton.js': 'kmwuibutton.js', + 'kmwuifloat.js': 'kmwuifloat.js', + 'kmwuitoggle.js': 'kmwuitoggle.js', + 'kmwuitoolbar.js': 'kmwuitoolbar.js' + // Also add entries for the naming system used by Android and iOS - and map them to the EMBEDDED upload, not the std 'native' one. + } + + static DEFAULT_OPTIONS: Options = { + hostPlatform: "native-web" + } + + constructor(options: Options = KeymanSentryManager.DEFAULT_OPTIONS) { + this.keymanPlatform = options.hostPlatform; + } + + // If we've recognized one of our source files, + aliasFilename(filename: string): string|null { + if(!this.mayAlias(filename)) { + return null; + } + + filename = KeymanSentryManager.STANDARD_ALIASABLE_FILES[filename]; + + switch(location.protocol) { + case 'http:': + return 'http://' + location.host + '/' + filename; + case 'file:': + return 'file:///' + filename; + default: + return null; + } + } + + mayAlias(filename: string): boolean { + return !!KeymanSentryManager.STANDARD_ALIASABLE_FILES[filename]; + } + + // Filters all expected but unnecessary path prefixes, affixes, and suffixes reported by Sentry from our products. + // This allows us to mask all different sorts of installations with a single uploaded path. + // Modifies original object. + pathFilter(event: any) { + // Get the underlying JS error. + let exception = event.exception; + + // Iterate through all wrapped exceptions. + for(let e of exception.values) { + // If Sentry was unable to generate a stacktrace, there's no path filtering to + // perform on its stack frames. + if(!e.stacktrace) { + continue; + } + + for(let frame of e.stacktrace.frames) { + let URL = frame.filename as string; + let filename: string = ''; + try { + filename = URL.substr(URL.lastIndexOf('/')+1); + if(this.mayAlias(filename)) { + // Make the file look like it's at the host's root so that the Sentry server will recognize it + // regardless of actual filepath position. + frame.filename = this.aliasFilename(filename) || frame.filename; + } + } catch { + // not sure what to do yet, but... don't make more errors in the error handler. That's a bad idea. + } + } + } + } + + // Attaches some useful debugging information to the specified object, pass-by-reference style. + attachEventMetadata(event: any) { + // Ensure that the 'extra' object exists. (May not exist for synthetic/custom Errors.) + event.extra = event.extra || {}; + event.extra.keymanState = window['keyman']['getDebugInfo'](); + event.extra.keymanHostPlatform = this.keymanPlatform; + } + + /** + * Pre-processes a Sentry event object (in-place) to provide more metadata and enhance + * the Sentry server's ability to match the error against release artifacts. + * @param event A Sentry-generated event + */ + prepareEvent(event: any): boolean { + this.pathFilter(event); + this.attachEventMetadata(event); + + if(DEBUG) { + console.log("DEBUG: event object for Sentry") + console.log(event); + return false; //event + } else { + return true; + } + } + + /** + * Allows debugging our custom event preparation code without bombarding Sentry with errors + * during development. + * + * Note that Sentry expects us either to return the event object to be sent or to return `null` + * if we want to prevent the event from being sent to the server. + * @param event + */ + prepareEventDebugWrapper(event: any) { + if(DEBUG) { + try { + if(this.prepareEvent(event)) { + return event; + } else { + return null; + } + } catch(err) { + console.log(err); + } + } else { + // If not in DEBUG mode, simply forward to the actual preparer; we should be notified + // of any event-prep errors that may occur. + if(this.prepareEvent(event)) { + return event; + } else { + return null; + } + } + } + + init() { + // Do the actual Sentry initialization. + //@ts-ignore + Sentry.init({ + beforeSend: this.prepareEventDebugWrapper.bind(this), + debug: DEBUG, + dsn: 'https://cf96f32d107c4286ab2fd82af49c4d3b@sentry.keyman.com/11', // keyman-web DSN + release: com.keyman.environment.SENTRY_RELEASE + }); + } + } +} \ No newline at end of file diff --git a/common/core/web/tools/sentry-manager/src/tsconfig.json b/common/core/web/tools/sentry-manager/src/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..7a552cecca1020b6d42e63a09e1ea2b8acb2d4a6 --- /dev/null +++ b/common/core/web/tools/sentry-manager/src/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "allowJs": true, + "module": "none", + "outDir": "../dist/", + "inlineSources": true, + "sourceMap": true, + "target": "es5", + "lib": ["es6", "dom"], + "outFile": "../dist/index.js" + }, + "files": [ + "../node_modules/@keymanapp/web-environment/environment.inc.ts", + "index.ts" + ] +} \ No newline at end of file diff --git a/common/core/web/utils/.gitignore b/common/core/web/utils/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a9e0c255148b412ebdd55ddba4bc67f7322f814f --- /dev/null +++ b/common/core/web/utils/.gitignore @@ -0,0 +1,18 @@ +# Build products +src/environment.inc.ts + +# Legacy build folders. +output/ +build/ +embedded/ + +# Current build output folder (matches standard node publish location). +dist/ + +# Other local files. +node_modules/ +unit_tests/modernizr.js +source/environment.inc.ts +**/.idea/**/*.xml +**/*.iml +**/*.kpj.user \ No newline at end of file diff --git a/common/core/web/utils/build.sh b/common/core/web/utils/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..c7c5b36e2c7937295c8be7d63c67b2caed2b445b --- /dev/null +++ b/common/core/web/utils/build.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# +# Compiles common TS-based utility functions for use among Keyman's codebase + +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +SCRIPT_DIR="$(dirname "$THIS_SCRIPT")" +KEYMAN_ROOT="$(dirname "$THIS_SCRIPT")/../../../.." +. "$KEYMAN_ROOT/resources/build/build-utils.sh" +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +## END STANDARD BUILD SCRIPT INCLUDE + +display_usage ( ) { + echo "build.sh [-skip-package-install]" + echo + echo " -skip-package-install skips the \`lerna bootstrap\` dependency check." + echo " (or -S) Intended for use when this script is called by another build script." + echo "" + echo " If more than one target is specified, the last one will take precedence." + exit 1 +} + +# Establish default build parameters +set_default_vars ( ) { + FETCH_DEPS=true +} + +set_default_vars + +# Parse args +while [[ $# -gt 0 ]] ; do + key="$1" + case $key in + -skip-package-install|-S) + FETCH_DEPS=false + ;; + esac + shift # past argument +done + +if [ "$FETCH_DEPS" = true ]; then + verify_npm_setup +fi + +# Definition of global compile constants +OUTPUT_DIR="dist" +OUTPUT="index.js" + +# Ensures that we rely first upon the local npm-based install of Typescript. +# (Facilitates automated setup for build agents.) +PATH="../node_modules/.bin:$PATH" + +compiler="npm run tsc --" +compilecmd="$compiler" + +$compilecmd -p "$SCRIPT_DIR/tsconfig.json" +if [ $? -ne 0 ]; then + fail "Utility-function package compilation failed." +fi diff --git a/common/core/web/utils/package-lock.json b/common/core/web/utils/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..749d6518962b4f6bc03e6caee498b2602edfeb31 --- /dev/null +++ b/common/core/web/utils/package-lock.json @@ -0,0 +1,14 @@ +{ + "name": "@keymanapp/web-utils", + "version": "14.0.144", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/node": { + "version": "14.0.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.5.tgz", + "integrity": "sha512-90hiq6/VqtQgX8Sp0EzeIsv3r+ellbGj4URKj5j30tLlZvRUpnAe9YbYnjl3pJM93GyXU0tghHhvXHq+5rnCKA==", + "dev": true + } + } +} diff --git a/common/core/web/utils/package.json b/common/core/web/utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7b9cd162c92c6ea1f1b441cb7ddb98a7d22539ba --- /dev/null +++ b/common/core/web/utils/package.json @@ -0,0 +1,28 @@ +{ + "name": "@keymanapp/web-utils", + "version": "14.0.144", + "description": "Common utility functions used throughout other Keyman packages", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "scripts": { + "build": "gosh ./build.sh", + "prepare": "npm run build -- -skip-package-install", + "tsc": "tsc" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/keymanapp/keyman.git" + }, + "author": "SIL International", + "license": "MIT", + "bugs": { + "url": "https://github.com/keymanapp/keyman/issues" + }, + "homepage": "https://github.com/keymanapp/keyman#readme", + "devDependencies": { + "@keymanapp/resources-gosh": "^14.0.144", + "@keymanapp/web-environment": "^14.0.144", + "@types/node": "^14.0.5", + "typescript": "^3.8.3" + } +} diff --git a/web/source/utils/deepCopy.ts b/common/core/web/utils/src/deepCopy.ts similarity index 100% rename from web/source/utils/deepCopy.ts rename to common/core/web/utils/src/deepCopy.ts diff --git a/web/source/text/engineDeviceSpec.ts b/common/core/web/utils/src/deviceSpec.ts similarity index 97% rename from web/source/text/engineDeviceSpec.ts rename to common/core/web/utils/src/deviceSpec.ts index c14a8d1b6682ea1b6cd540453ed5015f82c0055d..7e2932e471232b9882a6a919e88eade829b5eb01 100644 --- a/web/source/text/engineDeviceSpec.ts +++ b/common/core/web/utils/src/deviceSpec.ts @@ -1,4 +1,4 @@ -namespace com.keyman.text { +namespace com.keyman.utils { export enum Browser { Chrome = 'chrome', Edge = 'edge', @@ -29,7 +29,7 @@ namespace com.keyman.text { * containing only the information needed by web-core for text processing use, devoid * of any direct references to the DOM. */ - export class EngineDeviceSpec { + export class DeviceSpec { readonly browser: Browser; readonly formFactor: FormFactor; readonly OS: OperatingSystem; diff --git a/web/source/utils/globalObject.ts b/common/core/web/utils/src/globalObject.ts similarity index 100% rename from web/source/utils/globalObject.ts rename to common/core/web/utils/src/globalObject.ts diff --git a/common/core/web/utils/src/index.ts b/common/core/web/utils/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d7a2e7773ed44839e31701c4856b33171cb3ba9 --- /dev/null +++ b/common/core/web/utils/src/index.ts @@ -0,0 +1,6 @@ +// References all utility includes from a single file, making import/export simple. +/// +/// +/// +/// +/// \ No newline at end of file diff --git a/web/source/text/kmwstring.ts b/common/core/web/utils/src/kmwstring.ts similarity index 98% rename from web/source/text/kmwstring.ts rename to common/core/web/utils/src/kmwstring.ts index 5bb636fd1558ab5fb144b89dae70107d4baae3f1..397b9041a5434f8ba1cdd01989231f8b75f32e18 100644 --- a/web/source/text/kmwstring.ts +++ b/common/core/web/utils/src/kmwstring.ts @@ -1,8 +1,12 @@ /*** - KeymanWeb 11.0 - Copyright 2019 SIL International + KeymanWeb 14.0 + Copyright 2020 SIL International ***/ +/* + * TODO: Remove this file as part of addressing https://github.com/keymanapp/keyman/issues/2492. + */ + interface StringConstructor { kmwFromCharCode(cp0: number): string, _kmwFromCharCode(cp0: number): string, diff --git a/web/source/utils/version.ts b/common/core/web/utils/src/version.ts similarity index 96% rename from web/source/utils/version.ts rename to common/core/web/utils/src/version.ts index daa288f280f0fc7d2bbcfbd5dba8992ae95277ef..1778607b38f17e96008891c468b4b61d59546af5 100644 --- a/web/source/utils/version.ts +++ b/common/core/web/utils/src/version.ts @@ -1,6 +1,3 @@ -// Defines build-environment variables, as used for versioning. -/// - // Ensure that this class contains no reference into core KMW code - it is referenced // by components intended to be modular and possible to separate from core KMW. @@ -75,6 +72,10 @@ namespace com.keyman.utils { return this.components.join('.'); } + toJSON(): string { + return this.toString(); + } + equals(other: Version): boolean { return this.compareTo(other) == 0; } diff --git a/common/core/web/utils/tsconfig.json b/common/core/web/utils/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..66ad6ecf2f5a45f8600a8b2f42c2733e2b6480c5 --- /dev/null +++ b/common/core/web/utils/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "allowJs": true, + "module": "none", + "inlineSources": true, + "sourceMap": true, + "declaration": true, + "target": "es5", + "types": ["node"], + "lib": ["es6"], + "outFile": "dist/index.js" + }, + "include": [ + "node_modules/@keymanapp/web-environment/environment.inc.ts", + "src/**/*.ts" + ] +} diff --git a/common/lexical-model-types/README.md b/common/lexical-model-types/README.md index 9cc33de3ba9636448d32444d3a30375c1dd546f3..3d6bf6200952ab1af7f2afe5b34215015ee84dc7 100644 --- a/common/lexical-model-types/README.md +++ b/common/lexical-model-types/README.md @@ -1,69 +1,5 @@ -Lexical Model Types -=================== +# `@keymanapp/lexical-model-types` -Declares TypeScript types and interfaces required to define **Lexical -Models**, **Word breaking functions**, and all things in between. +> **MOVED** Please use [`@keymanapp/models-types`][0] instead! -Install -------- - -> (see below if you are working in the keymanapp/keyman repo!) - - npm install --save-dev @keymanapp/lexical-model-types - -Usage ------ - -Say you are creating a **custom lexical model**. Then import this module -in your lexical model file! - -```Typescript -// my-nifty-model.ts - -import "@keymanapp/lexical-model-types"; - -export class MyNiftyClass implements LexicalModel { - configure(capabilities: Capabilities): Configuration { - // TODO: implement me! - throw new Error("Method not implemented."); - } - predict(transform: Transform, context: Context): ProbabilityMass[] { - // TODO: implement me! - throw new Error("Method not implemented."); - } - wordbreak(context: Context): string { - // TODO: implement me! - throw new Error("Method not implemented."); - } - punctuation?: LexicalModelPunctuation; -} -``` - -If your are creating a **custom word breaker**, you would do the same: - -```typescript -import "@keymanapp/lexical-model-types"; - -export let myShinyWordBreaker: WordBreakingFunction; -myShinyWordBreaker = function (phrase: string): Span[] { - // TODO: implement me! - throw new Error("Function not implemented") -} -``` - -Look at [index.d.ts](./index.d.ts) for documentation on each and every -type! - - -Usage within keymanapp/keyman repo ----------------------------------- - -To use it in other subprojects within keymanapp/keyman, ensure that this -package is linked using: - - npm link . - -The following subprojects already perform `npm link .` as part of their `build.sh`: - - common/predictive-text/ - developer/js/ +[0]: https://www.npmjs.com/package/@keymanapp/models-types diff --git a/common/lexical-model-types/index.d.ts b/common/lexical-model-types/index.d.ts index d2f44e6ac300cc7c35d687a8a6c3bedf48a87b8b..7999ed9501474919597565d8f101e00928b0c7a4 100644 --- a/common/lexical-model-types/index.d.ts +++ b/common/lexical-model-types/index.d.ts @@ -1,371 +1,2 @@ -/** - * TypeScript interfaces and types required in both within the LMLayer, and for - * tools that create lexical models. - */ - -/****************************** Lexical Models ******************************/ - -/** - * A JavaScript string with the restriction that it must only - * contain Unicode scalar values. - * - * This means that any lone high surrogate must be paired with - * a low surrogate, if it exists. Lone surrogate code units are - * forbidden. - * - * See also: https://developer.mozilla.org/en-US/docs/Web/API/USVString - */ -declare type USVString = string; - -/** - * The model implementation, within the Worker. - */ -declare interface LexicalModel { - /** - * Processes `config` messages, configuring the newly-loaded model based on the host - * platform's capability restrictions. - * - * This allows the model to configure its suggestions according to what the platform - * allows the host to actually perform - for example, if post-caret deletions are not - * supported, no suggestions requiring this feature should be produced by the model. - * - * Returns a `Configuration` object detailing the capabilities the model plans to - * actually utilize, which must be as restrictive or more restrictive than those - * indicated within the provided `Capabilities` object. - * @param capabilities - */ - configure(capabilities: Capabilities): Configuration; - - /** - * Generates predictive suggestions corresponding to the state of context after the proposed - * transform is applied to it. This transform may correspond to a 'correction' of a recent - * keystroke rather than one actually received. - * - * This method should NOT attempt to perform any form of correction; this is modeled within a - * separate component of the LMLayer predictive engine. That is, "th" + "e" should not be - * have "this" for a suggestion ("e" has been 'corrected' to "i"), while "there" would be - * a reasonable prediction. - * - * However, addition of diacritics to characters (which may transform the underlying char code - * when Unicode-normalized) is permitted. For example, "pur" + "e" may reasonably predict - * "purée", where "e" has been transformed to "é" as part of the suggestion. - * - * When both prediction and correction are permitted, said component (the `ModelCompositor`) will - * generally call this method once per 'likely' generated corrected state of the context, - * utilizing the results to compute an overall likelihood across all possible suggestions. - * @param transform A Transform corresponding to a recent input keystroke - * @param context A depiction of the context to which `transform` is applied. - * @returns A probability distribution (`Distribution`) on the resulting `Suggestion` - * space for use in determining the most optimal overall suggestions. - */ - predict(transform: Transform, context: Context): Distribution; - - /** - * Performs a wordbreak operation given the current context state, returning whatever word - * or word fragment exists that starts before the caret but after the most recent whitespace - * preceding the caret. If no such text exists, the empty string is returned. - * - * This function is designed for use in generating display text for 'keep' `Suggestions` - * and display text for reverting any previously-applied `Suggestions`. - * @param context - */ - wordbreak(context: Context): USVString; - - /** - * Punctuation and presentational settings that the underlying lexical model - * expects to be applied at higher levels. e.g., the ModelCompositor. - * - * @see LexicalModelPunctuation - */ - readonly punctuation?: LexicalModelPunctuation; -} - -/** - * Describes how to change a buffer at the cursor position. - * first, you delete the specified amount amount from the left - * and right, then you insert the provided text. - */ -declare interface Transform { - /** - * Facilitates use of unique identifiers for tracking the Transform and - * any related data from its original source, as the reference cannot be - * preserved across WebWorker boundaries. - * - * This is *separate* from any LMLayer-internal identification values. - */ - id?: number; - - /** - * The Unicode scalar values (i.e., characters) to be inserted at the - * cursor position. - * - * Corresponds to `s` in com.keyman.KeyboardInterface.output. - */ - insert: USVString; - - /** - * The number of code units to delete to the left of the cursor. - * - * Corresponds to `dn` in com.keyman.KeyboardInterface.output. - */ - deleteLeft: number; - - /** - * The number of code units to delete to the right of the cursor. - * Not available on all platforms. - */ - deleteRight?: number; -} - -/** - * A concrete suggestion - */ -declare interface Suggestion { - /** - * Indicates the externally-supplied id of the Transform that prompted - * the Suggestion. Automatically handled by the LMLayer; models should - * not handle this field. - */ - transformId?: number; - - /** - * The suggested update to the buffer. Note that this transform should - * be applied AFTER the instigating transform, if any. - */ - readonly transform: Transform; - - /** - * A string to display the suggestion to the typist. - * This should aid the typist understand what the transform - * will do to their text. - * - * When suggesting a word, `displayAs` should be that entire word. - */ - displayAs: string; - - /** - * A single metalabel data describing the relation of the suggestion - * to the input text. Ex: 'keep', 'emoji', 'correction', etc. - */ - tag?: SuggestionTag; -} - -/** - * A tag indicating the nature of the current suggestion. - * - * Tags include: - * * 'keep' -- suggest the word as what was typed in the first place. - * This tends to be presented as the leftmost suggestion. - * @see LexicalModelPunctuation.quotesForKeepSuggestion - * * 'correction' -- this suggests a correction to the current phrase - * * 'emoji' -- replaces whatever is typed in with an appropriate emoji. - * This tends to be presented as the rightmost suggestion. - * - * If left undefined, the consumers will assume this is a prediction. - */ -type SuggestionTag = undefined | 'keep' | 'correction' | 'emoji'; - - -/** - * The text and environment surrounding the insertion point (text cursor). - */ -declare interface Context { - /** - * Up to maxLeftContextCodeUnits code units of Unicode scalar value - * (i. e., characters) to the left of the insertion point in the - * buffer. If there is nothing to the left of the buffer, this is - * an empty string. - */ - readonly left: USVString; - - /** - * Up to maxRightContextCodeUnits code units of Unicode scalar value - * (i. e., characters) to the right of the insertion point in the - * buffer. If there is nothing to the right of the buffer, this is - * an empty string. - * - * This property may be missing entirely. - */ - readonly right?: USVString; - - /** - * Whether the insertion point is at the start of the buffer. - */ - readonly startOfBuffer: boolean; - - /** - * Whether the insertion point is at the end of the buffer. - */ - readonly endOfBuffer: boolean; -} - -/** - * Represents members of a probability distribution over potential outputs - * from ambiguous text sequences. Designed for use with fat-finger correction - * and similar typing ambiguities. - */ -interface ProbabilityMass { - /** - * An individual sample from a Distribution over the same type. - */ - readonly sample: T; - - /** - * The probability mass for this member of the distribution, - * calculated devoid of any language-modeling influences. - */ - p: number; -} - -declare type Distribution = ProbabilityMass[]; - - -/******************************** Messaging ********************************/ - -/** - * Describes the capabilities of the keyboard's platform. - * This includes upper bounds for how much text will be sent on each - * prediction, as well as what operations the keyboard is allowed to do on the - * underlying buffer. - */ -declare interface Capabilities { - /** - * The maximum amount of UTF-16 code points that the keyboard will provide to - * the left of the cursor, as an integer. - */ - readonly maxLeftContextCodePoints: number, - - /** - * The maximum amount of code points that the keyboard will provide to the - * right of the cursor, as an integer. The value 0 or the absence of this - * rule implies that the right contexts are not supported. - */ - readonly maxRightContextCodePoints?: number, - - /** - * Whether the platform supports deleting to the right. The absence of this - * rule implies false. - */ - readonly supportsDeleteRight?: false, -} - -/** - * Configuration of the LMLayer, sent back to the keyboard. - */ -declare interface Configuration { - /** - * How many UTF-16 code units maximum to send as the context to the - * left of the cursor ("left" in the Unicode character stream). - * - * Affects the `context` property sent in `predict` messages. - * - * While the left context MUST NOT bisect surrogate pairs, they MAY - * bisect graphical clusters. - */ - leftContextCodePoints: number; - /** deprecated; use `leftContextCodePoints` instead! */ - leftContextCodeUnits?: number, - - /** - * How many UTF-16 code units maximum to send as the context to the - * right of the cursor ("right" in the Unicode character stream). - * - * Affects the `context` property sent in `predict` messages. - * - * While the right context MUST NOT bisect surrogate pairs, they MAY - * bisect graphical clusters. - */ - rightContextCodePoints: number; - /** deprecated; use `leftContextCodePoints` instead! */ - rightContextCodeUnits?: number, -} - - -/****************************** Word breaking ******************************/ - -/** - * A simple word breaking function takes a phrase, and splits it into "words", - * for whatever definition of "word" is usable for the language model. - * - * For example: - * - * getText(breakWordsEnglish("Hello, world!")) == ["Hello", "world"] - * getText(breakWordsCree("ᑕᐻ ᒥᔪ ᑮᓯᑲᐤ ᐊᓄᐦᐨ᙮")) == ["ᑕᐻ", "ᒥᔪ ᑮᓯᑲᐤ""", "ᐊᓄᐦᐨ"] - * getText(breakWordsJapanese("英語を話せますか?")) == ["英語", "を", "話せます", "か"] - * - * Not all language models take in a configurable word breaking function. - * - * @returns an array of spans from the phrase, in order as they appear in the - * phrase, each span which representing a word. - */ -declare interface WordBreakingFunction { - // invariant: span[i].end <= span[i + 1].start - // invariant: for all span[i] and span[i + 1], there does not exist a span[k] - // where span[i].end <= span[k].start AND span[k].end <= span[i + 1].start - (phrase: string): Span[]; -} - -/** - * A span of text in a phrase. This is usually meant to represent words from a - * pharse. - */ -declare interface Span { - // invariant: start < end (empty spans not allowed) - readonly start: number; - // invariant: end > end (empty spans not allowed) - readonly end: number; - // invariant: length === end - start - readonly length: number; - // invariant: text.length === length - // invariant: each character is BMP UTF-16 code unit, or is a high surrogate - // UTF-16 code unit followed by a low surrogate UTF-16 code unit. - readonly text: string; -} - - -/********************************** OTHER **********************************/ - -/** - * Options for various punctuation to use in suggestions. - */ -interface LexicalModelPunctuation { - /** - * The quotes that appear in "keep" suggestions, e.g., keep what the user - * typed verbatim. - * - * The keep suggestion is often the leftmost one, when suggested. - * - * [ “Hrllo” ] [ Hello ] [ Heck ] - */ - readonly quotesForKeepSuggestion: { - /** - * What will appear on the opening side of the quote. - * (left side for LTR scripts; right side for RTL scripts) - * - * Default: `“` - */ - readonly open: string; - /** - * What will appear on the closing side of the quote. - * (right side for LTR scripts; left side for RTL scripts) - * - * Default: `”` - */ - readonly close: string; - }; - /** - * What punctuation or spacing to insert after every complete word - * prediction. This can be set to the empty string when the script does not - * use spaces to separate words. - * - * Default: ` ` - */ - readonly insertAfterWord: string; - - /** - * Whether or not the model's language is typically displayed in RTL form. - * - * Default: false (or undefined) - */ - readonly isRTL?: boolean; -} +// Please include this package instead: +/// diff --git a/common/lexical-model-types/package-lock.json b/common/lexical-model-types/package-lock.json deleted file mode 100644 index 722e833af57a822dd6941715efdf6358e01fd79a..0000000000000000000000000000000000000000 --- a/common/lexical-model-types/package-lock.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@keymanapp/lexical-model-types", - "version": "0.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "typescript": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.6.3.tgz", - "integrity": "sha512-N7bceJL1CtRQ2RiG0AQME13ksR7DiuQh/QehubYcghzv20tnh+MQnQIuJddTmsbqYj+dztchykemz0zFzlvdQw==", - "dev": true - } - } -} diff --git a/common/lexical-model-types/package.json b/common/lexical-model-types/package.json index b8c0d8a27a28b68928fc03f85d8ef8319323fdae..7e132b7546d348309b91665a48e641a13f32836a 100644 --- a/common/lexical-model-types/package.json +++ b/common/lexical-model-types/package.json @@ -1,39 +1,29 @@ { "name": "@keymanapp/lexical-model-types", - "version": "0.0.0", - "description": "Type definitions in used in the LMLayer (lexical model/predictive text) component of Keyman.", - "types": "./index.d.ts", - "scripts": { - "test": "tsc test.ts" + "version": "14.0.78", + "description": "(deprecated) please use @keymanapp/models-types instead!", + "contributors": [ + "Eddie Antonio Santos " + ], + "homepage": "https://github.com/keymanapp/keyman#readme", + "license": "MIT", + "files": [ + "index.d.ts" + ], + "publishConfig": { + "access": "public" }, "repository": { "type": "git", - "url": "https://github.com/keymanapp/keyman" + "url": "git+https://github.com/keymanapp/keyman.git" + }, + "scripts": { + "test": "true" }, - "keywords": [ - "lmlayer", - "keyman", - "predictive", - "text", - "types", - "typing", - "typescript" - ], - "author": "Marc Durdin (https://github.com/mcdurdin)", - "contributors": [ - "Eddie Antonio Santos (https://github.com/eddieantonio)", - "Joshua Horton" - ], - "license": "MIT", "bugs": { "url": "https://github.com/keymanapp/keyman/issues" }, - "homepage": "https://github.com/keymanapp/keyman/tree/master/common/lexical-model-types#readme", - "devDependencies": { - "typescript": "^3.6.3" - }, - "files": [ - "README.md", - "index.d.ts" - ] + "dependencies": { + "@keymanapp/models-types": "^14.0.79" + } } diff --git a/common/models/templates/.gitignore b/common/models/templates/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b000665f7c74faf02f8fe3de00c7ba58cfb4053d --- /dev/null +++ b/common/models/templates/.gitignore @@ -0,0 +1,3 @@ +index.js +index.d.ts +*.js.map diff --git a/common/models/templates/package-lock.json b/common/models/templates/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..987e525d04c402d34cdce7f5ccd2785cf2f03fb7 --- /dev/null +++ b/common/models/templates/package-lock.json @@ -0,0 +1,272 @@ +{ + "name": "@keymanapp/models-templates", + "version": "14.0.144", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/chai": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.2.11.tgz", + "integrity": "sha512-t7uW6eFafjO+qJ3BIV2gGUyZs27egcNRkUdalkud+Qa3+kg//f129iuOFivHDXQ+vnU3fDXuwgv0cqMCbcE8sw==", + "dev": true + }, + "@types/mocha": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-7.0.2.tgz", + "integrity": "sha512-ZvO2tAcjmMi8V/5Z3JsyofMe3hasRcaw88cto5etSVMwVQfeivGAlEYmaQgceUSVYFofVjT+ioHsATjdWcFt1w==", + "dev": true + }, + "@types/node": { + "version": "14.0.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.4.tgz", + "integrity": "sha512-k3NqigXWRzQZVBDS5D1U70A5E8Qk4Kh+Ha/x4M8Bt9pF0X05eggfnC9+63Usc9Q928hRUIpIhTQaXsZwZBl4Ew==" + }, + "assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "browser-stdout": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", + "dev": true + }, + "chai": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.2.0.tgz", + "integrity": "sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw==", + "dev": true, + "requires": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^3.0.1", + "get-func-name": "^2.0.0", + "pathval": "^1.1.0", + "type-detect": "^4.0.5" + } + }, + "check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", + "dev": true + }, + "commander": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz", + "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-eql": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", + "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "dev": true, + "requires": { + "type-detect": "^4.0.0" + } + }, + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "get-func-name": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", + "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "growl": { + "version": "1.10.5", + "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", + "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "he": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "mocha": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-5.2.0.tgz", + "integrity": "sha512-2IUgKDhc3J7Uug+FxMXuqIyYzH7gJjXECKe/w43IGgQHTSj3InJi+yAA7T24L9bQMRKiUEHxEX37G5JpVUGLcQ==", + "dev": true, + "requires": { + "browser-stdout": "1.3.1", + "commander": "2.15.1", + "debug": "3.1.0", + "diff": "3.5.0", + "escape-string-regexp": "1.0.5", + "glob": "7.1.2", + "growl": "1.10.5", + "he": "1.1.1", + "minimatch": "3.0.4", + "mkdirp": "0.5.1", + "supports-color": "5.4.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "pathval": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz", + "integrity": "sha1-uULm1L3mUwBe9rcTYd74cn0GReA=", + "dev": true + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true + }, + "typescript": { + "version": "3.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.2.tgz", + "integrity": "sha512-q2ktq4n/uLuNNShyayit+DTobV2ApPEo/6so68JaD5ojvc/6GClBipedB9zNWYxRSAlZXAe405Rlijzl6qDiSw==", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/common/models/templates/package.json b/common/models/templates/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0df0c081ea1ed8414fcf37df0e96137029cfb23c --- /dev/null +++ b/common/models/templates/package.json @@ -0,0 +1,57 @@ +{ + "name": "@keymanapp/models-templates", + "version": "14.0.144", + "description": "Backing model implementations (templates) for Keyman's modelling layer", + "keywords": [ + "lm", + "lmlayer", + "lexical", + "model", + "templates", + "modelling", + "keyman", + "backend" + ], + "contributors": [ + "Eddie Antonio Santos " + ], + "homepage": "https://github.com/keymanapp/keyman#readme", + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "directories": { + "test": "test" + }, + "files": [ + "index.js" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/keymanapp/keyman.git" + }, + "scripts": { + "build": "tsc", + "prepare": "npm run build", + "pretest": "npm run build", + "test": "mocha -r test/helpers.js" + }, + "bugs": { + "url": "https://github.com/keymanapp/keyman/issues" + }, + "devDependencies": { + "@keymanapp/models-types": "^14.0.144", + "@keymanapp/web-utils": "^14.0.144", + "@types/chai": "^4.2.11", + "@types/mocha": "^7.0.2", + "@types/node": "^14.0.4", + "chai": "^4.2.0", + "mocha": "^5.2.0", + "typescript": "^3.8.3" + }, + "dependencies": { + "@keymanapp/models-wordbreakers": "^14.0.144" + } +} diff --git a/common/predictive-text/worker/models/common.ts b/common/models/templates/src/common.ts similarity index 58% rename from common/predictive-text/worker/models/common.ts rename to common/models/templates/src/common.ts index b5c803384044a648c9dfd1e0e192a704a777d1f2..6b9fb2bdea8e24846ee37e39865e0daa671fca5b 100644 --- a/common/predictive-text/worker/models/common.ts +++ b/common/models/templates/src/common.ts @@ -1,4 +1,6 @@ namespace models { + export const SENTINEL_CODE_UNIT = '\uFDD0'; + export function applyTransform(transform: Transform, context: Context): Context { // First, get the current context let fullLeftContext = context.left || ''; @@ -22,10 +24,10 @@ namespace models { } /** - * + * * @param transform Merges one transform into another, mutating the first parameter to * include the effects of the second. - * @param prefix + * @param prefix */ export function prependTransform(transform: Transform, prefix: Transform) { transform.insert = prefix.insert + transform.insert; @@ -34,4 +36,28 @@ namespace models { transform.deleteRight = (transform.deleteRight || 0) + prefix.deleteRight; } } -} \ No newline at end of file + + /** + * Checks whether or not the specified UCS-2 character corresponds to a UTF-16 high surrogate. + * + * @param char A single JavaScript (UCS-2) char corresponding to a single code unit. + */ + export function isHighSurrogate(char: string): boolean; + /** + * Checks whether or not the specified UCS-2 character corresponds to a UTF-16 high surrogate. + * + * @param codeUnit A code unit corresponding to a single UCS-2 char. + */ + export function isHighSurrogate(codeUnit: number): boolean; + export function isHighSurrogate(codeUnit: string|number): boolean { + if(typeof codeUnit == 'string') { + codeUnit = codeUnit.charCodeAt(0); + } + + return codeUnit >= 0xD800 && codeUnit <= 0xDBFF; + } + + export function isSentinel(char: string): boolean { + return char == models.SENTINEL_CODE_UNIT; + } +} diff --git a/common/models/templates/src/index.ts b/common/models/templates/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d63fe73a5e3831aa21fc957449019c1ad2e7099 --- /dev/null +++ b/common/models/templates/src/index.ts @@ -0,0 +1,6 @@ +/// + +// Add all namespaces defined here to the global scope: +if (typeof module != 'undefined' && typeof module.exports != 'undefined') { + module.exports['models'] = models; +} diff --git a/common/models/templates/src/priority-queue.ts b/common/models/templates/src/priority-queue.ts new file mode 100644 index 0000000000000000000000000000000000000000..c372d881c58074ad3caf1e502066d163244a697c --- /dev/null +++ b/common/models/templates/src/priority-queue.ts @@ -0,0 +1,219 @@ +/** + * @file priority-queue.ts + * + * Defines a mildly abstracted priority queue implementation. + */ + +namespace models { + /** + * Used to compare two instances of a type. + * @returns + * - value < 0 if `a` should come before `b` + * - value > 0 if `b` should come before `a` + * - 0 if they should be treated equally. + */ + export type Comparator = (a: Type, b: Type) => number; + + export class PriorityQueue { + + private comparator: Comparator; + private heap: Type[]; + + /** + * Constructs an empty priority queue. + * @param comparator A `Comparator` returning negative values when and only when + * the first parameter should precede the second parameter. + */ + constructor(comparator: Comparator, initialEntries: Type[] = []) { + // TODO: We may wish to allow options specifying a limit or threshold for adding + // items to the priority queue. Possibly both. + // + // When that time comes, consider a min-max heap. + // https://en.wikipedia.org/wiki/Min-max_heap + this.comparator = comparator; + + this.heap = Array.from(initialEntries); + this.heapify(); + } + + private static leftChildIndex(index: number): number { + return index * 2 + 1; + } + + private static rightChildIndex(index: number): number { + return index * 2 + 2; + } + + private static parentIndex(index: number): number { + return Math.floor((index-1)/2); + } + + /** + * Maintains internal state, rearranging the internal state until all heap constraints + * are properly satisfied. + * - O(N) when 'heapifying' the whole heap + * - O(N) worst-case for partial heap operations (as part of an enqueueAll) + *

+ */ + private heapify(): void; + private heapify(start: number, end: number): void; + private heapify(start?: number, end?: number): void { + if(start == undefined || end == undefined) { + this.heapify(0, this.count - 1); + } + + // Use of 'indices' here is a bit of a customization. + // At the cost of (temporary) extra storage space, we can more efficiently enqueue + // multiple elements simultaneously. + let queuedIndices: number[] = []; + let lastParent = -1; + + for(let i = end; i >= start; i--) { + let parent = PriorityQueue.parentIndex(i); + if(this.siftDown(i) && parent < start && lastParent != parent) { + // We only need to queue examination for a heap node if its children have changed + // and it isn't already being examined. + queuedIndices.push(parent); + lastParent = parent; + } + } + + lastParent = -1; + while(queuedIndices.length > 0) { + let index = queuedIndices.shift(); + let parent = PriorityQueue.parentIndex(index); + if(this.siftDown(index) && parent >= 0 && lastParent != parent) { + // We only need to queue examination for a heap node if its children have changed. + queuedIndices.push(parent); + lastParent = parent; + } + } + } + + /** + * Returns the number of elements currently held by the priority queue. + */ + get count(): number { + return this.heap.length; + } + + /** + * Returns the highest-priority item within the priority queue. + *

+ * Is O(1). + */ + peek() { + return this.heap[0]; // undefined if it doesn't exist... which is completely correct. + } + + /** + * Inserts a new element into the priority queue, placing it in order. + *

+ * Is O(log N), where N = # of items in the priority queue. + * @param element + */ + enqueue(element: Type) { + let index = this.heap.length; + this.heap.push(element); + + let parent = PriorityQueue.parentIndex; + let parentIndex = parent(index); + while(index !== 0 && this.comparator(this.heap[index], this.heap[parentIndex]) < 0) { + let a = this.heap[index]; + this.heap[index] = this.heap[parentIndex]; + this.heap[parentIndex] = a; + + index = parentIndex; + parentIndex = parent(index); + } + } + + /** + * Efficiently batch-enqueues multiple elements. + * Worst-case is the _better_ of the following: + * - O(`elements.count` + `heap.count`) - large element counts will trigger in-place + * heap reconstruction. + * - O(`elements.count` * log(`heap.count`)) - logarithmic when elements.count << heap.count + * @param elements A group of elements to enqueue simultaneously. + */ + enqueueAll(elements: Type[]) { + if(elements.length == 0) { + return; + } + + let firstIndex = this.count + this.heap = this.heap.concat(elements); + let firstParent = PriorityQueue.parentIndex(firstIndex); + + // The 'parent' of index 0 will return -1, which is illegal. + this.heapify(firstParent >= 0 ? firstParent : 0, PriorityQueue.parentIndex(this.count-1)); + } + + /** + * Removes the highest-priority element from the queue, returning it. + *

+ * Is O(log N), where N = number of items in the priority queue. + */ + dequeue(): Type { + if(this.count == 0) { + return undefined; + } + + const root = this.heap[0]; + let tail = this.heap.pop(); + if(this.heap.length > 0) { + this.heap[0] = tail; + this.siftDown(0); + } + + return root; + } + + /** + * Compares the entry at the specified index against its children, + * propagating it downward within the heap until heap requirements are specified. + *

+ * Is O(log N), where N = number of items in the priority queue. + * + * @param index The index of the top-most node that must be examined + * for repositioning. + * @returns `true` if a swap occurred, `false` otherwise. + */ + private siftDown(index: number): boolean { + let leftIndex = PriorityQueue.leftChildIndex(index); + let rightIndex = PriorityQueue.rightChildIndex(index); + let topMostIndex = index; + + if(leftIndex < this.heap.length && this.comparator(this.heap[leftIndex], this.heap[topMostIndex]) < 0) { + topMostIndex = leftIndex; + } + + if(rightIndex < this.heap.length && this.comparator(this.heap[rightIndex], this.heap[topMostIndex]) < 0) { + topMostIndex = rightIndex; + } + + if(topMostIndex != index) { + let a = this.heap[index]; + this.heap[index] = this.heap[topMostIndex]; + this.heap[topMostIndex] = a; + + this.siftDown(topMostIndex); + return true; + } else { + return false; + } + } + + /** + * Returns an array containing all entries of the priority queue. + * Altering the returned array will not affect the queue, but mutating + * the array's elements can cause unintended side effects. + * + * This function makes no guarantees on the ordering of the returned elements; + * they will almost certainly be unsorted. + */ + toArray(): Type[] { + return Array.from(this.heap); + } + } +} diff --git a/common/predictive-text/worker/models/trie-model.ts b/common/models/templates/src/trie-model.ts similarity index 75% rename from common/predictive-text/worker/models/trie-model.ts rename to common/models/templates/src/trie-model.ts index 896c3c1d45978d7a2846accb38a99bdcd07a948c..d187b3414e1b7b1374d3905825cf57ae7c5ba4bf 100644 --- a/common/predictive-text/worker/models/trie-model.ts +++ b/common/models/templates/src/trie-model.ts @@ -22,8 +22,8 @@ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/// /// +/// /** * @file trie-model.ts @@ -85,7 +85,7 @@ trieData['totalWeight'], options.searchTermToKey as Wordform2Key || defaultSearchTermToKey ); - this.breakWords = options.wordBreaker || wordBreakers['default']; + this.breakWords = options.wordBreaker || getDefaultWordBreaker(); this.punctuation = options.punctuation; } @@ -162,6 +162,118 @@ public wordbreak(context: Context): USVString { return this.getLastWord(context.left); } + + public traverseFromRoot(): LexiconTraversal { + return new TrieModel.Traversal(this._trie['root'], ''); + } + + private static Traversal = class implements LexiconTraversal { + /** + * The lexical prefix corresponding to the current traversal state. + */ + prefix: String; + + /** + * The current traversal node. Serves as the 'root' of its own sub-Trie, + * and we cannot navigate back to its parent. + */ + root: Node; + + constructor(root: Node, prefix: string) { + this.root = root; + this.prefix = prefix; + } + + *children(): Generator<{char: string, traversal: () => LexiconTraversal}> { + let root = this.root; + + if(root.type == 'internal') { + for(let entry of root.values) { + let entryNode = root.children[entry]; + + // UTF-16 astral plane check. + if(models.isHighSurrogate(entry)) { + // First code unit of a UTF-16 code point. + // For now, we'll just assume the second always completes such a char. + // + // Note: Things get nasty here if this is only sometimes true; in the future, + // we should compile-time enforce that this assumption is always true if possible. + if(entryNode.type == 'internal') { + let internalNode = entryNode; + for(let lowSurrogate of internalNode.values) { + let prefix = this.prefix + entry + lowSurrogate; + yield { + char: entry + lowSurrogate, + traversal: function() { return new TrieModel.Traversal(internalNode.children[lowSurrogate], prefix) } + } + } + } else { + // Determine how much of the 'leaf' entry has no Trie nodes, emulate them. + let fullText = entryNode.entries[0].key; + entry = entry + fullText[this.prefix.length + 1]; // The other half of the non-BMP char. + let prefix = this.prefix + entry; + + yield { + char: entry, + traversal: function () {return new TrieModel.Traversal(entryNode, prefix)} + } + } + } else if(models.isSentinel(entry)) { + continue; + } else if(!entry) { + // Prevent any accidental 'null' or 'undefined' entries from having an effect. + continue; + } else { + let prefix = this.prefix + entry; + yield { + char: entry, + traversal: function() { return new TrieModel.Traversal(entryNode, prefix)} + } + } + } + + return; + } else { // type == 'leaf' + let prefix = this.prefix; + + let children = root.entries.filter(function(entry) { + return entry.key != prefix && prefix.length < entry.key.length; + }) + + for(let {key} of children) { + let nodeKey = key[prefix.length]; + + if(models.isHighSurrogate(nodeKey)) { + // Merge the other half of an SMP char in! + nodeKey = nodeKey + key[prefix.length+1]; + } + yield { + char: nodeKey, + traversal: function() { return new TrieModel.Traversal(root, prefix + nodeKey)} + } + }; + return; + } + } + + get entries(): string[] { + if(this.root.type == 'leaf') { + let prefix = this.prefix; + let matches = this.root.entries.filter(function(entry) { + return entry.key == prefix; + }); + + return matches.map(function(value) { return value.content }); + } else { + let matchingLeaf = this.root.children[models.SENTINEL_CODE_UNIT]; + if(matchingLeaf && matchingLeaf.type == 'leaf') { + return matchingLeaf.entries.map(function(value) { return value.content }); + } else { + return []; + } + } + } + } }; ///////////////////////////////////////////////////////////////////////////////// @@ -316,7 +428,10 @@ * @param queue */ function getSortedResults(node: Node, prefix: SearchKey, N: number, limit = MAX_SUGGESTIONS): TextWithProbability[] { - let queue = new PriorityQueue(); + let queue = new PriorityQueue(function(a: Weighted, b: Weighted) { + // In case of Trie compilation issues that emit `null` or `undefined` + return (b ? b.weight : 0) - (a ? a.weight : 0); + }); let results: TextWithProbability[] = []; if (node.type === 'leaf') { @@ -339,7 +454,7 @@ queue.enqueue(node); let next: Weighted; - while (next = queue.pop()) { + while (next = queue.dequeue()) { if (isNode(next)) { // When a node is next up in the queue, that means that next least // likely suggestion is among its decsendants. @@ -378,41 +493,6 @@ return 'type' in x; } - /** - * A priority queue that always pops the highest weighted item. - */ - class PriorityQueue { - // TODO: This probable should use a max-heap implementation, but I'm just doing - // a O(n log n) sort of the array when an item is popped. - private _storage: Weighted[] = []; - // TODO: this should have a limit, and ensure small values are not added. - - /** - * Enqueues a single element to the priority queue. - */ - enqueue(element: Weighted) { - this._storage.push(element); - } - - /** - * Adds an array of weighted elements to the priority queue. - */ - enqueueAll(elements: Weighted[]) { - this._storage = this._storage.concat(elements); - } - - /** - * Pops the highest weighted item in the queue. - */ - pop(): Weighted { - // Lazily sort only when NEEDED. - // Sort in descending order of weight, so heaviest weight will be popped - // first. - this._storage.sort((a, b) => b.weight - a.weight); - return this._storage.shift(); - } - } - /** * Converts wordforms into an indexable form. It does this by * normalizing into NFD, removing diacritics, and then converting @@ -452,4 +532,16 @@ .replace(/[\u0300-\u036f]/g, '') .toLowerCase() as SearchKey; } + + function getDefaultWordBreaker() { + let namespace: {}; + // @ts-ignore + if (typeof wordBreakers !== 'undefined') { + // @ts-ignore + namespace = wordBreakers; + } else { + namespace = require('@keymanapp/models-wordBreakers').wordBreakers; + } + return namespace['default']; + } } diff --git a/common/models/templates/test/fixtures/tries/accented.json b/common/models/templates/test/fixtures/tries/accented.json new file mode 100644 index 0000000000000000000000000000000000000000..1ea81f4cba7e71c258907ce7fac6b555720c57eb --- /dev/null +++ b/common/models/templates/test/fixtures/tries/accented.json @@ -0,0 +1,4 @@ +{ + "totalWeight": 2, + "root": {"type":"internal","weight":1,"values":["p","n"],"children":{"p":{"type":"leaf","weight":1,"entries":[{"key":"pho","weight":1,"content":"phở"}]},"n":{"type":"leaf","weight":1,"entries":[{"key":"naive","weight":1,"content":"naïve"}]}}} +} diff --git a/common/models/templates/test/fixtures/tries/english-1000.json b/common/models/templates/test/fixtures/tries/english-1000.json new file mode 100644 index 0000000000000000000000000000000000000000..519a97aeb6005fc4af92005e3dbebbc09cd65540 --- /dev/null +++ b/common/models/templates/test/fixtures/tries/english-1000.json @@ -0,0 +1,4 @@ +{ + "totalWeight": 500500, + "root": {"type":"internal","weight":1000,"values":["t","o","a","i","w","h","f","b","n","y","s","m","u","c","d","l","e","j","p","g","v","k","r","q"],"children":{"t":{"type":"internal","weight":1000,"values":["h","o","i","w","a","u","e","r","y"],"children":{"h":{"type":"internal","weight":1000,"values":["e","a","i","r","o","u"],"children":{"e":{"type":"internal","weight":1000,"values":["\ufdd0","y","r","i","m","s","n","o"],"children":{"\ufdd0":{"type":"leaf","weight":1000,"entries":[{"key":"the","weight":1000,"content":"the"}]},"y":{"type":"leaf","weight":971,"entries":[{"key":"they","weight":971,"content":"they"}]},"r":{"type":"internal","weight":963,"values":["e"],"children":{"e":{"type":"internal","weight":963,"values":["\ufdd0","f"],"children":{"\ufdd0":{"type":"leaf","weight":963,"entries":[{"key":"there","weight":963,"content":"there"}]},"f":{"type":"leaf","weight":552,"entries":[{"key":"therefore","weight":552,"content":"therefore"}]}}}}},"i":{"type":"leaf","weight":961,"entries":[{"key":"their","weight":961,"content":"their"}]},"m":{"type":"internal","weight":941,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":941,"entries":[{"key":"them","weight":941,"content":"them"}]},"s":{"type":"leaf","weight":662,"entries":[{"key":"themselves","weight":662,"content":"themselves"}]}}},"s":{"type":"leaf","weight":933,"entries":[{"key":"these","weight":933,"content":"these"}]},"n":{"type":"leaf","weight":930,"entries":[{"key":"then","weight":930,"content":"then"}]},"o":{"type":"leaf","weight":229,"entries":[{"key":"theory","weight":229,"content":"theory"}]}}},"a":{"type":"internal","weight":994,"values":["t","n"],"children":{"t":{"type":"leaf","weight":994,"entries":[{"key":"that","weight":994,"content":"that"}]},"n":{"type":"leaf","weight":942,"entries":[{"key":"than","weight":942,"content":"than"}]}}},"i":{"type":"internal","weight":980,"values":["s","n","r"],"children":{"s":{"type":"leaf","weight":980,"entries":[{"key":"this","weight":980,"content":"this"}]},"n":{"type":"internal","weight":808,"values":["k","g"],"children":{"k":{"type":"internal","weight":808,"values":["\ufdd0","i"],"children":{"\ufdd0":{"type":"leaf","weight":808,"entries":[{"key":"think","weight":808,"content":"think"}]},"i":{"type":"leaf","weight":337,"entries":[{"key":"thinking","weight":337,"content":"thinking"}]}}},"g":{"type":"leaf","weight":754,"entries":[{"key":"things","weight":754,"content":"things"},{"key":"thing","weight":732,"content":"thing"}]}}},"r":{"type":"leaf","weight":504,"entries":[{"key":"third","weight":504,"content":"third"}]}}},"r":{"type":"internal","weight":908,"values":["o","e"],"children":{"o":{"type":"internal","weight":908,"values":["u"],"children":{"u":{"type":"internal","weight":908,"values":["g"],"children":{"g":{"type":"internal","weight":908,"values":["h"],"children":{"h":{"type":"internal","weight":908,"values":["\ufdd0","o"],"children":{"\ufdd0":{"type":"leaf","weight":908,"entries":[{"key":"through","weight":908,"content":"through"}]},"o":{"type":"leaf","weight":305,"entries":[{"key":"throughout","weight":305,"content":"throughout"}]}}}}}}}}},"e":{"type":"leaf","weight":852,"entries":[{"key":"three","weight":852,"content":"three"}]}}},"o":{"type":"internal","weight":895,"values":["s","u"],"children":{"s":{"type":"leaf","weight":895,"entries":[{"key":"those","weight":895,"content":"those"}]},"u":{"type":"internal","weight":835,"values":["g"],"children":{"g":{"type":"internal","weight":835,"values":["h"],"children":{"h":{"type":"leaf","weight":835,"entries":[{"key":"thought","weight":835,"content":"thought"},{"key":"though","weight":812,"content":"though"}]}}}}}}},"u":{"type":"leaf","weight":711,"entries":[{"key":"thus","weight":711,"content":"thus"}]}}},"o":{"type":"internal","weight":997,"values":["\ufdd0","o","l","w","d","g","t","p"],"children":{"\ufdd0":{"type":"leaf","weight":997,"entries":[{"key":"to","weight":997,"content":"to"}]},"o":{"type":"internal","weight":893,"values":["\ufdd0","k"],"children":{"\ufdd0":{"type":"leaf","weight":893,"entries":[{"key":"too","weight":893,"content":"too"}]},"k":{"type":"leaf","weight":804,"entries":[{"key":"took","weight":804,"content":"took"}]}}},"l":{"type":"leaf","weight":796,"entries":[{"key":"told","weight":796,"content":"told"}]},"w":{"type":"internal","weight":776,"values":["a","n"],"children":{"a":{"type":"leaf","weight":776,"entries":[{"key":"toward","weight":776,"content":"toward"}]},"n":{"type":"leaf","weight":567,"entries":[{"key":"town","weight":567,"content":"town"}]}}},"d":{"type":"leaf","weight":683,"entries":[{"key":"today","weight":683,"content":"today"}]},"g":{"type":"leaf","weight":658,"entries":[{"key":"together","weight":658,"content":"together"}]},"t":{"type":"leaf","weight":564,"entries":[{"key":"total","weight":564,"content":"total"}]},"p":{"type":"leaf","weight":550,"entries":[{"key":"top","weight":550,"content":"top"}]}}},"i":{"type":"internal","weight":934,"values":["m"],"children":{"m":{"type":"internal","weight":934,"values":["e"],"children":{"e":{"type":"internal","weight":934,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":934,"entries":[{"key":"time","weight":934,"content":"time"}]},"s":{"type":"leaf","weight":700,"entries":[{"key":"times","weight":700,"content":"times"}]}}}}}}},"w":{"type":"leaf","weight":932,"entries":[{"key":"two","weight":932,"content":"two"}]},"a":{"type":"internal","weight":851,"values":["k","x","b","l"],"children":{"k":{"type":"internal","weight":851,"values":["e","i"],"children":{"e":{"type":"internal","weight":851,"values":["\ufdd0","n"],"children":{"\ufdd0":{"type":"leaf","weight":851,"entries":[{"key":"take","weight":851,"content":"take"}]},"n":{"type":"leaf","weight":678,"entries":[{"key":"taken","weight":678,"content":"taken"}]}}},"i":{"type":"leaf","weight":464,"entries":[{"key":"taking","weight":464,"content":"taking"}]}}},"x":{"type":"leaf","weight":542,"entries":[{"key":"tax","weight":542,"content":"tax"}]},"b":{"type":"leaf","weight":529,"entries":[{"key":"table","weight":529,"content":"table"}]},"l":{"type":"leaf","weight":374,"entries":[{"key":"talk","weight":374,"content":"talk"}]}}},"u":{"type":"internal","weight":720,"values":["r"],"children":{"r":{"type":"internal","weight":720,"values":["n"],"children":{"n":{"type":"leaf","weight":720,"entries":[{"key":"turned","weight":720,"content":"turned"},{"key":"turn","weight":610,"content":"turn"}]}}}}},"e":{"type":"internal","weight":660,"values":["l","n","r","m","c","s"],"children":{"l":{"type":"leaf","weight":660,"entries":[{"key":"tell","weight":660,"content":"tell"}]},"n":{"type":"leaf","weight":415,"entries":[{"key":"ten","weight":415,"content":"ten"}]},"r":{"type":"leaf","weight":411,"entries":[{"key":"terms","weight":411,"content":"terms"}]},"m":{"type":"leaf","weight":270,"entries":[{"key":"temperature","weight":270,"content":"temperature"}]},"c":{"type":"leaf","weight":162,"entries":[{"key":"technical","weight":162,"content":"technical"}]},"s":{"type":"leaf","weight":157,"entries":[{"key":"test","weight":157,"content":"test"}]}}},"r":{"type":"internal","weight":607,"values":["u","i","y","a","o","e"],"children":{"u":{"type":"internal","weight":607,"values":["e","t"],"children":{"e":{"type":"leaf","weight":607,"entries":[{"key":"true","weight":607,"content":"true"}]},"t":{"type":"leaf","weight":203,"entries":[{"key":"truth","weight":203,"content":"truth"}]}}},"i":{"type":"internal","weight":431,"values":["e","a"],"children":{"e":{"type":"leaf","weight":431,"entries":[{"key":"tried","weight":431,"content":"tried"}]},"a":{"type":"leaf","weight":268,"entries":[{"key":"trial","weight":268,"content":"trial"}]}}},"y":{"type":"leaf","weight":409,"entries":[{"key":"trying","weight":409,"content":"trying"},{"key":"try","weight":295,"content":"try"}]},"a":{"type":"internal","weight":382,"values":["i","d"],"children":{"i":{"type":"leaf","weight":382,"entries":[{"key":"training","weight":382,"content":"training"}]},"d":{"type":"leaf","weight":315,"entries":[{"key":"trade","weight":315,"content":"trade"}]}}},"o":{"type":"leaf","weight":267,"entries":[{"key":"trouble","weight":267,"content":"trouble"}]},"e":{"type":"leaf","weight":216,"entries":[{"key":"treatment","weight":216,"content":"treatment"}]}}},"y":{"type":"internal","weight":540,"values":["p"],"children":{"p":{"type":"internal","weight":540,"values":["e"],"children":{"e":{"type":"internal","weight":540,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":540,"entries":[{"key":"type","weight":540,"content":"type"}]},"s":{"type":"leaf","weight":132,"entries":[{"key":"types","weight":132,"content":"types"}]}}}}}}}}},"o":{"type":"internal","weight":999,"values":["f","n","r","u","t","v","w","l","p","h","b"],"children":{"f":{"type":"internal","weight":999,"values":["\ufdd0","f","t"],"children":{"\ufdd0":{"type":"leaf","weight":999,"entries":[{"key":"of","weight":999,"content":"of"}]},"f":{"type":"internal","weight":860,"values":["\ufdd0","i"],"children":{"\ufdd0":{"type":"leaf","weight":860,"entries":[{"key":"off","weight":860,"content":"off"}]},"i":{"type":"leaf","weight":641,"entries":[{"key":"office","weight":641,"content":"office"}]}}},"t":{"type":"leaf","weight":756,"entries":[{"key":"often","weight":756,"content":"often"}]}}},"n":{"type":"internal","weight":985,"values":["\ufdd0","e","l","c"],"children":{"\ufdd0":{"type":"leaf","weight":985,"entries":[{"key":"on","weight":985,"content":"on"}]},"e":{"type":"internal","weight":969,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":969,"entries":[{"key":"one","weight":969,"content":"one"}]},"s":{"type":"leaf","weight":133,"entries":[{"key":"ones","weight":133,"content":"ones"}]}}},"l":{"type":"leaf","weight":939,"entries":[{"key":"only","weight":939,"content":"only"}]},"c":{"type":"leaf","weight":831,"entries":[{"key":"once","weight":831,"content":"once"}]}}},"r":{"type":"internal","weight":974,"values":["\ufdd0","d","g","i"],"children":{"\ufdd0":{"type":"leaf","weight":974,"entries":[{"key":"or","weight":974,"content":"or"}]},"d":{"type":"leaf","weight":765,"entries":[{"key":"order","weight":765,"content":"order"}]},"g":{"type":"leaf","weight":219,"entries":[{"key":"organization","weight":219,"content":"organization"}]},"i":{"type":"leaf","weight":4,"entries":[{"key":"original","weight":4,"content":"original"}]}}},"u":{"type":"internal","weight":950,"values":["t","r"],"children":{"t":{"type":"internal","weight":950,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":950,"entries":[{"key":"out","weight":950,"content":"out"}]},"s":{"type":"leaf","weight":562,"entries":[{"key":"outside","weight":562,"content":"outside"}]}}},"r":{"type":"leaf","weight":922,"entries":[{"key":"our","weight":922,"content":"our"}]}}},"t":{"type":"internal","weight":938,"values":["h"],"children":{"h":{"type":"internal","weight":938,"values":["e"],"children":{"e":{"type":"internal","weight":938,"values":["r"],"children":{"r":{"type":"internal","weight":938,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":938,"entries":[{"key":"other","weight":938,"content":"other"}]},"s":{"type":"leaf","weight":722,"entries":[{"key":"others","weight":722,"content":"others"}]}}}}}}}}},"v":{"type":"leaf","weight":921,"entries":[{"key":"over","weight":921,"content":"over"}]},"w":{"type":"leaf","weight":884,"entries":[{"key":"own","weight":884,"content":"own"}]},"l":{"type":"leaf","weight":862,"entries":[{"key":"old","weight":862,"content":"old"}]},"p":{"type":"internal","weight":718,"values":["e","p"],"children":{"e":{"type":"internal","weight":718,"values":["n","r"],"children":{"n":{"type":"internal","weight":718,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":718,"entries":[{"key":"open","weight":718,"content":"open"}]},"e":{"type":"leaf","weight":243,"entries":[{"key":"opened","weight":243,"content":"opened"}]}}},"r":{"type":"leaf","weight":93,"entries":[{"key":"operation","weight":93,"content":"operation"}]}}},"p":{"type":"leaf","weight":167,"entries":[{"key":"opportunity","weight":167,"content":"opportunity"}]}}},"h":{"type":"leaf","weight":176,"entries":[{"key":"oh","weight":176,"content":"oh"}]},"b":{"type":"internal","weight":119,"values":["t","v"],"children":{"t":{"type":"leaf","weight":119,"entries":[{"key":"obtained","weight":119,"content":"obtained"}]},"v":{"type":"leaf","weight":110,"entries":[{"key":"obviously","weight":110,"content":"obviously"}]}}}}},"a":{"type":"internal","weight":998,"values":["n","\ufdd0","s","t","r","l","b","f","g","m","w","c","i","v","d","p","j","u","h"],"children":{"n":{"type":"internal","weight":998,"values":["d","\ufdd0","y","o","s","a"],"children":{"d":{"type":"leaf","weight":998,"entries":[{"key":"and","weight":998,"content":"and"}]},"\ufdd0":{"type":"leaf","weight":972,"entries":[{"key":"an","weight":972,"content":"an"}]},"y":{"type":"internal","weight":927,"values":["\ufdd0","t","o"],"children":{"\ufdd0":{"type":"leaf","weight":927,"entries":[{"key":"any","weight":927,"content":"any"}]},"t":{"type":"leaf","weight":676,"entries":[{"key":"anything","weight":676,"content":"anything"}]},"o":{"type":"leaf","weight":296,"entries":[{"key":"anyone","weight":296,"content":"anyone"}]}}},"o":{"type":"leaf","weight":869,"entries":[{"key":"another","weight":869,"content":"another"}]},"s":{"type":"leaf","weight":366,"entries":[{"key":"answer","weight":366,"content":"answer"}]},"a":{"type":"leaf","weight":65,"entries":[{"key":"analysis","weight":65,"content":"analysis"}]}}},"\ufdd0":{"type":"leaf","weight":996,"entries":[{"key":"a","weight":996,"content":"a"}]},"s":{"type":"internal","weight":987,"values":["\ufdd0","k","s"],"children":{"\ufdd0":{"type":"leaf","weight":987,"entries":[{"key":"as","weight":987,"content":"as"}]},"k":{"type":"leaf","weight":786,"entries":[{"key":"asked","weight":786,"content":"asked"},{"key":"ask","weight":221,"content":"ask"}]},"s":{"type":"leaf","weight":256,"entries":[{"key":"association","weight":256,"content":"association"}]}}},"t":{"type":"internal","weight":983,"values":["\ufdd0","t"],"children":{"\ufdd0":{"type":"leaf","weight":983,"entries":[{"key":"at","weight":983,"content":"at"}]},"t":{"type":"internal","weight":473,"values":["e","i","a"],"children":{"e":{"type":"leaf","weight":473,"entries":[{"key":"attention","weight":473,"content":"attention"}]},"i":{"type":"leaf","weight":48,"entries":[{"key":"attitude","weight":48,"content":"attitude"}]},"a":{"type":"leaf","weight":28,"entries":[{"key":"attack","weight":28,"content":"attack"}]}}}}},"r":{"type":"internal","weight":977,"values":["e","o","t","m"],"children":{"e":{"type":"internal","weight":977,"values":["\ufdd0","a"],"children":{"\ufdd0":{"type":"leaf","weight":977,"entries":[{"key":"are","weight":977,"content":"are"}]},"a":{"type":"internal","weight":724,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":724,"entries":[{"key":"area","weight":724,"content":"area"}]},"s":{"type":"leaf","weight":613,"entries":[{"key":"areas","weight":613,"content":"areas"}]}}}}},"o":{"type":"leaf","weight":840,"entries":[{"key":"around","weight":840,"content":"around"}]},"t":{"type":"leaf","weight":559,"entries":[{"key":"art","weight":559,"content":"art"}]},"m":{"type":"internal","weight":250,"values":["y","s"],"children":{"y":{"type":"leaf","weight":250,"entries":[{"key":"army","weight":250,"content":"army"}]},"s":{"type":"leaf","weight":169,"entries":[{"key":"arms","weight":169,"content":"arms"}]}}}}},"l":{"type":"internal","weight":965,"values":["l","s","w","m","o","t","r"],"children":{"l":{"type":"leaf","weight":965,"entries":[{"key":"all","weight":965,"content":"all"}]},"s":{"type":"leaf","weight":914,"entries":[{"key":"also","weight":914,"content":"also"}]},"w":{"type":"leaf","weight":817,"entries":[{"key":"always","weight":817,"content":"always"}]},"m":{"type":"leaf","weight":807,"entries":[{"key":"almost","weight":807,"content":"almost"}]},"o":{"type":"internal","weight":741,"values":["n"],"children":{"n":{"type":"internal","weight":741,"values":["g","e"],"children":{"g":{"type":"leaf","weight":741,"entries":[{"key":"along","weight":741,"content":"along"}]},"e":{"type":"leaf","weight":519,"entries":[{"key":"alone","weight":519,"content":"alone"}]}}}}},"t":{"type":"leaf","weight":721,"entries":[{"key":"although","weight":721,"content":"although"}]},"r":{"type":"leaf","weight":663,"entries":[{"key":"already","weight":663,"content":"already"}]}}},"b":{"type":"internal","weight":944,"values":["o","l"],"children":{"o":{"type":"internal","weight":944,"values":["u","v"],"children":{"u":{"type":"leaf","weight":944,"entries":[{"key":"about","weight":944,"content":"about"}]},"v":{"type":"leaf","weight":696,"entries":[{"key":"above","weight":696,"content":"above"}]}}},"l":{"type":"leaf","weight":578,"entries":[{"key":"able","weight":578,"content":"able"}]}}},"f":{"type":"internal","weight":915,"values":["t","\ufdd0"],"children":{"t":{"type":"internal","weight":915,"values":["e"],"children":{"e":{"type":"internal","weight":915,"values":["r"],"children":{"r":{"type":"internal","weight":915,"values":["\ufdd0","n"],"children":{"\ufdd0":{"type":"leaf","weight":915,"entries":[{"key":"after","weight":915,"content":"after"}]},"n":{"type":"leaf","weight":33,"entries":[{"key":"afternoon","weight":33,"content":"afternoon"}]}}}}}}},"\ufdd0":{"type":"leaf","weight":909,"entries":[{"key":"af","weight":909,"content":"af"}]}}},"g":{"type":"internal","weight":857,"values":["a","o","e","r"],"children":{"a":{"type":"internal","weight":857,"values":["i"],"children":{"i":{"type":"internal","weight":857,"values":["n"],"children":{"n":{"type":"leaf","weight":857,"entries":[{"key":"against","weight":857,"content":"against"},{"key":"again","weight":843,"content":"again"}]}}}}},"o":{"type":"leaf","weight":630,"entries":[{"key":"ago","weight":630,"content":"ago"}]},"e":{"type":"leaf","weight":600,"entries":[{"key":"age","weight":600,"content":"age"}]},"r":{"type":"leaf","weight":36,"entries":[{"key":"agreement","weight":36,"content":"agreement"}]}}},"m":{"type":"internal","weight":841,"values":["e","o",null],"children":{"e":{"type":"internal","weight":841,"values":["r"],"children":{"r":{"type":"internal","weight":841,"values":["i"],"children":{"i":{"type":"internal","weight":841,"values":["c"],"children":{"c":{"type":"internal","weight":841,"values":["a"],"children":{"a":{"type":"leaf","weight":841,"entries":[{"key":"american","weight":841,"content":"american"},{"key":"america","weight":512,"content":"america"}]}}}}}}}}},"o":{"type":"internal","weight":758,"values":["n","u"],"children":{"n":{"type":"leaf","weight":758,"entries":[{"key":"among","weight":758,"content":"among"}]},"u":{"type":"leaf","weight":442,"entries":[{"key":"amount","weight":442,"content":"amount"}]}}},"undefined":{"type":"leaf","weight":614,"entries":[{"key":"am","weight":614,"content":"am"}]}}},"w":{"type":"leaf","weight":816,"entries":[{"key":"away","weight":816,"content":"away"}]},"c":{"type":"internal","weight":693,"values":["t","r","c"],"children":{"t":{"type":"internal","weight":693,"values":["i","\ufdd0","u"],"children":{"i":{"type":"internal","weight":693,"values":["o","v"],"children":{"o":{"type":"leaf","weight":693,"entries":[{"key":"action","weight":693,"content":"action"}]},"v":{"type":"internal","weight":131,"values":["i"],"children":{"i":{"type":"internal","weight":131,"values":["t"],"children":{"t":{"type":"internal","weight":131,"values":["y","i"],"children":{"y":{"type":"leaf","weight":131,"entries":[{"key":"activity","weight":131,"content":"activity"}]},"i":{"type":"leaf","weight":121,"entries":[{"key":"activities","weight":121,"content":"activities"}]}}}}}}}}},"\ufdd0":{"type":"leaf","weight":682,"entries":[{"key":"act","weight":682,"content":"act"}]},"u":{"type":"leaf","weight":423,"entries":[{"key":"actually","weight":423,"content":"actually"}]}}},"r":{"type":"leaf","weight":680,"entries":[{"key":"across","weight":680,"content":"across"}]},"c":{"type":"internal","weight":298,"values":["o"],"children":{"o":{"type":"internal","weight":298,"values":["r","u"],"children":{"r":{"type":"leaf","weight":298,"entries":[{"key":"according","weight":298,"content":"according"}]},"u":{"type":"leaf","weight":135,"entries":[{"key":"account","weight":135,"content":"account"}]}}}}}}},"i":{"type":"internal","weight":643,"values":["r","d"],"children":{"r":{"type":"leaf","weight":643,"entries":[{"key":"air","weight":643,"content":"air"}]},"d":{"type":"leaf","weight":265,"entries":[{"key":"aid","weight":265,"content":"aid"}]}}},"v":{"type":"internal","weight":627,"values":["a","e"],"children":{"a":{"type":"leaf","weight":627,"entries":[{"key":"available","weight":627,"content":"available"}]},"e":{"type":"leaf","weight":241,"entries":[{"key":"average","weight":241,"content":"average"}]}}},"d":{"type":"internal","weight":446,"values":["d","m"],"children":{"d":{"type":"internal","weight":446,"values":["e","i"],"children":{"e":{"type":"leaf","weight":446,"entries":[{"key":"added","weight":446,"content":"added"}]},"i":{"type":"internal","weight":308,"values":["t"],"children":{"t":{"type":"internal","weight":308,"values":["i"],"children":{"i":{"type":"internal","weight":308,"values":["o"],"children":{"o":{"type":"internal","weight":308,"values":["n"],"children":{"n":{"type":"internal","weight":308,"values":["\ufdd0","a"],"children":{"\ufdd0":{"type":"leaf","weight":308,"entries":[{"key":"addition","weight":308,"content":"addition"}]},"a":{"type":"leaf","weight":164,"entries":[{"key":"additional","weight":164,"content":"additional"}]}}}}}}}}}}}}},"m":{"type":"leaf","weight":402,"entries":[{"key":"administration","weight":402,"content":"administration"}]}}},"p":{"type":"internal","weight":275,"values":["p"],"children":{"p":{"type":"internal","weight":275,"values":["e","a","r","l"],"children":{"e":{"type":"internal","weight":275,"values":["a"],"children":{"a":{"type":"internal","weight":275,"values":["r"],"children":{"r":{"type":"leaf","weight":275,"entries":[{"key":"appeared","weight":275,"content":"appeared"},{"key":"appear","weight":137,"content":"appear"}]}}}}},"a":{"type":"leaf","weight":195,"entries":[{"key":"apparently","weight":195,"content":"apparently"}]},"r":{"type":"leaf","weight":185,"entries":[{"key":"approach","weight":185,"content":"approach"}]},"l":{"type":"leaf","weight":39,"entries":[{"key":"applied","weight":39,"content":"applied"}]}}}}},"j":{"type":"leaf","weight":142,"entries":[{"key":"aj","weight":142,"content":"aj"}]},"u":{"type":"leaf","weight":118,"entries":[{"key":"audience","weight":118,"content":"audience"}]},"h":{"type":"leaf","weight":73,"entries":[{"key":"ahead","weight":73,"content":"ahead"}]}}},"i":{"type":"internal","weight":995,"values":["n","s","t","f","m","d",null],"children":{"n":{"type":"internal","weight":995,"values":["\ufdd0","t","f","d","c","s","v"],"children":{"\ufdd0":{"type":"leaf","weight":995,"entries":[{"key":"in","weight":995,"content":"in"}]},"t":{"type":"internal","weight":943,"values":["o","e"],"children":{"o":{"type":"leaf","weight":943,"entries":[{"key":"into","weight":943,"content":"into"}]},"e":{"type":"internal","weight":728,"values":["r"],"children":{"r":{"type":"internal","weight":728,"values":["e","n"],"children":{"e":{"type":"internal","weight":728,"values":["s"],"children":{"s":{"type":"internal","weight":728,"values":["t"],"children":{"t":{"type":"internal","weight":728,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":728,"entries":[{"key":"interest","weight":728,"content":"interest"}]},"e":{"type":"leaf","weight":24,"entries":[{"key":"interested","weight":24,"content":"interested"}]}}}}}}},"n":{"type":"leaf","weight":380,"entries":[{"key":"international","weight":380,"content":"international"}]}}}}}}},"f":{"type":"internal","weight":661,"values":["o","l"],"children":{"o":{"type":"leaf","weight":661,"entries":[{"key":"information","weight":661,"content":"information"}]},"l":{"type":"leaf","weight":254,"entries":[{"key":"influence","weight":254,"content":"influence"}]}}},"d":{"type":"internal","weight":617,"values":["i","u","e"],"children":{"i":{"type":"internal","weight":617,"values":["v","c"],"children":{"v":{"type":"leaf","weight":617,"entries":[{"key":"individual","weight":617,"content":"individual"}]},"c":{"type":"leaf","weight":59,"entries":[{"key":"indicated","weight":59,"content":"indicated"}]}}},"u":{"type":"internal","weight":432,"values":["s"],"children":{"s":{"type":"internal","weight":432,"values":["t"],"children":{"t":{"type":"internal","weight":432,"values":["r"],"children":{"r":{"type":"internal","weight":432,"values":["y","i"],"children":{"y":{"type":"leaf","weight":432,"entries":[{"key":"industry","weight":432,"content":"industry"}]},"i":{"type":"leaf","weight":323,"entries":[{"key":"industrial","weight":323,"content":"industrial"}]}}}}}}}}},"e":{"type":"leaf","weight":408,"entries":[{"key":"indeed","weight":408,"content":"indeed"}]}}},"c":{"type":"internal","weight":514,"values":["r","l","o"],"children":{"r":{"type":"internal","weight":514,"values":["e"],"children":{"e":{"type":"internal","weight":514,"values":["a"],"children":{"a":{"type":"internal","weight":514,"values":["s"],"children":{"s":{"type":"internal","weight":514,"values":["e"],"children":{"e":{"type":"internal","weight":514,"values":["\ufdd0","d"],"children":{"\ufdd0":{"type":"leaf","weight":514,"entries":[{"key":"increase","weight":514,"content":"increase"}]},"d":{"type":"leaf","weight":339,"entries":[{"key":"increased","weight":339,"content":"increased"}]}}}}}}}}}}},"l":{"type":"internal","weight":438,"values":["u"],"children":{"u":{"type":"internal","weight":438,"values":["d"],"children":{"d":{"type":"internal","weight":438,"values":["i","e"],"children":{"i":{"type":"leaf","weight":438,"entries":[{"key":"including","weight":438,"content":"including"}]},"e":{"type":"leaf","weight":102,"entries":[{"key":"include","weight":102,"content":"include"}]}}}}}}},"o":{"type":"leaf","weight":71,"entries":[{"key":"income","weight":71,"content":"income"}]}}},"s":{"type":"internal","weight":459,"values":["i","t"],"children":{"i":{"type":"leaf","weight":459,"entries":[{"key":"inside","weight":459,"content":"inside"}]},"t":{"type":"leaf","weight":452,"entries":[{"key":"instead","weight":452,"content":"instead"}]}}},"v":{"type":"leaf","weight":344,"entries":[{"key":"involved","weight":344,"content":"involved"}]}}},"s":{"type":"internal","weight":993,"values":["\ufdd0","l","s"],"children":{"\ufdd0":{"type":"leaf","weight":993,"entries":[{"key":"is","weight":993,"content":"is"}]},"l":{"type":"leaf","weight":424,"entries":[{"key":"island","weight":424,"content":"island"}]},"s":{"type":"leaf","weight":368,"entries":[{"key":"issue","weight":368,"content":"issue"}]}}},"t":{"type":"internal","weight":989,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":989,"entries":[{"key":"it","weight":989,"content":"it"}]},"s":{"type":"internal","weight":945,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":945,"entries":[{"key":"its","weight":945,"content":"its"}]},"e":{"type":"leaf","weight":702,"entries":[{"key":"itself","weight":702,"content":"itself"}]}}}}},"undefined":{"type":"leaf","weight":981,"entries":[{"key":"i","weight":981,"content":"i"}]},"f":{"type":"leaf","weight":952,"entries":[{"key":"if","weight":952,"content":"if"}]},"m":{"type":"internal","weight":755,"values":["p","m","a"],"children":{"p":{"type":"internal","weight":755,"values":["o"],"children":{"o":{"type":"internal","weight":755,"values":["r"],"children":{"r":{"type":"internal","weight":755,"values":["t"],"children":{"t":{"type":"internal","weight":755,"values":["a"],"children":{"a":{"type":"internal","weight":755,"values":["n"],"children":{"n":{"type":"internal","weight":755,"values":["t","c"],"children":{"t":{"type":"leaf","weight":755,"entries":[{"key":"important","weight":755,"content":"important"}]},"c":{"type":"leaf","weight":67,"entries":[{"key":"importance","weight":67,"content":"importance"}]}}}}}}}}}}}}},"m":{"type":"leaf","weight":184,"entries":[{"key":"immediately","weight":184,"content":"immediately"}]},"a":{"type":"leaf","weight":152,"entries":[{"key":"image","weight":152,"content":"image"}]}}},"d":{"type":"internal","weight":520,"values":["e"],"children":{"e":{"type":"internal","weight":520,"values":["a"],"children":{"a":{"type":"internal","weight":520,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":520,"entries":[{"key":"idea","weight":520,"content":"idea"}]},"s":{"type":"leaf","weight":319,"entries":[{"key":"ideas","weight":319,"content":"ideas"}]}}}}}}}}},"w":{"type":"internal","weight":992,"values":["a","i","h","e","o","r"],"children":{"a":{"type":"internal","weight":992,"values":["s","y","r","t","n","l","i"],"children":{"s":{"type":"internal","weight":992,"values":["\ufdd0","h"],"children":{"\ufdd0":{"type":"leaf","weight":992,"entries":[{"key":"was","weight":992,"content":"was"}]},"h":{"type":"leaf","weight":554,"entries":[{"key":"washington","weight":554,"content":"washington"}]}}},"y":{"type":"internal","weight":902,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":902,"entries":[{"key":"way","weight":902,"content":"way"}]},"s":{"type":"leaf","weight":217,"entries":[{"key":"ways","weight":217,"content":"ways"}]}}},"r":{"type":"leaf","weight":819,"entries":[{"key":"war","weight":819,"content":"war"}]},"t":{"type":"leaf","weight":813,"entries":[{"key":"water","weight":813,"content":"water"}]},"n":{"type":"internal","weight":727,"values":["t"],"children":{"t":{"type":"internal","weight":727,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":727,"entries":[{"key":"want","weight":727,"content":"want"}]},"e":{"type":"leaf","weight":598,"entries":[{"key":"wanted","weight":598,"content":"wanted"}]}}}}},"l":{"type":"internal","weight":395,"values":["l","k"],"children":{"l":{"type":"leaf","weight":395,"entries":[{"key":"wall","weight":395,"content":"wall"}]},"k":{"type":"leaf","weight":394,"entries":[{"key":"walked","weight":394,"content":"walked"}]}}},"i":{"type":"leaf","weight":81,"entries":[{"key":"waiting","weight":81,"content":"waiting"}]}}},"i":{"type":"internal","weight":988,"values":["t","l","f","d","n","s"],"children":{"t":{"type":"internal","weight":988,"values":["h"],"children":{"h":{"type":"internal","weight":988,"values":["\ufdd0","o","i"],"children":{"\ufdd0":{"type":"leaf","weight":988,"entries":[{"key":"with","weight":988,"content":"with"}]},"o":{"type":"leaf","weight":844,"entries":[{"key":"without","weight":844,"content":"without"}]},"i":{"type":"leaf","weight":744,"entries":[{"key":"within","weight":744,"content":"within"}]}}}}},"l":{"type":"internal","weight":954,"values":["l"],"children":{"l":{"type":"internal","weight":954,"values":["\ufdd0","i"],"children":{"\ufdd0":{"type":"leaf","weight":954,"entries":[{"key":"will","weight":954,"content":"will"}]},"i":{"type":"leaf","weight":347,"entries":[{"key":"william","weight":347,"content":"william"}]}}}}},"f":{"type":"leaf","weight":601,"entries":[{"key":"wife","weight":601,"content":"wife"}]},"d":{"type":"leaf","weight":192,"entries":[{"key":"wide","weight":192,"content":"wide"}]},"n":{"type":"leaf","weight":149,"entries":[{"key":"window","weight":149,"content":"window"}]},"s":{"type":"leaf","weight":77,"entries":[{"key":"wish","weight":77,"content":"wish"}]}}},"h":{"type":"internal","weight":970,"values":["i","e","o","a","y"],"children":{"i":{"type":"internal","weight":970,"values":["c","l","t"],"children":{"c":{"type":"leaf","weight":970,"entries":[{"key":"which","weight":970,"content":"which"}]},"l":{"type":"leaf","weight":867,"entries":[{"key":"while","weight":867,"content":"while"}]},"t":{"type":"leaf","weight":751,"entries":[{"key":"white","weight":751,"content":"white"}]}}},"e":{"type":"internal","weight":956,"values":["n","r","t"],"children":{"n":{"type":"leaf","weight":956,"entries":[{"key":"when","weight":956,"content":"when"}]},"r":{"type":"leaf","weight":904,"entries":[{"key":"where","weight":904,"content":"where"}]},"t":{"type":"leaf","weight":688,"entries":[{"key":"whether","weight":688,"content":"whether"}]}}},"o":{"type":"internal","weight":955,"values":["\ufdd0","l","s","m"],"children":{"\ufdd0":{"type":"leaf","weight":955,"entries":[{"key":"who","weight":955,"content":"who"}]},"l":{"type":"leaf","weight":705,"entries":[{"key":"whole","weight":705,"content":"whole"}]},"s":{"type":"leaf","weight":638,"entries":[{"key":"whose","weight":638,"content":"whose"}]},"m":{"type":"leaf","weight":341,"entries":[{"key":"whom","weight":341,"content":"whom"}]}}},"a":{"type":"internal","weight":947,"values":["t"],"children":{"t":{"type":"internal","weight":947,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":947,"entries":[{"key":"what","weight":947,"content":"what"}]},"e":{"type":"leaf","weight":91,"entries":[{"key":"whatever","weight":91,"content":"whatever"}]}}}}},"y":{"type":"leaf","weight":792,"entries":[{"key":"why","weight":792,"content":"why"}]}}},"e":{"type":"internal","weight":967,"values":["r","\ufdd0","l","n","e","s"],"children":{"r":{"type":"leaf","weight":967,"entries":[{"key":"were","weight":967,"content":"were"}]},"\ufdd0":{"type":"leaf","weight":960,"entries":[{"key":"we","weight":960,"content":"we"}]},"l":{"type":"leaf","weight":901,"entries":[{"key":"well","weight":901,"content":"well"}]},"n":{"type":"leaf","weight":834,"entries":[{"key":"went","weight":834,"content":"went"}]},"e":{"type":"internal","weight":668,"values":["k"],"children":{"k":{"type":"internal","weight":668,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":668,"entries":[{"key":"week","weight":668,"content":"week"}]},"s":{"type":"leaf","weight":299,"entries":[{"key":"weeks","weight":299,"content":"weeks"}]}}}}},"s":{"type":"internal","weight":612,"values":["t"],"children":{"t":{"type":"internal","weight":612,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":612,"entries":[{"key":"west","weight":612,"content":"west"}]},"e":{"type":"leaf","weight":282,"entries":[{"key":"western","weight":282,"content":"western"}]}}}}}}},"o":{"type":"internal","weight":962,"values":["u","r","m"],"children":{"u":{"type":"leaf","weight":962,"entries":[{"key":"would","weight":962,"content":"would"}]},"r":{"type":"internal","weight":886,"values":["l","k","d"],"children":{"l":{"type":"leaf","weight":886,"entries":[{"key":"world","weight":886,"content":"world"}]},"k":{"type":"internal","weight":881,"values":["\ufdd0","i","s","e"],"children":{"\ufdd0":{"type":"leaf","weight":881,"entries":[{"key":"work","weight":881,"content":"work"}]},"i":{"type":"leaf","weight":363,"entries":[{"key":"working","weight":363,"content":"working"}]},"s":{"type":"leaf","weight":237,"entries":[{"key":"works","weight":237,"content":"works"}]},"e":{"type":"leaf","weight":222,"entries":[{"key":"worked","weight":222,"content":"worked"}]}}},"d":{"type":"leaf","weight":665,"entries":[{"key":"words","weight":665,"content":"words"},{"key":"word","weight":664,"content":"word"}]}}},"m":{"type":"internal","weight":594,"values":["a","e"],"children":{"a":{"type":"leaf","weight":594,"entries":[{"key":"woman","weight":594,"content":"woman"}]},"e":{"type":"leaf","weight":518,"entries":[{"key":"women","weight":518,"content":"women"}]}}}}},"r":{"type":"internal","weight":481,"values":["o","i"],"children":{"o":{"type":"internal","weight":481,"values":["t","n"],"children":{"t":{"type":"leaf","weight":481,"entries":[{"key":"wrote","weight":481,"content":"wrote"}]},"n":{"type":"leaf","weight":227,"entries":[{"key":"wrong","weight":227,"content":"wrong"}]}}},"i":{"type":"internal","weight":373,"values":["t"],"children":{"t":{"type":"internal","weight":373,"values":["t","i","e"],"children":{"t":{"type":"leaf","weight":373,"entries":[{"key":"written","weight":373,"content":"written"}]},"i":{"type":"leaf","weight":139,"entries":[{"key":"writing","weight":139,"content":"writing"}]},"e":{"type":"leaf","weight":34,"entries":[{"key":"write","weight":34,"content":"write"}]}}}}}}}}},"h":{"type":"internal","weight":991,"values":["e","i","a","o","u"],"children":{"e":{"type":"internal","weight":991,"values":["\ufdd0","r","a","l"],"children":{"\ufdd0":{"type":"leaf","weight":991,"entries":[{"key":"he","weight":991,"content":"he"}]},"r":{"type":"internal","weight":966,"values":["\ufdd0","e","s"],"children":{"\ufdd0":{"type":"leaf","weight":966,"entries":[{"key":"her","weight":966,"content":"her"}]},"e":{"type":"leaf","weight":879,"entries":[{"key":"here","weight":879,"content":"here"}]},"s":{"type":"leaf","weight":196,"entries":[{"key":"herself","weight":196,"content":"herself"}]}}},"a":{"type":"internal","weight":802,"values":["d","r","v","l"],"children":{"d":{"type":"leaf","weight":802,"entries":[{"key":"head","weight":802,"content":"head"}]},"r":{"type":"internal","weight":634,"values":["d","t",null],"children":{"d":{"type":"leaf","weight":634,"entries":[{"key":"heard","weight":634,"content":"heard"}]},"t":{"type":"leaf","weight":453,"entries":[{"key":"heart","weight":453,"content":"heart"}]},"undefined":{"type":"leaf","weight":369,"entries":[{"key":"hear","weight":369,"content":"hear"}]}}},"v":{"type":"leaf","weight":84,"entries":[{"key":"heavy","weight":84,"content":"heavy"}]},"l":{"type":"leaf","weight":30,"entries":[{"key":"health","weight":30,"content":"health"}]}}},"l":{"type":"internal","weight":707,"values":["p","d"],"children":{"p":{"type":"leaf","weight":707,"entries":[{"key":"help","weight":707,"content":"help"}]},"d":{"type":"leaf","weight":653,"entries":[{"key":"held","weight":653,"content":"held"}]}}}}},"i":{"type":"internal","weight":986,"values":["s","m","g","t"],"children":{"s":{"type":"internal","weight":986,"values":["\ufdd0","t"],"children":{"\ufdd0":{"type":"leaf","weight":986,"entries":[{"key":"his","weight":986,"content":"his"}]},"t":{"type":"leaf","weight":687,"entries":[{"key":"history","weight":687,"content":"history"}]}}},"m":{"type":"internal","weight":959,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":959,"entries":[{"key":"him","weight":959,"content":"him"}]},"s":{"type":"leaf","weight":850,"entries":[{"key":"himself","weight":850,"content":"himself"}]}}},"g":{"type":"internal","weight":829,"values":["h"],"children":{"h":{"type":"internal","weight":829,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":829,"entries":[{"key":"high","weight":829,"content":"high"}]},"e":{"type":"leaf","weight":397,"entries":[{"key":"higher","weight":397,"content":"higher"}]}}}}},"t":{"type":"leaf","weight":114,"entries":[{"key":"hit","weight":114,"content":"hit"}]}}},"a":{"type":"internal","weight":979,"values":["d","v","s","n","l","r","p","i"],"children":{"d":{"type":"leaf","weight":979,"entries":[{"key":"had","weight":979,"content":"had"}]},"v":{"type":"internal","weight":973,"values":["e","i"],"children":{"e":{"type":"leaf","weight":973,"entries":[{"key":"have","weight":973,"content":"have"}]},"i":{"type":"leaf","weight":675,"entries":[{"key":"having","weight":675,"content":"having"}]}}},"s":{"type":"leaf","weight":957,"entries":[{"key":"has","weight":957,"content":"has"}]},"n":{"type":"internal","weight":806,"values":["d"],"children":{"d":{"type":"internal","weight":806,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":806,"entries":[{"key":"hand","weight":806,"content":"hand"}]},"s":{"type":"leaf","weight":691,"entries":[{"key":"hands","weight":691,"content":"hands"}]}}}}},"l":{"type":"internal","weight":669,"values":["f","l"],"children":{"f":{"type":"leaf","weight":669,"entries":[{"key":"half","weight":669,"content":"half"}]},"l":{"type":"leaf","weight":367,"entries":[{"key":"hall","weight":367,"content":"hall"}]}}},"r":{"type":"internal","weight":545,"values":["d"],"children":{"d":{"type":"internal","weight":545,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":545,"entries":[{"key":"hard","weight":545,"content":"hard"}]},"l":{"type":"leaf","weight":40,"entries":[{"key":"hardly","weight":40,"content":"hardly"}]}}}}},"p":{"type":"leaf","weight":353,"entries":[{"key":"happened","weight":353,"content":"happened"}]},"i":{"type":"leaf","weight":348,"entries":[{"key":"hair","weight":348,"content":"hair"}]}}},"o":{"type":"internal","weight":892,"values":["w","u","m","p","l","t","r","s"],"children":{"w":{"type":"internal","weight":892,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":892,"entries":[{"key":"how","weight":892,"content":"how"}]},"e":{"type":"leaf","weight":839,"entries":[{"key":"however","weight":839,"content":"however"}]}}},"u":{"type":"internal","weight":846,"values":["s","r"],"children":{"s":{"type":"leaf","weight":846,"entries":[{"key":"house","weight":846,"content":"house"}]},"r":{"type":"leaf","weight":454,"entries":[{"key":"hours","weight":454,"content":"hours"},{"key":"hour","weight":331,"content":"hour"}]}}},"m":{"type":"leaf","weight":838,"entries":[{"key":"home","weight":838,"content":"home"}]},"p":{"type":"leaf","weight":471,"entries":[{"key":"hope","weight":471,"content":"hope"}]},"l":{"type":"leaf","weight":428,"entries":[{"key":"hold","weight":428,"content":"hold"}]},"t":{"type":"internal","weight":238,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":238,"entries":[{"key":"hot","weight":238,"content":"hot"}]},"e":{"type":"leaf","weight":201,"entries":[{"key":"hotel","weight":201,"content":"hotel"}]}}},"r":{"type":"leaf","weight":138,"entries":[{"key":"horse","weight":138,"content":"horse"}]},"s":{"type":"leaf","weight":79,"entries":[{"key":"hospital","weight":79,"content":"hospital"}]}}},"u":{"type":"internal","weight":699,"values":["m","n","s"],"children":{"m":{"type":"leaf","weight":699,"entries":[{"key":"human","weight":699,"content":"human"}]},"n":{"type":"leaf","weight":434,"entries":[{"key":"hundred","weight":434,"content":"hundred"}]},"s":{"type":"leaf","weight":247,"entries":[{"key":"husband","weight":247,"content":"husband"}]}}}}},"f":{"type":"internal","weight":990,"values":["o","r","i","e","a","u","l"],"children":{"o":{"type":"internal","weight":990,"values":["r","u","l","o"],"children":{"r":{"type":"internal","weight":990,"values":["\ufdd0","m","c","e","w"],"children":{"\ufdd0":{"type":"leaf","weight":990,"entries":[{"key":"for","weight":990,"content":"for"}]},"m":{"type":"internal","weight":757,"values":["\ufdd0","e","s"],"children":{"\ufdd0":{"type":"leaf","weight":757,"entries":[{"key":"form","weight":757,"content":"form"}]},"e":{"type":"leaf","weight":242,"entries":[{"key":"former","weight":242,"content":"former"}]},"s":{"type":"leaf","weight":206,"entries":[{"key":"forms","weight":206,"content":"forms"}]}}},"c":{"type":"internal","weight":606,"values":["e"],"children":{"e":{"type":"internal","weight":606,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":606,"entries":[{"key":"force","weight":606,"content":"force"}]},"s":{"type":"leaf","weight":461,"entries":[{"key":"forces","weight":461,"content":"forces"}]}}}}},"e":{"type":"leaf","weight":390,"entries":[{"key":"foreign","weight":390,"content":"foreign"}]},"w":{"type":"leaf","weight":124,"entries":[{"key":"forward","weight":124,"content":"forward"}]}}},"u":{"type":"internal","weight":836,"values":["n","r"],"children":{"n":{"type":"leaf","weight":836,"entries":[{"key":"found","weight":836,"content":"found"}]},"r":{"type":"leaf","weight":747,"entries":[{"key":"four","weight":747,"content":"four"}]}}},"l":{"type":"internal","weight":588,"values":["l"],"children":{"l":{"type":"internal","weight":588,"values":["o"],"children":{"o":{"type":"internal","weight":588,"values":["w"],"children":{"w":{"type":"internal","weight":588,"values":["i","e"],"children":{"i":{"type":"leaf","weight":588,"entries":[{"key":"following","weight":588,"content":"following"}]},"e":{"type":"leaf","weight":443,"entries":[{"key":"followed","weight":443,"content":"followed"}]}}}}}}}}},"o":{"type":"leaf","weight":342,"entries":[{"key":"food","weight":342,"content":"food"}]}}},"r":{"type":"internal","weight":975,"values":["o","e","i"],"children":{"o":{"type":"internal","weight":975,"values":["m","n"],"children":{"m":{"type":"leaf","weight":975,"entries":[{"key":"from","weight":975,"content":"from"}]},"n":{"type":"leaf","weight":589,"entries":[{"key":"front","weight":589,"content":"front"}]}}},"e":{"type":"internal","weight":650,"values":["e","n"],"children":{"e":{"type":"internal","weight":650,"values":["\ufdd0","d"],"children":{"\ufdd0":{"type":"leaf","weight":650,"entries":[{"key":"free","weight":650,"content":"free"}]},"d":{"type":"leaf","weight":223,"entries":[{"key":"freedom","weight":223,"content":"freedom"}]}}},"n":{"type":"leaf","weight":288,"entries":[{"key":"french","weight":288,"content":"french"}]}}},"i":{"type":"internal","weight":406,"values":["e"],"children":{"e":{"type":"internal","weight":406,"values":["n"],"children":{"n":{"type":"internal","weight":406,"values":["d"],"children":{"d":{"type":"leaf","weight":406,"entries":[{"key":"friends","weight":406,"content":"friends"},{"key":"friend","weight":263,"content":"friend"}]}}}}}}}}},"i":{"type":"internal","weight":928,"values":["r","n","v","e","g","s"],"children":{"r":{"type":"internal","weight":928,"values":["s","e","m"],"children":{"s":{"type":"leaf","weight":928,"entries":[{"key":"first","weight":928,"content":"first"}]},"e":{"type":"leaf","weight":499,"entries":[{"key":"fire","weight":499,"content":"fire"}]},"m":{"type":"leaf","weight":68,"entries":[{"key":"firm","weight":68,"content":"firm"}]}}},"n":{"type":"internal","weight":789,"values":["d","a","e"],"children":{"d":{"type":"leaf","weight":789,"entries":[{"key":"find","weight":789,"content":"find"}]},"a":{"type":"internal","weight":508,"values":["l"],"children":{"l":{"type":"leaf","weight":508,"entries":[{"key":"finally","weight":508,"content":"finally"},{"key":"final","weight":384,"content":"final"}]}}},"e":{"type":"leaf","weight":400,"entries":[{"key":"fine","weight":400,"content":"fine"}]}}},"v":{"type":"leaf","weight":686,"entries":[{"key":"five","weight":686,"content":"five"}]},"e":{"type":"leaf","weight":666,"entries":[{"key":"field","weight":666,"content":"field"}]},"g":{"type":"internal","weight":560,"values":["u"],"children":{"u":{"type":"internal","weight":560,"values":["r"],"children":{"r":{"type":"internal","weight":560,"values":["e"],"children":{"e":{"type":"internal","weight":560,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":560,"entries":[{"key":"figure","weight":560,"content":"figure"}]},"s":{"type":"leaf","weight":100,"entries":[{"key":"figures","weight":100,"content":"figures"}]}}}}}}}}},"s":{"type":"leaf","weight":160,"entries":[{"key":"fiscal","weight":160,"content":"fiscal"}]}}},"e":{"type":"internal","weight":848,"values":["w","l","e","d","a"],"children":{"w":{"type":"leaf","weight":848,"entries":[{"key":"few","weight":848,"content":"few"}]},"l":{"type":"leaf","weight":742,"entries":[{"key":"felt","weight":742,"content":"felt"}]},"e":{"type":"internal","weight":681,"values":["t","l","d"],"children":{"t":{"type":"leaf","weight":681,"entries":[{"key":"feet","weight":681,"content":"feet"}]},"l":{"type":"internal","weight":580,"values":["\ufdd0","i"],"children":{"\ufdd0":{"type":"leaf","weight":580,"entries":[{"key":"feel","weight":580,"content":"feel"}]},"i":{"type":"leaf","weight":440,"entries":[{"key":"feeling","weight":440,"content":"feeling"}]}}},"d":{"type":"leaf","weight":174,"entries":[{"key":"feed","weight":174,"content":"feed"}]}}},"d":{"type":"leaf","weight":629,"entries":[{"key":"federal","weight":629,"content":"federal"}]},"a":{"type":"leaf","weight":215,"entries":[{"key":"fear","weight":215,"content":"fear"}]}}},"a":{"type":"internal","weight":814,"values":["c","r","m","t","l","i"],"children":{"c":{"type":"internal","weight":814,"values":["t","e"],"children":{"t":{"type":"internal","weight":814,"values":["\ufdd0","o"],"children":{"\ufdd0":{"type":"leaf","weight":814,"entries":[{"key":"fact","weight":814,"content":"fact"}]},"o":{"type":"leaf","weight":41,"entries":[{"key":"factors","weight":41,"content":"factors"}]}}},"e":{"type":"leaf","weight":760,"entries":[{"key":"face","weight":760,"content":"face"}]}}},"r":{"type":"internal","weight":803,"values":["\ufdd0","m"],"children":{"\ufdd0":{"type":"leaf","weight":803,"entries":[{"key":"far","weight":803,"content":"far"}]},"m":{"type":"leaf","weight":188,"entries":[{"key":"farm","weight":188,"content":"farm"}]}}},"m":{"type":"leaf","weight":729,"entries":[{"key":"family","weight":729,"content":"family"}]},"t":{"type":"leaf","weight":487,"entries":[{"key":"father","weight":487,"content":"father"}]},"l":{"type":"leaf","weight":343,"entries":[{"key":"fall","weight":343,"content":"fall"}]},"i":{"type":"leaf","weight":88,"entries":[{"key":"faith","weight":88,"content":"faith"}]}}},"u":{"type":"internal","weight":605,"values":["l","t","r","n"],"children":{"l":{"type":"leaf","weight":605,"entries":[{"key":"full","weight":605,"content":"full"}]},"t":{"type":"leaf","weight":599,"entries":[{"key":"future","weight":599,"content":"future"}]},"r":{"type":"leaf","weight":583,"entries":[{"key":"further","weight":583,"content":"further"}]},"n":{"type":"leaf","weight":105,"entries":[{"key":"function","weight":105,"content":"function"}]}}},"l":{"type":"leaf","weight":391,"entries":[{"key":"floor","weight":391,"content":"floor"}]}}},"b":{"type":"internal","weight":984,"values":["e","y","u","a","o","i","r","l",null],"children":{"e":{"type":"internal","weight":984,"values":["\ufdd0","e","f","c","t","i","s","g","h","l","y","a","d"],"children":{"\ufdd0":{"type":"leaf","weight":984,"entries":[{"key":"be","weight":984,"content":"be"}]},"e":{"type":"leaf","weight":958,"entries":[{"key":"been","weight":958,"content":"been"}]},"f":{"type":"leaf","weight":911,"entries":[{"key":"before","weight":911,"content":"before"}]},"c":{"type":"internal","weight":898,"values":["a","o"],"children":{"a":{"type":"internal","weight":898,"values":["u","m"],"children":{"u":{"type":"leaf","weight":898,"entries":[{"key":"because","weight":898,"content":"because"}]},"m":{"type":"leaf","weight":633,"entries":[{"key":"became","weight":633,"content":"became"}]}}},"o":{"type":"internal","weight":743,"values":["m"],"children":{"m":{"type":"internal","weight":743,"values":["e"],"children":{"e":{"type":"internal","weight":743,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":743,"entries":[{"key":"become","weight":743,"content":"become"}]},"s":{"type":"leaf","weight":17,"entries":[{"key":"becomes","weight":17,"content":"becomes"}]}}}}}}}}},"t":{"type":"internal","weight":877,"values":["w","t"],"children":{"w":{"type":"leaf","weight":877,"entries":[{"key":"between","weight":877,"content":"between"}]},"t":{"type":"leaf","weight":797,"entries":[{"key":"better","weight":797,"content":"better"}]}}},"i":{"type":"leaf","weight":874,"entries":[{"key":"being","weight":874,"content":"being"}]},"s":{"type":"leaf","weight":738,"entries":[{"key":"best","weight":738,"content":"best"}]},"g":{"type":"internal","weight":710,"values":["a","i"],"children":{"a":{"type":"leaf","weight":710,"entries":[{"key":"began","weight":710,"content":"began"}]},"i":{"type":"leaf","weight":416,"entries":[{"key":"beginning","weight":416,"content":"beginning"}]}}},"h":{"type":"leaf","weight":648,"entries":[{"key":"behind","weight":648,"content":"behind"}]},"l":{"type":"internal","weight":541,"values":["i","o"],"children":{"i":{"type":"leaf","weight":541,"entries":[{"key":"believe","weight":541,"content":"believe"}]},"o":{"type":"leaf","weight":333,"entries":[{"key":"below","weight":333,"content":"below"}]}}},"y":{"type":"leaf","weight":466,"entries":[{"key":"beyond","weight":466,"content":"beyond"}]},"a":{"type":"leaf","weight":214,"entries":[{"key":"beautiful","weight":214,"content":"beautiful"}]},"d":{"type":"leaf","weight":211,"entries":[{"key":"bed","weight":211,"content":"bed"}]}}},"y":{"type":"leaf","weight":982,"entries":[{"key":"by","weight":982,"content":"by"}]},"u":{"type":"internal","weight":976,"values":["t","s","i"],"children":{"t":{"type":"leaf","weight":976,"entries":[{"key":"but","weight":976,"content":"but"}]},"s":{"type":"leaf","weight":779,"entries":[{"key":"business","weight":779,"content":"business"}]},"i":{"type":"internal","weight":398,"values":["l"],"children":{"l":{"type":"internal","weight":398,"values":["d","t"],"children":{"d":{"type":"leaf","weight":398,"entries":[{"key":"building","weight":398,"content":"building"}]},"t":{"type":"leaf","weight":9,"entries":[{"key":"built","weight":9,"content":"built"}]}}}}}}},"a":{"type":"internal","weight":907,"values":["c","s","d","l"],"children":{"c":{"type":"leaf","weight":907,"entries":[{"key":"back","weight":907,"content":"back"}]},"s":{"type":"internal","weight":489,"values":["i","e"],"children":{"i":{"type":"internal","weight":489,"values":["s","c"],"children":{"s":{"type":"leaf","weight":489,"entries":[{"key":"basis","weight":489,"content":"basis"}]},"c":{"type":"leaf","weight":439,"entries":[{"key":"basic","weight":439,"content":"basic"}]}}},"e":{"type":"leaf","weight":154,"entries":[{"key":"based","weight":154,"content":"based"}]}}},"d":{"type":"leaf","weight":313,"entries":[{"key":"bad","weight":313,"content":"bad"}]},"l":{"type":"leaf","weight":78,"entries":[{"key":"ball","weight":78,"content":"ball"}]}}},"o":{"type":"internal","weight":876,"values":["t","d","y","a","o","r"],"children":{"t":{"type":"leaf","weight":876,"entries":[{"key":"both","weight":876,"content":"both"}]},"d":{"type":"leaf","weight":671,"entries":[{"key":"body","weight":671,"content":"body"}]},"y":{"type":"internal","weight":623,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":623,"entries":[{"key":"boy","weight":623,"content":"boy"}]},"s":{"type":"leaf","weight":324,"entries":[{"key":"boys","weight":324,"content":"boys"}]}}},"a":{"type":"leaf","weight":618,"entries":[{"key":"board","weight":618,"content":"board"}]},"o":{"type":"leaf","weight":528,"entries":[{"key":"book","weight":528,"content":"book"}]},"r":{"type":"leaf","weight":99,"entries":[{"key":"born","weight":99,"content":"born"}]}}},"i":{"type":"internal","weight":745,"values":["g","l"],"children":{"g":{"type":"leaf","weight":745,"entries":[{"key":"big","weight":745,"content":"big"}]},"l":{"type":"leaf","weight":322,"entries":[{"key":"bill","weight":322,"content":"bill"}]}}},"r":{"type":"internal","weight":640,"values":["o","i"],"children":{"o":{"type":"internal","weight":640,"values":["u","w"],"children":{"u":{"type":"leaf","weight":640,"entries":[{"key":"brought","weight":640,"content":"brought"}]},"w":{"type":"leaf","weight":467,"entries":[{"key":"brown","weight":467,"content":"brown"}]}}},"i":{"type":"internal","weight":392,"values":["n","t"],"children":{"n":{"type":"leaf","weight":392,"entries":[{"key":"bring","weight":392,"content":"bring"}]},"t":{"type":"leaf","weight":143,"entries":[{"key":"british","weight":143,"content":"british"}]}}}}},"l":{"type":"internal","weight":546,"values":["a","u","o"],"children":{"a":{"type":"leaf","weight":546,"entries":[{"key":"black","weight":546,"content":"black"}]},"u":{"type":"leaf","weight":316,"entries":[{"key":"blue","weight":316,"content":"blue"}]},"o":{"type":"leaf","weight":168,"entries":[{"key":"blood","weight":168,"content":"blood"}]}}},"undefined":{"type":"leaf","weight":32,"entries":[{"key":"b","weight":32,"content":"b"}]}}},"n":{"type":"internal","weight":978,"values":["o","e","u","i","a"],"children":{"o":{"type":"internal","weight":978,"values":["t","\ufdd0","w","r","n"],"children":{"t":{"type":"internal","weight":978,"values":["\ufdd0","h","e"],"children":{"\ufdd0":{"type":"leaf","weight":978,"entries":[{"key":"not","weight":978,"content":"not"}]},"h":{"type":"leaf","weight":795,"entries":[{"key":"nothing","weight":795,"content":"nothing"}]},"e":{"type":"leaf","weight":204,"entries":[{"key":"note","weight":204,"content":"note"}]}}},"\ufdd0":{"type":"leaf","weight":951,"entries":[{"key":"no","weight":951,"content":"no"}]},"w":{"type":"leaf","weight":925,"entries":[{"key":"now","weight":925,"content":"now"}]},"r":{"type":"internal","weight":555,"values":["t","\ufdd0","m"],"children":{"t":{"type":"leaf","weight":555,"entries":[{"key":"north","weight":555,"content":"north"}]},"\ufdd0":{"type":"leaf","weight":521,"entries":[{"key":"nor","weight":521,"content":"nor"}]},"m":{"type":"leaf","weight":277,"entries":[{"key":"normal","weight":277,"content":"normal"}]}}},"n":{"type":"leaf","weight":61,"entries":[{"key":"none","weight":61,"content":"none"}]}}},"e":{"type":"internal","weight":937,"values":["w","v","x","e","c","a","i","g"],"children":{"w":{"type":"leaf","weight":937,"entries":[{"key":"new","weight":937,"content":"new"}]},"v":{"type":"leaf","weight":872,"entries":[{"key":"never","weight":872,"content":"never"}]},"x":{"type":"leaf","weight":782,"entries":[{"key":"next","weight":782,"content":"next"}]},"e":{"type":"internal","weight":746,"values":["d"],"children":{"d":{"type":"internal","weight":746,"values":["\ufdd0","e","s"],"children":{"\ufdd0":{"type":"leaf","weight":746,"entries":[{"key":"need","weight":746,"content":"need"}]},"e":{"type":"leaf","weight":498,"entries":[{"key":"needed","weight":498,"content":"needed"}]},"s":{"type":"leaf","weight":365,"entries":[{"key":"needs","weight":365,"content":"needs"}]}}}}},"c":{"type":"leaf","weight":591,"entries":[{"key":"necessary","weight":591,"content":"necessary"}]},"a":{"type":"internal","weight":532,"values":["r"],"children":{"r":{"type":"internal","weight":532,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":532,"entries":[{"key":"near","weight":532,"content":"near"}]},"l":{"type":"leaf","weight":303,"entries":[{"key":"nearly","weight":303,"content":"nearly"}]}}}}},"i":{"type":"leaf","weight":307,"entries":[{"key":"neither","weight":307,"content":"neither"}]},"g":{"type":"leaf","weight":43,"entries":[{"key":"negro","weight":43,"content":"negro"}]}}},"u":{"type":"internal","weight":821,"values":["m","c"],"children":{"m":{"type":"internal","weight":821,"values":["b"],"children":{"b":{"type":"internal","weight":821,"values":["e"],"children":{"e":{"type":"internal","weight":821,"values":["r"],"children":{"r":{"type":"internal","weight":821,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":821,"entries":[{"key":"number","weight":821,"content":"number"}]},"s":{"type":"leaf","weight":199,"entries":[{"key":"numbers","weight":199,"content":"numbers"}]}}}}}}}}},"c":{"type":"leaf","weight":127,"entries":[{"key":"nuclear","weight":127,"content":"nuclear"}]}}},"i":{"type":"leaf","weight":794,"entries":[{"key":"night","weight":794,"content":"night"}]},"a":{"type":"internal","weight":764,"values":["t","m"],"children":{"t":{"type":"internal","weight":764,"values":["i","u"],"children":{"i":{"type":"internal","weight":764,"values":["o"],"children":{"o":{"type":"internal","weight":764,"values":["n"],"children":{"n":{"type":"internal","weight":764,"values":["a","s",null],"children":{"a":{"type":"leaf","weight":764,"entries":[{"key":"national","weight":764,"content":"national"}]},"s":{"type":"leaf","weight":462,"entries":[{"key":"nations","weight":462,"content":"nations"}]},"undefined":{"type":"leaf","weight":291,"entries":[{"key":"nation","weight":291,"content":"nation"}]}}}}}}},"u":{"type":"internal","weight":506,"values":["r"],"children":{"r":{"type":"internal","weight":506,"values":["e","a"],"children":{"e":{"type":"leaf","weight":506,"entries":[{"key":"nature","weight":506,"content":"nature"}]},"a":{"type":"leaf","weight":385,"entries":[{"key":"natural","weight":385,"content":"natural"}]}}}}}}},"m":{"type":"leaf","weight":695,"entries":[{"key":"name","weight":695,"content":"name"}]}}}}},"y":{"type":"internal","weight":968,"values":["o","e"],"children":{"o":{"type":"internal","weight":968,"values":["u","r"],"children":{"u":{"type":"internal","weight":968,"values":["\ufdd0","r","n"],"children":{"\ufdd0":{"type":"leaf","weight":968,"entries":[{"key":"you","weight":968,"content":"you"}]},"r":{"type":"leaf","weight":903,"entries":[{"key":"your","weight":903,"content":"your"}]},"n":{"type":"leaf","weight":775,"entries":[{"key":"young","weight":775,"content":"young"}]}}},"r":{"type":"leaf","weight":701,"entries":[{"key":"york","weight":701,"content":"york"}]}}},"e":{"type":"internal","weight":906,"values":["a","t","s"],"children":{"a":{"type":"internal","weight":906,"values":["r"],"children":{"r":{"type":"leaf","weight":906,"entries":[{"key":"years","weight":906,"content":"years"},{"key":"year","weight":861,"content":"year"}]}}},"t":{"type":"leaf","weight":801,"entries":[{"key":"yet","weight":801,"content":"yet"}]},"s":{"type":"leaf","weight":326,"entries":[{"key":"yes","weight":326,"content":"yes"}]}}}}},"s":{"type":"internal","weight":964,"values":["h","o","a","u","t","e","i","m","c","y","p","q","l"],"children":{"h":{"type":"internal","weight":964,"values":["e","o","a"],"children":{"e":{"type":"leaf","weight":964,"entries":[{"key":"she","weight":964,"content":"she"}]},"o":{"type":"internal","weight":899,"values":["u","w","r","t"],"children":{"u":{"type":"leaf","weight":899,"entries":[{"key":"should","weight":899,"content":"should"}]},"w":{"type":"internal","weight":689,"values":["\ufdd0","n","e"],"children":{"\ufdd0":{"type":"leaf","weight":689,"entries":[{"key":"show","weight":689,"content":"show"}]},"n":{"type":"leaf","weight":422,"entries":[{"key":"shown","weight":422,"content":"shown"}]},"e":{"type":"leaf","weight":306,"entries":[{"key":"showed","weight":306,"content":"showed"}]}}},"r":{"type":"leaf","weight":566,"entries":[{"key":"short","weight":566,"content":"short"}]},"t":{"type":"leaf","weight":92,"entries":[{"key":"shot","weight":92,"content":"shot"}]}}},"a":{"type":"leaf","weight":659,"entries":[{"key":"shall","weight":659,"content":"shall"}]}}},"o":{"type":"internal","weight":949,"values":["\ufdd0","m","c","u","o","n","r","v"],"children":{"\ufdd0":{"type":"leaf","weight":949,"entries":[{"key":"so","weight":949,"content":"so"}]},"m":{"type":"internal","weight":936,"values":["e"],"children":{"e":{"type":"internal","weight":936,"values":["\ufdd0","t","w"],"children":{"\ufdd0":{"type":"leaf","weight":936,"entries":[{"key":"some","weight":936,"content":"some"}]},"t":{"type":"internal","weight":815,"values":["h","i"],"children":{"h":{"type":"leaf","weight":815,"entries":[{"key":"something","weight":815,"content":"something"}]},"i":{"type":"leaf","weight":587,"entries":[{"key":"sometimes","weight":587,"content":"sometimes"}]}}},"w":{"type":"leaf","weight":209,"entries":[{"key":"somewhat","weight":209,"content":"somewhat"}]}}}}},"c":{"type":"internal","weight":769,"values":["i"],"children":{"i":{"type":"internal","weight":769,"values":["a","e"],"children":{"a":{"type":"leaf","weight":769,"entries":[{"key":"social","weight":769,"content":"social"}]},"e":{"type":"leaf","weight":615,"entries":[{"key":"society","weight":615,"content":"society"}]}}}}},"u":{"type":"internal","weight":620,"values":["t","n"],"children":{"t":{"type":"internal","weight":620,"values":["h"],"children":{"h":{"type":"internal","weight":620,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":620,"entries":[{"key":"south","weight":620,"content":"south"}]},"e":{"type":"leaf","weight":278,"entries":[{"key":"southern","weight":278,"content":"southern"}]}}}}},"n":{"type":"leaf","weight":548,"entries":[{"key":"sound","weight":548,"content":"sound"}]}}},"o":{"type":"leaf","weight":534,"entries":[{"key":"soon","weight":534,"content":"soon"}]},"n":{"type":"leaf","weight":421,"entries":[{"key":"son","weight":421,"content":"son"}]},"r":{"type":"leaf","weight":414,"entries":[{"key":"sort","weight":414,"content":"sort"}]},"v":{"type":"leaf","weight":224,"entries":[{"key":"soviet","weight":224,"content":"soviet"}]}}},"a":{"type":"internal","weight":948,"values":["i","m","y","w","t","l"],"children":{"i":{"type":"leaf","weight":948,"entries":[{"key":"said","weight":948,"content":"said"}]},"m":{"type":"leaf","weight":870,"entries":[{"key":"same","weight":870,"content":"same"}]},"y":{"type":"internal","weight":833,"values":["\ufdd0","s","i"],"children":{"\ufdd0":{"type":"leaf","weight":833,"entries":[{"key":"say","weight":833,"content":"say"}]},"s":{"type":"leaf","weight":538,"entries":[{"key":"says","weight":538,"content":"says"}]},"i":{"type":"leaf","weight":106,"entries":[{"key":"saying","weight":106,"content":"saying"}]}}},"w":{"type":"leaf","weight":739,"entries":[{"key":"saw","weight":739,"content":"saw"}]},"t":{"type":"leaf","weight":358,"entries":[{"key":"sat","weight":358,"content":"sat"}]},"l":{"type":"leaf","weight":262,"entries":[{"key":"sales","weight":262,"content":"sales"}]}}},"u":{"type":"internal","weight":924,"values":["c","r","p","b","d","m","n","g"],"children":{"c":{"type":"leaf","weight":924,"entries":[{"key":"such","weight":924,"content":"such"}]},"r":{"type":"internal","weight":652,"values":["e","f"],"children":{"e":{"type":"leaf","weight":652,"entries":[{"key":"sure","weight":652,"content":"sure"}]},"f":{"type":"leaf","weight":536,"entries":[{"key":"surface","weight":536,"content":"surface"}]}}},"p":{"type":"leaf","weight":478,"entries":[{"key":"support","weight":478,"content":"support"}]},"b":{"type":"leaf","weight":401,"entries":[{"key":"subject","weight":401,"content":"subject"}]},"d":{"type":"leaf","weight":370,"entries":[{"key":"suddenly","weight":370,"content":"suddenly"}]},"m":{"type":"leaf","weight":266,"entries":[{"key":"summer","weight":266,"content":"summer"}]},"n":{"type":"leaf","weight":89,"entries":[{"key":"sun","weight":89,"content":"sun"}]},"g":{"type":"leaf","weight":31,"entries":[{"key":"suggested","weight":31,"content":"suggested"}]}}},"t":{"type":"internal","weight":890,"values":["a","i","u","r","o","e"],"children":{"a":{"type":"internal","weight":890,"values":["t","r","g","n","f","y"],"children":{"t":{"type":"internal","weight":890,"values":["e","i"],"children":{"e":{"type":"internal","weight":890,"values":["\ufdd0","s","m"],"children":{"\ufdd0":{"type":"leaf","weight":890,"entries":[{"key":"state","weight":890,"content":"state"}]},"s":{"type":"leaf","weight":849,"entries":[{"key":"states","weight":849,"content":"states"}]},"m":{"type":"leaf","weight":302,"entries":[{"key":"statement","weight":302,"content":"statement"}]}}},"i":{"type":"leaf","weight":23,"entries":[{"key":"station","weight":23,"content":"station"}]}}},"r":{"type":"internal","weight":511,"values":["t"],"children":{"t":{"type":"leaf","weight":511,"entries":[{"key":"started","weight":511,"content":"started"},{"key":"start","weight":372,"content":"start"}]}}},"g":{"type":"leaf","weight":465,"entries":[{"key":"stage","weight":465,"content":"stage"}]},"n":{"type":"internal","weight":349,"values":["d"],"children":{"d":{"type":"internal","weight":349,"values":["\ufdd0","a"],"children":{"\ufdd0":{"type":"leaf","weight":349,"entries":[{"key":"stand","weight":349,"content":"stand"}]},"a":{"type":"leaf","weight":80,"entries":[{"key":"standard","weight":80,"content":"standard"}]}}}}},"f":{"type":"leaf","weight":103,"entries":[{"key":"staff","weight":103,"content":"staff"}]},"y":{"type":"leaf","weight":97,"entries":[{"key":"stay","weight":97,"content":"stay"}]}}},"i":{"type":"leaf","weight":885,"entries":[{"key":"still","weight":885,"content":"still"}]},"u":{"type":"internal","weight":631,"values":["d"],"children":{"d":{"type":"internal","weight":631,"values":["y","e","i"],"children":{"y":{"type":"leaf","weight":631,"entries":[{"key":"study","weight":631,"content":"study"}]},"e":{"type":"internal","weight":571,"values":["n"],"children":{"n":{"type":"internal","weight":571,"values":["t"],"children":{"t":{"type":"leaf","weight":571,"entries":[{"key":"students","weight":571,"content":"students"},{"key":"student","weight":244,"content":"student"}]}}}}},"i":{"type":"leaf","weight":3,"entries":[{"key":"studies","weight":3,"content":"studies"}]}}}}},"r":{"type":"internal","weight":626,"values":["e","o","a"],"children":{"e":{"type":"internal","weight":626,"values":["e","n","s"],"children":{"e":{"type":"leaf","weight":626,"entries":[{"key":"street","weight":626,"content":"street"}]},"n":{"type":"leaf","weight":281,"entries":[{"key":"strength","weight":281,"content":"strength"}]},"s":{"type":"leaf","weight":49,"entries":[{"key":"stress","weight":49,"content":"stress"}]}}},"o":{"type":"leaf","weight":544,"entries":[{"key":"strong","weight":544,"content":"strong"}]},"a":{"type":"leaf","weight":109,"entries":[{"key":"straight","weight":109,"content":"straight"}]}}},"o":{"type":"internal","weight":568,"values":["o","r","c","p"],"children":{"o":{"type":"leaf","weight":568,"entries":[{"key":"stood","weight":568,"content":"stood"}]},"r":{"type":"leaf","weight":371,"entries":[{"key":"story","weight":371,"content":"story"}]},"c":{"type":"leaf","weight":345,"entries":[{"key":"stock","weight":345,"content":"stock"}]},"p":{"type":"leaf","weight":231,"entries":[{"key":"stopped","weight":231,"content":"stopped"},{"key":"stop","weight":161,"content":"stop"}]}}},"e":{"type":"internal","weight":246,"values":["p"],"children":{"p":{"type":"internal","weight":246,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":246,"entries":[{"key":"step","weight":246,"content":"step"}]},"s":{"type":"leaf","weight":153,"entries":[{"key":"steps","weight":153,"content":"steps"}]}}}}}}},"e":{"type":"internal","weight":883,"values":["e","t","v","c","r","n","a"],"children":{"e":{"type":"internal","weight":883,"values":["\ufdd0","m","n"],"children":{"\ufdd0":{"type":"leaf","weight":883,"entries":[{"key":"see","weight":883,"content":"see"}]},"m":{"type":"internal","weight":731,"values":["e","s",null],"children":{"e":{"type":"leaf","weight":731,"entries":[{"key":"seemed","weight":731,"content":"seemed"}]},"s":{"type":"leaf","weight":649,"entries":[{"key":"seems","weight":649,"content":"seems"}]},"undefined":{"type":"leaf","weight":603,"entries":[{"key":"seem","weight":603,"content":"seem"}]}}},"n":{"type":"leaf","weight":674,"entries":[{"key":"seen","weight":674,"content":"seen"}]}}},"t":{"type":"leaf","weight":798,"entries":[{"key":"set","weight":798,"content":"set"}]},"v":{"type":"internal","weight":766,"values":["e"],"children":{"e":{"type":"internal","weight":766,"values":["r","n"],"children":{"r":{"type":"leaf","weight":766,"entries":[{"key":"several","weight":766,"content":"several"}]},"n":{"type":"leaf","weight":96,"entries":[{"key":"seven","weight":96,"content":"seven"}]}}}}},"c":{"type":"internal","weight":761,"values":["o","r","t"],"children":{"o":{"type":"leaf","weight":761,"entries":[{"key":"second","weight":761,"content":"second"}]},"r":{"type":"leaf","weight":505,"entries":[{"key":"secretary","weight":505,"content":"secretary"}]},"t":{"type":"leaf","weight":503,"entries":[{"key":"section","weight":503,"content":"section"}]}}},"r":{"type":"internal","weight":716,"values":["v","i"],"children":{"v":{"type":"internal","weight":716,"values":["i","e"],"children":{"i":{"type":"internal","weight":716,"values":["c"],"children":{"c":{"type":"internal","weight":716,"values":["e"],"children":{"e":{"type":"internal","weight":716,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":716,"entries":[{"key":"service","weight":716,"content":"service"}]},"s":{"type":"leaf","weight":290,"entries":[{"key":"services","weight":290,"content":"services"}]}}}}}}},"e":{"type":"leaf","weight":150,"entries":[{"key":"served","weight":150,"content":"served"},{"key":"serve","weight":50,"content":"serve"}]}}},"i":{"type":"internal","weight":239,"values":["e","o"],"children":{"e":{"type":"leaf","weight":239,"entries":[{"key":"series","weight":239,"content":"series"}]},"o":{"type":"leaf","weight":134,"entries":[{"key":"serious","weight":134,"content":"serious"}]}}}}},"n":{"type":"internal","weight":708,"values":["s","t"],"children":{"s":{"type":"leaf","weight":708,"entries":[{"key":"sense","weight":708,"content":"sense"}]},"t":{"type":"leaf","weight":328,"entries":[{"key":"sent","weight":328,"content":"sent"}]}}},"a":{"type":"leaf","weight":25,"entries":[{"key":"season","weight":25,"content":"season"}]}}},"i":{"type":"internal","weight":858,"values":["n","d","x","t","m","z"],"children":{"n":{"type":"internal","weight":858,"values":["c","g"],"children":{"c":{"type":"leaf","weight":858,"entries":[{"key":"since","weight":858,"content":"since"}]},"g":{"type":"leaf","weight":444,"entries":[{"key":"single","weight":444,"content":"single"}]}}},"d":{"type":"leaf","weight":770,"entries":[{"key":"side","weight":770,"content":"side"}]},"x":{"type":"leaf","weight":585,"entries":[{"key":"six","weight":585,"content":"six"}]},"t":{"type":"leaf","weight":525,"entries":[{"key":"situation","weight":525,"content":"situation"}]},"m":{"type":"internal","weight":437,"values":["p","i"],"children":{"p":{"type":"internal","weight":437,"values":["l"],"children":{"l":{"type":"internal","weight":437,"values":["y","e"],"children":{"y":{"type":"leaf","weight":437,"entries":[{"key":"simply","weight":437,"content":"simply"}]},"e":{"type":"leaf","weight":396,"entries":[{"key":"simple","weight":396,"content":"simple"}]}}}}},"i":{"type":"leaf","weight":388,"entries":[{"key":"similar","weight":388,"content":"similar"}]}}},"z":{"type":"leaf","weight":285,"entries":[{"key":"size","weight":285,"content":"size"}]}}},"m":{"type":"leaf","weight":837,"entries":[{"key":"small","weight":837,"content":"small"}]},"c":{"type":"internal","weight":827,"values":["h","i","e"],"children":{"h":{"type":"internal","weight":827,"values":["o"],"children":{"o":{"type":"internal","weight":827,"values":["o"],"children":{"o":{"type":"internal","weight":827,"values":["l"],"children":{"l":{"type":"internal","weight":827,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":827,"entries":[{"key":"school","weight":827,"content":"school"}]},"s":{"type":"leaf","weight":516,"entries":[{"key":"schools","weight":516,"content":"schools"}]}}}}}}}}},"i":{"type":"leaf","weight":249,"entries":[{"key":"science","weight":249,"content":"science"}]},"e":{"type":"leaf","weight":35,"entries":[{"key":"scene","weight":35,"content":"scene"}]}}},"y":{"type":"internal","weight":799,"values":["s"],"children":{"s":{"type":"internal","weight":799,"values":["t"],"children":{"t":{"type":"internal","weight":799,"values":["e"],"children":{"e":{"type":"internal","weight":799,"values":["m"],"children":{"m":{"type":"internal","weight":799,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":799,"entries":[{"key":"system","weight":799,"content":"system"}]},"s":{"type":"leaf","weight":233,"entries":[{"key":"systems","weight":233,"content":"systems"}]}}}}}}}}}}},"p":{"type":"internal","weight":637,"values":["e","a","i","r"],"children":{"e":{"type":"internal","weight":637,"values":["c","a","n"],"children":{"c":{"type":"internal","weight":637,"values":["i"],"children":{"i":{"type":"internal","weight":637,"values":["a","f"],"children":{"a":{"type":"leaf","weight":637,"entries":[{"key":"special","weight":637,"content":"special"}]},"f":{"type":"leaf","weight":126,"entries":[{"key":"specific","weight":126,"content":"specific"}]}}}}},"a":{"type":"leaf","weight":85,"entries":[{"key":"speak","weight":85,"content":"speak"}]},"n":{"type":"leaf","weight":13,"entries":[{"key":"spent","weight":13,"content":"spent"}]}}},"a":{"type":"leaf","weight":488,"entries":[{"key":"space","weight":488,"content":"space"}]},"i":{"type":"leaf","weight":485,"entries":[{"key":"spirit","weight":485,"content":"spirit"}]},"r":{"type":"leaf","weight":210,"entries":[{"key":"spring","weight":210,"content":"spring"}]}}},"q":{"type":"leaf","weight":317,"entries":[{"key":"square","weight":317,"content":"square"}]},"l":{"type":"leaf","weight":125,"entries":[{"key":"slowly","weight":125,"content":"slowly"}]}}},"m":{"type":"internal","weight":953,"values":["o","a","y","e","u","i"],"children":{"o":{"type":"internal","weight":953,"values":["r","s","n","m","t","d","v","u"],"children":{"r":{"type":"internal","weight":953,"values":["e","n","a"],"children":{"e":{"type":"leaf","weight":953,"entries":[{"key":"more","weight":953,"content":"more"}]},"n":{"type":"leaf","weight":563,"entries":[{"key":"morning","weight":563,"content":"morning"}]},"a":{"type":"leaf","weight":314,"entries":[{"key":"moral","weight":314,"content":"moral"}]}}},"s":{"type":"leaf","weight":917,"entries":[{"key":"most","weight":917,"content":"most"}]},"n":{"type":"internal","weight":656,"values":["e","t"],"children":{"e":{"type":"leaf","weight":656,"entries":[{"key":"money","weight":656,"content":"money"}]},"t":{"type":"internal","weight":502,"values":["h"],"children":{"h":{"type":"leaf","weight":502,"entries":[{"key":"months","weight":502,"content":"months"},{"key":"month","weight":240,"content":"month"}]}}}}},"m":{"type":"leaf","weight":632,"entries":[{"key":"moment","weight":632,"content":"moment"}]},"t":{"type":"leaf","weight":579,"entries":[{"key":"mother","weight":579,"content":"mother"}]},"d":{"type":"leaf","weight":533,"entries":[{"key":"modern","weight":533,"content":"modern"}]},"v":{"type":"internal","weight":479,"values":["e","i"],"children":{"e":{"type":"internal","weight":479,"values":["d","\ufdd0","m"],"children":{"d":{"type":"leaf","weight":479,"entries":[{"key":"moved","weight":479,"content":"moved"}]},"\ufdd0":{"type":"leaf","weight":436,"entries":[{"key":"move","weight":436,"content":"move"}]},"m":{"type":"leaf","weight":220,"entries":[{"key":"movement","weight":220,"content":"movement"}]}}},"i":{"type":"leaf","weight":111,"entries":[{"key":"moving","weight":111,"content":"moving"}]}}},"u":{"type":"leaf","weight":6,"entries":[{"key":"mouth","weight":6,"content":"mouth"}]}}},"a":{"type":"internal","weight":931,"values":["y","n","d","k","t","j","r","i","c"],"children":{"y":{"type":"internal","weight":931,"values":["\ufdd0","b"],"children":{"\ufdd0":{"type":"leaf","weight":931,"entries":[{"key":"may","weight":931,"content":"may"}]},"b":{"type":"leaf","weight":259,"entries":[{"key":"maybe","weight":259,"content":"maybe"}]}}},"n":{"type":"internal","weight":920,"values":["\ufdd0","y","n"],"children":{"\ufdd0":{"type":"leaf","weight":920,"entries":[{"key":"man","weight":920,"content":"man"}]},"y":{"type":"leaf","weight":912,"entries":[{"key":"many","weight":912,"content":"many"}]},"n":{"type":"leaf","weight":190,"entries":[{"key":"manner","weight":190,"content":"manner"}]}}},"d":{"type":"leaf","weight":916,"entries":[{"key":"made","weight":916,"content":"made"}]},"k":{"type":"internal","weight":887,"values":["e","i"],"children":{"e":{"type":"internal","weight":887,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":887,"entries":[{"key":"make","weight":887,"content":"make"}]},"s":{"type":"leaf","weight":445,"entries":[{"key":"makes","weight":445,"content":"makes"}]}}},"i":{"type":"leaf","weight":642,"entries":[{"key":"making","weight":642,"content":"making"}]}}},"t":{"type":"internal","weight":704,"values":["t","e"],"children":{"t":{"type":"leaf","weight":704,"entries":[{"key":"matter","weight":704,"content":"matter"}]},"e":{"type":"leaf","weight":463,"entries":[{"key":"material","weight":463,"content":"material"}]}}},"j":{"type":"leaf","weight":635,"entries":[{"key":"major","weight":635,"content":"major"}]},"r":{"type":"internal","weight":377,"values":["k","c","r"],"children":{"k":{"type":"leaf","weight":377,"entries":[{"key":"market","weight":377,"content":"market"}]},"c":{"type":"leaf","weight":166,"entries":[{"key":"march","weight":166,"content":"march"}]},"r":{"type":"leaf","weight":21,"entries":[{"key":"married","weight":21,"content":"married"}]}}},"i":{"type":"leaf","weight":155,"entries":[{"key":"main","weight":155,"content":"main"}]},"c":{"type":"leaf","weight":1,"entries":[{"key":"machine","weight":1,"content":"machine"}]}}},"y":{"type":"internal","weight":926,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":926,"entries":[{"key":"my","weight":926,"content":"my"}]},"s":{"type":"leaf","weight":230,"entries":[{"key":"myself","weight":230,"content":"myself"}]}}},"e":{"type":"internal","weight":919,"values":["\ufdd0","n","m","a","d","e","t","r"],"children":{"\ufdd0":{"type":"leaf","weight":919,"entries":[{"key":"me","weight":919,"content":"me"}]},"n":{"type":"leaf","weight":882,"entries":[{"key":"men","weight":882,"content":"men"}]},"m":{"type":"internal","weight":725,"values":["b"],"children":{"b":{"type":"internal","weight":725,"values":["e"],"children":{"e":{"type":"internal","weight":725,"values":["r"],"children":{"r":{"type":"leaf","weight":725,"entries":[{"key":"members","weight":725,"content":"members"},{"key":"member","weight":284,"content":"member"}]}}}}}}},"a":{"type":"internal","weight":706,"values":["n"],"children":{"n":{"type":"internal","weight":706,"values":["s","\ufdd0","i"],"children":{"s":{"type":"leaf","weight":706,"entries":[{"key":"means","weight":706,"content":"means"}]},"\ufdd0":{"type":"leaf","weight":535,"entries":[{"key":"mean","weight":535,"content":"mean"}]},"i":{"type":"leaf","weight":213,"entries":[{"key":"meaning","weight":213,"content":"meaning"}]}}}}},"d":{"type":"leaf","weight":405,"entries":[{"key":"medical","weight":405,"content":"medical"}]},"e":{"type":"internal","weight":393,"values":["t"],"children":{"t":{"type":"leaf","weight":393,"entries":[{"key":"meeting","weight":393,"content":"meeting"},{"key":"meet","weight":356,"content":"meet"}]}}},"t":{"type":"internal","weight":311,"values":["h",null],"children":{"h":{"type":"internal","weight":311,"values":["o"],"children":{"o":{"type":"internal","weight":311,"values":["d"],"children":{"d":{"type":"leaf","weight":311,"entries":[{"key":"methods","weight":311,"content":"methods"},{"key":"method","weight":309,"content":"method"}]}}}}},"undefined":{"type":"leaf","weight":251,"entries":[{"key":"met","weight":251,"content":"met"}]}}},"r":{"type":"leaf","weight":274,"entries":[{"key":"merely","weight":274,"content":"merely"}]}}},"u":{"type":"internal","weight":910,"values":["s","c"],"children":{"s":{"type":"internal","weight":910,"values":["t","i"],"children":{"t":{"type":"leaf","weight":910,"entries":[{"key":"must","weight":910,"content":"must"}]},"i":{"type":"leaf","weight":581,"entries":[{"key":"music","weight":581,"content":"music"}]}}},"c":{"type":"leaf","weight":905,"entries":[{"key":"much","weight":905,"content":"much"}]}}},"i":{"type":"internal","weight":864,"values":["g","n","s","l","d"],"children":{"g":{"type":"leaf","weight":864,"entries":[{"key":"might","weight":864,"content":"might"}]},"n":{"type":"internal","weight":726,"values":["d","u"],"children":{"d":{"type":"leaf","weight":726,"entries":[{"key":"mind","weight":726,"content":"mind"}]},"u":{"type":"leaf","weight":523,"entries":[{"key":"minutes","weight":523,"content":"minutes"}]}}},"s":{"type":"leaf","weight":639,"entries":[{"key":"miss","weight":639,"content":"miss"}]},"l":{"type":"internal","weight":565,"values":["i","l","e"],"children":{"i":{"type":"leaf","weight":565,"entries":[{"key":"military","weight":565,"content":"military"}]},"l":{"type":"leaf","weight":547,"entries":[{"key":"million","weight":547,"content":"million"}]},"e":{"type":"leaf","weight":450,"entries":[{"key":"miles","weight":450,"content":"miles"}]}}},"d":{"type":"leaf","weight":144,"entries":[{"key":"middle","weight":144,"content":"middle"}]}}}}},"u":{"type":"internal","weight":946,"values":["p","n","s"],"children":{"p":{"type":"internal","weight":946,"values":["\ufdd0","o"],"children":{"\ufdd0":{"type":"leaf","weight":946,"entries":[{"key":"up","weight":946,"content":"up"}]},"o":{"type":"leaf","weight":828,"entries":[{"key":"upon","weight":828,"content":"upon"}]}}},"n":{"type":"internal","weight":873,"values":["d","i","t"],"children":{"d":{"type":"internal","weight":873,"values":["e"],"children":{"e":{"type":"internal","weight":873,"values":["r"],"children":{"r":{"type":"internal","weight":873,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":873,"entries":[{"key":"under","weight":873,"content":"under"}]},"s":{"type":"internal","weight":283,"values":["t"],"children":{"t":{"type":"internal","weight":283,"values":["a"],"children":{"a":{"type":"internal","weight":283,"values":["n"],"children":{"n":{"type":"internal","weight":283,"values":["d"],"children":{"d":{"type":"internal","weight":283,"values":["\ufdd0","i"],"children":{"\ufdd0":{"type":"leaf","weight":283,"entries":[{"key":"understand","weight":283,"content":"understand"}]},"i":{"type":"leaf","weight":170,"entries":[{"key":"understanding","weight":170,"content":"understanding"}]}}}}}}}}}}}}}}}}},"i":{"type":"internal","weight":823,"values":["t","v","o"],"children":{"t":{"type":"leaf","weight":823,"entries":[{"key":"united","weight":823,"content":"united"},{"key":"unit","weight":10,"content":"unit"}]},"v":{"type":"leaf","weight":575,"entries":[{"key":"university","weight":575,"content":"university"}]},"o":{"type":"leaf","weight":483,"entries":[{"key":"union","weight":483,"content":"union"}]}}},"t":{"type":"leaf","weight":818,"entries":[{"key":"until","weight":818,"content":"until"}]}}},"s":{"type":"internal","weight":865,"values":["\ufdd0","e","u","i"],"children":{"\ufdd0":{"type":"leaf","weight":865,"entries":[{"key":"us","weight":865,"content":"us"}]},"e":{"type":"leaf","weight":853,"entries":[{"key":"used","weight":853,"content":"used"},{"key":"use","weight":847,"content":"use"}]},"u":{"type":"leaf","weight":556,"entries":[{"key":"usually","weight":556,"content":"usually"}]},"i":{"type":"leaf","weight":330,"entries":[{"key":"using","weight":330,"content":"using"}]}}}}},"c":{"type":"internal","weight":940,"values":["a","o","i","h","e","l","u",null],"children":{"a":{"type":"internal","weight":940,"values":["n","m","l","s","r","u"],"children":{"n":{"type":"internal","weight":940,"values":["\ufdd0","n"],"children":{"\ufdd0":{"type":"leaf","weight":940,"entries":[{"key":"can","weight":940,"content":"can"}]},"n":{"type":"leaf","weight":646,"entries":[{"key":"cannot","weight":646,"content":"cannot"}]}}},"m":{"type":"leaf","weight":855,"entries":[{"key":"came","weight":855,"content":"came"}]},"l":{"type":"internal","weight":791,"values":["l"],"children":{"l":{"type":"leaf","weight":791,"entries":[{"key":"called","weight":791,"content":"called"},{"key":"call","weight":500,"content":"call"}]}}},"s":{"type":"internal","weight":750,"values":["e"],"children":{"e":{"type":"internal","weight":750,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":750,"entries":[{"key":"case","weight":750,"content":"case"}]},"s":{"type":"leaf","weight":350,"entries":[{"key":"cases","weight":350,"content":"cases"}]}}}}},"r":{"type":"internal","weight":667,"values":["\ufdd0","e","r","s"],"children":{"\ufdd0":{"type":"leaf","weight":667,"entries":[{"key":"car","weight":667,"content":"car"}]},"e":{"type":"leaf","weight":407,"entries":[{"key":"care","weight":407,"content":"care"}]},"r":{"type":"leaf","weight":200,"entries":[{"key":"carried","weight":200,"content":"carried"}]},"s":{"type":"leaf","weight":90,"entries":[{"key":"cars","weight":90,"content":"cars"}]}}},"u":{"type":"leaf","weight":236,"entries":[{"key":"cause","weight":236,"content":"cause"}]}}},"o":{"type":"internal","weight":935,"values":["u","m","l","s","n","r","v"],"children":{"u":{"type":"internal","weight":935,"values":["l","r","n","p"],"children":{"l":{"type":"leaf","weight":935,"entries":[{"key":"could","weight":935,"content":"could"}]},"r":{"type":"internal","weight":820,"values":["s","t"],"children":{"s":{"type":"leaf","weight":820,"entries":[{"key":"course","weight":820,"content":"course"}]},"t":{"type":"leaf","weight":604,"entries":[{"key":"court","weight":604,"content":"court"}]}}},"n":{"type":"internal","weight":723,"values":["t","c"],"children":{"t":{"type":"internal","weight":723,"values":["r","y"],"children":{"r":{"type":"internal","weight":723,"values":["y","i"],"children":{"y":{"type":"leaf","weight":723,"entries":[{"key":"country","weight":723,"content":"country"}]},"i":{"type":"leaf","weight":360,"entries":[{"key":"countries","weight":360,"content":"countries"}]}}},"y":{"type":"leaf","weight":378,"entries":[{"key":"county","weight":378,"content":"county"}]}}},"c":{"type":"leaf","weight":11,"entries":[{"key":"council","weight":11,"content":"council"}]}}},"p":{"type":"leaf","weight":178,"entries":[{"key":"couple","weight":178,"content":"couple"}]}}},"m":{"type":"internal","weight":859,"values":["e","p","m","i"],"children":{"e":{"type":"internal","weight":859,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":859,"entries":[{"key":"come","weight":859,"content":"come"}]},"s":{"type":"leaf","weight":279,"entries":[{"key":"comes","weight":279,"content":"comes"}]}}},"p":{"type":"internal","weight":692,"values":["a","l"],"children":{"a":{"type":"leaf","weight":692,"entries":[{"key":"company","weight":692,"content":"company"}]},"l":{"type":"internal","weight":482,"values":["e"],"children":{"e":{"type":"internal","weight":482,"values":["t"],"children":{"t":{"type":"internal","weight":482,"values":["e"],"children":{"e":{"type":"internal","weight":482,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":482,"entries":[{"key":"complete","weight":482,"content":"complete"}]},"l":{"type":"leaf","weight":83,"entries":[{"key":"completely","weight":83,"content":"completely"}]}}}}}}}}}}},"m":{"type":"internal","weight":608,"values":["u","o","i"],"children":{"u":{"type":"leaf","weight":608,"entries":[{"key":"community","weight":608,"content":"community"}]},"o":{"type":"leaf","weight":593,"entries":[{"key":"common","weight":593,"content":"common"}]},"i":{"type":"internal","weight":427,"values":["t","s"],"children":{"t":{"type":"leaf","weight":427,"entries":[{"key":"committee","weight":427,"content":"committee"}]},"s":{"type":"leaf","weight":8,"entries":[{"key":"commission","weight":8,"content":"commission"}]}}}}},"i":{"type":"leaf","weight":456,"entries":[{"key":"coming","weight":456,"content":"coming"}]}}},"l":{"type":"internal","weight":657,"values":["l","d","o"],"children":{"l":{"type":"leaf","weight":657,"entries":[{"key":"college","weight":657,"content":"college"}]},"d":{"type":"leaf","weight":435,"entries":[{"key":"cold","weight":435,"content":"cold"}]},"o":{"type":"leaf","weight":294,"entries":[{"key":"color","weight":294,"content":"color"}]}}},"s":{"type":"internal","weight":602,"values":["t"],"children":{"t":{"type":"internal","weight":602,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":602,"entries":[{"key":"cost","weight":602,"content":"cost"}]},"s":{"type":"leaf","weight":468,"entries":[{"key":"costs","weight":468,"content":"costs"}]}}}}},"n":{"type":"internal","weight":592,"values":["t","d","g","s","c"],"children":{"t":{"type":"internal","weight":592,"values":["r","i"],"children":{"r":{"type":"leaf","weight":592,"entries":[{"key":"control","weight":592,"content":"control"}]},"i":{"type":"internal","weight":258,"values":["n"],"children":{"n":{"type":"internal","weight":258,"values":["u"],"children":{"u":{"type":"internal","weight":258,"values":["e"],"children":{"e":{"type":"leaf","weight":258,"entries":[{"key":"continued","weight":258,"content":"continued"},{"key":"continue","weight":54,"content":"continue"}]}}}}}}}}},"d":{"type":"leaf","weight":476,"entries":[{"key":"conditions","weight":476,"content":"conditions"}]},"g":{"type":"leaf","weight":364,"entries":[{"key":"congress","weight":364,"content":"congress"}]},"s":{"type":"internal","weight":361,"values":["i"],"children":{"i":{"type":"internal","weight":361,"values":["d"],"children":{"d":{"type":"internal","weight":361,"values":["e"],"children":{"e":{"type":"internal","weight":361,"values":["r"],"children":{"r":{"type":"leaf","weight":361,"entries":[{"key":"considered","weight":361,"content":"considered"},{"key":"consider","weight":212,"content":"consider"}]}}}}}}}}},"c":{"type":"leaf","weight":273,"entries":[{"key":"concerned","weight":273,"content":"concerned"}]}}},"r":{"type":"internal","weight":120,"values":["n","p"],"children":{"n":{"type":"leaf","weight":120,"entries":[{"key":"corner","weight":120,"content":"corner"}]},"p":{"type":"leaf","weight":76,"entries":[{"key":"corps","weight":76,"content":"corps"}]}}},"v":{"type":"leaf","weight":19,"entries":[{"key":"covered","weight":19,"content":"covered"}]}}},"i":{"type":"internal","weight":780,"values":["t"],"children":{"t":{"type":"internal","weight":780,"values":["y","i"],"children":{"y":{"type":"leaf","weight":780,"entries":[{"key":"city","weight":780,"content":"city"}]},"i":{"type":"leaf","weight":44,"entries":[{"key":"cities","weight":44,"content":"cities"}]}}}}},"h":{"type":"internal","weight":740,"values":["i","u","a","r","o"],"children":{"i":{"type":"internal","weight":740,"values":["l","e"],"children":{"l":{"type":"internal","weight":740,"values":["d"],"children":{"d":{"type":"leaf","weight":740,"entries":[{"key":"children","weight":740,"content":"children"},{"key":"child","weight":569,"content":"child"}]}}},"e":{"type":"leaf","weight":151,"entries":[{"key":"chief","weight":151,"content":"chief"}]}}},"u":{"type":"leaf","weight":737,"entries":[{"key":"church","weight":737,"content":"church"}]},"a":{"type":"internal","weight":619,"values":["n","r"],"children":{"n":{"type":"internal","weight":619,"values":["g","c"],"children":{"g":{"type":"internal","weight":619,"values":["e"],"children":{"e":{"type":"internal","weight":619,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":619,"entries":[{"key":"change","weight":619,"content":"change"}]},"s":{"type":"leaf","weight":248,"entries":[{"key":"changes","weight":248,"content":"changes"}]}}}}},"c":{"type":"leaf","weight":245,"entries":[{"key":"chance","weight":245,"content":"chance"}]}}},"r":{"type":"internal","weight":179,"values":["g","a"],"children":{"g":{"type":"leaf","weight":179,"entries":[{"key":"charge","weight":179,"content":"charge"}]},"a":{"type":"leaf","weight":145,"entries":[{"key":"character","weight":145,"content":"character"}]}}}}},"r":{"type":"leaf","weight":327,"entries":[{"key":"christian","weight":327,"content":"christian"}]},"o":{"type":"leaf","weight":104,"entries":[{"key":"choice","weight":104,"content":"choice"}]}}},"e":{"type":"internal","weight":713,"values":["r","n"],"children":{"r":{"type":"internal","weight":713,"values":["t"],"children":{"t":{"type":"internal","weight":713,"values":["a"],"children":{"a":{"type":"internal","weight":713,"values":["i"],"children":{"i":{"type":"internal","weight":713,"values":["n"],"children":{"n":{"type":"internal","weight":713,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":713,"entries":[{"key":"certain","weight":713,"content":"certain"}]},"l":{"type":"leaf","weight":318,"entries":[{"key":"certainly","weight":318,"content":"certainly"}]}}}}}}}}}}},"n":{"type":"internal","weight":595,"values":["t"],"children":{"t":{"type":"internal","weight":595,"values":["e","u","r",null],"children":{"e":{"type":"leaf","weight":595,"entries":[{"key":"center","weight":595,"content":"center"}]},"u":{"type":"leaf","weight":557,"entries":[{"key":"century","weight":557,"content":"century"}]},"r":{"type":"leaf","weight":420,"entries":[{"key":"central","weight":420,"content":"central"}]},"undefined":{"type":"leaf","weight":379,"entries":[{"key":"cent","weight":379,"content":"cent"}]}}}}}}},"l":{"type":"internal","weight":611,"values":["o","e","a","u"],"children":{"o":{"type":"internal","weight":611,"values":["s"],"children":{"s":{"type":"internal","weight":611,"values":["e"],"children":{"e":{"type":"internal","weight":611,"values":["\ufdd0","d"],"children":{"\ufdd0":{"type":"leaf","weight":611,"entries":[{"key":"close","weight":611,"content":"close"}]},"d":{"type":"leaf","weight":37,"entries":[{"key":"closed","weight":37,"content":"closed"}]}}}}}}},"e":{"type":"internal","weight":584,"values":["a"],"children":{"a":{"type":"internal","weight":584,"values":["r"],"children":{"r":{"type":"internal","weight":584,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":584,"entries":[{"key":"clear","weight":584,"content":"clear"}]},"l":{"type":"leaf","weight":218,"entries":[{"key":"clearly","weight":218,"content":"clearly"}]}}}}}}},"a":{"type":"leaf","weight":558,"entries":[{"key":"class","weight":558,"content":"class"}]},"u":{"type":"leaf","weight":336,"entries":[{"key":"club","weight":336,"content":"club"}]}}},"u":{"type":"internal","weight":509,"values":["t","r"],"children":{"t":{"type":"leaf","weight":509,"entries":[{"key":"cut","weight":509,"content":"cut"}]},"r":{"type":"leaf","weight":15,"entries":[{"key":"current","weight":15,"content":"current"}]}}},"undefined":{"type":"leaf","weight":171,"entries":[{"key":"c","weight":171,"content":"c"}]}}},"d":{"type":"internal","weight":929,"values":["o","i","a","u","e","r"],"children":{"o":{"type":"internal","weight":929,"values":["\ufdd0","w","e","n","o","i","u"],"children":{"\ufdd0":{"type":"leaf","weight":929,"entries":[{"key":"do","weight":929,"content":"do"}]},"w":{"type":"leaf","weight":900,"entries":[{"key":"down","weight":900,"content":"down"}]},"e":{"type":"leaf","weight":825,"entries":[{"key":"does","weight":825,"content":"does"}]},"n":{"type":"leaf","weight":719,"entries":[{"key":"done","weight":719,"content":"done"}]},"o":{"type":"leaf","weight":709,"entries":[{"key":"door","weight":709,"content":"door"}]},"i":{"type":"leaf","weight":410,"entries":[{"key":"doing","weight":410,"content":"doing"}]},"u":{"type":"leaf","weight":116,"entries":[{"key":"doubt","weight":116,"content":"doubt"}]}}},"i":{"type":"internal","weight":913,"values":["d","f","r","s","v"],"children":{"d":{"type":"leaf","weight":913,"entries":[{"key":"did","weight":913,"content":"did"}]},"f":{"type":"internal","weight":712,"values":["f"],"children":{"f":{"type":"internal","weight":712,"values":["e","i"],"children":{"e":{"type":"internal","weight":712,"values":["r"],"children":{"r":{"type":"internal","weight":712,"values":["e"],"children":{"e":{"type":"internal","weight":712,"values":["n"],"children":{"n":{"type":"internal","weight":712,"values":["t","c"],"children":{"t":{"type":"leaf","weight":712,"entries":[{"key":"different","weight":712,"content":"different"}]},"c":{"type":"leaf","weight":351,"entries":[{"key":"difference","weight":351,"content":"difference"}]}}}}}}}}},"i":{"type":"leaf","weight":399,"entries":[{"key":"difficult","weight":399,"content":"difficult"}]}}}}},"r":{"type":"internal","weight":304,"values":["e"],"children":{"e":{"type":"internal","weight":304,"values":["c"],"children":{"c":{"type":"internal","weight":304,"values":["t"],"children":{"t":{"type":"internal","weight":304,"values":["l","i",null],"children":{"l":{"type":"leaf","weight":304,"entries":[{"key":"directly","weight":304,"content":"directly"}]},"i":{"type":"leaf","weight":269,"entries":[{"key":"direction","weight":269,"content":"direction"}]},"undefined":{"type":"leaf","weight":234,"entries":[{"key":"direct","weight":234,"content":"direct"}]}}}}}}}}},"s":{"type":"internal","weight":272,"values":["t"],"children":{"t":{"type":"internal","weight":272,"values":["r","a"],"children":{"r":{"type":"leaf","weight":272,"entries":[{"key":"district","weight":272,"content":"district"}]},"a":{"type":"leaf","weight":60,"entries":[{"key":"distance","weight":60,"content":"distance"}]}}}}},"v":{"type":"leaf","weight":55,"entries":[{"key":"division","weight":55,"content":"division"}]}}},"a":{"type":"internal","weight":871,"values":["y","r","t","i"],"children":{"y":{"type":"internal","weight":871,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":871,"entries":[{"key":"day","weight":871,"content":"day"}]},"s":{"type":"leaf","weight":772,"entries":[{"key":"days","weight":772,"content":"days"}]}}},"r":{"type":"leaf","weight":490,"entries":[{"key":"dark","weight":490,"content":"dark"}]},"t":{"type":"internal","weight":447,"values":["a","e"],"children":{"a":{"type":"leaf","weight":447,"entries":[{"key":"data","weight":447,"content":"data"}]},"e":{"type":"leaf","weight":7,"entries":[{"key":"date","weight":7,"content":"date"}]}}},"i":{"type":"leaf","weight":180,"entries":[{"key":"daily","weight":180,"content":"daily"}]}}},"u":{"type":"internal","weight":845,"values":["r","e"],"children":{"r":{"type":"leaf","weight":845,"entries":[{"key":"during","weight":845,"content":"during"}]},"e":{"type":"leaf","weight":312,"entries":[{"key":"due","weight":312,"content":"due"}]}}},"e":{"type":"internal","weight":733,"values":["v","a","p","f","c","g","s","t","e","m",null],"children":{"v":{"type":"internal","weight":733,"values":["e"],"children":{"e":{"type":"internal","weight":733,"values":["l"],"children":{"l":{"type":"internal","weight":733,"values":["o"],"children":{"o":{"type":"internal","weight":733,"values":["p"],"children":{"p":{"type":"internal","weight":733,"values":["m","e"],"children":{"m":{"type":"leaf","weight":733,"entries":[{"key":"development","weight":733,"content":"development"}]},"e":{"type":"leaf","weight":430,"entries":[{"key":"developed","weight":430,"content":"developed"}]}}}}}}}}}}},"a":{"type":"internal","weight":673,"values":["t","d","l"],"children":{"t":{"type":"leaf","weight":673,"entries":[{"key":"death","weight":673,"content":"death"}]},"d":{"type":"leaf","weight":458,"entries":[{"key":"dead","weight":458,"content":"dead"}]},"l":{"type":"leaf","weight":321,"entries":[{"key":"deal","weight":321,"content":"deal"}]}}},"p":{"type":"leaf","weight":596,"entries":[{"key":"department","weight":596,"content":"department"}]},"f":{"type":"leaf","weight":426,"entries":[{"key":"defense","weight":426,"content":"defense"}]},"c":{"type":"internal","weight":301,"values":["i"],"children":{"i":{"type":"internal","weight":301,"values":["d","s"],"children":{"d":{"type":"leaf","weight":301,"entries":[{"key":"decided","weight":301,"content":"decided"}]},"s":{"type":"leaf","weight":148,"entries":[{"key":"decision","weight":148,"content":"decision"}]}}}}},"g":{"type":"leaf","weight":193,"entries":[{"key":"degree","weight":193,"content":"degree"}]},"undefined":{"type":"leaf","weight":173,"entries":[{"key":"de","weight":173,"content":"de"}]},"s":{"type":"internal","weight":163,"values":["c","i","p"],"children":{"c":{"type":"leaf","weight":163,"entries":[{"key":"described","weight":163,"content":"described"}]},"i":{"type":"internal","weight":108,"values":["g"],"children":{"g":{"type":"internal","weight":108,"values":["n"],"children":{"n":{"type":"internal","weight":108,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":108,"entries":[{"key":"design","weight":108,"content":"design"}]},"e":{"type":"leaf","weight":64,"entries":[{"key":"designed","weight":64,"content":"designed"}]}}}}}}},"p":{"type":"leaf","weight":20,"entries":[{"key":"despite","weight":20,"content":"despite"}]}}},"t":{"type":"internal","weight":147,"values":["e"],"children":{"e":{"type":"internal","weight":147,"values":["r"],"children":{"r":{"type":"internal","weight":147,"values":["m"],"children":{"m":{"type":"internal","weight":147,"values":["i"],"children":{"i":{"type":"internal","weight":147,"values":["n"],"children":{"n":{"type":"internal","weight":147,"values":["e"],"children":{"e":{"type":"leaf","weight":147,"entries":[{"key":"determined","weight":147,"content":"determined"},{"key":"determine","weight":51,"content":"determine"}]}}}}}}}}}}}}},"e":{"type":"leaf","weight":72,"entries":[{"key":"deep","weight":72,"content":"deep"}]},"m":{"type":"leaf","weight":69,"entries":[{"key":"democratic","weight":69,"content":"democratic"}]}}},"r":{"type":"leaf","weight":26,"entries":[{"key":"drive","weight":26,"content":"drive"}]}}},"l":{"type":"internal","weight":923,"values":["i","o","a","e"],"children":{"i":{"type":"internal","weight":923,"values":["k","t","f","g","n","v","s","m"],"children":{"k":{"type":"internal","weight":923,"values":["e"],"children":{"e":{"type":"internal","weight":923,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":923,"entries":[{"key":"like","weight":923,"content":"like"}]},"l":{"type":"leaf","weight":362,"entries":[{"key":"likely","weight":362,"content":"likely"}]}}}}},"t":{"type":"internal","weight":891,"values":["t","e"],"children":{"t":{"type":"leaf","weight":891,"entries":[{"key":"little","weight":891,"content":"little"}]},"e":{"type":"leaf","weight":261,"entries":[{"key":"literature","weight":261,"content":"literature"}]}}},"f":{"type":"leaf","weight":875,"entries":[{"key":"life","weight":875,"content":"life"}]},"g":{"type":"leaf","weight":730,"entries":[{"key":"light","weight":730,"content":"light"}]},"n":{"type":"internal","weight":697,"values":["e"],"children":{"e":{"type":"internal","weight":697,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":697,"entries":[{"key":"line","weight":697,"content":"line"}]},"s":{"type":"leaf","weight":530,"entries":[{"key":"lines","weight":530,"content":"lines"}]}}}}},"v":{"type":"internal","weight":513,"values":["i","e"],"children":{"i":{"type":"leaf","weight":513,"entries":[{"key":"living","weight":513,"content":"living"}]},"e":{"type":"internal","weight":470,"values":["\ufdd0","d"],"children":{"\ufdd0":{"type":"leaf","weight":470,"entries":[{"key":"live","weight":470,"content":"live"}]},"d":{"type":"leaf","weight":122,"entries":[{"key":"lived","weight":122,"content":"lived"}]}}}}},"s":{"type":"leaf","weight":260,"entries":[{"key":"list","weight":260,"content":"list"}]},"m":{"type":"leaf","weight":38,"entries":[{"key":"limited","weight":38,"content":"limited"}]}}},"o":{"type":"internal","weight":880,"values":["n","o","c","v","w","s","t"],"children":{"n":{"type":"internal","weight":880,"values":["g"],"children":{"g":{"type":"internal","weight":880,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":880,"entries":[{"key":"long","weight":880,"content":"long"}]},"e":{"type":"leaf","weight":510,"entries":[{"key":"longer","weight":510,"content":"longer"}]}}}}},"o":{"type":"internal","weight":788,"values":["k"],"children":{"k":{"type":"internal","weight":788,"values":["\ufdd0","e","i"],"children":{"\ufdd0":{"type":"leaf","weight":788,"entries":[{"key":"look","weight":788,"content":"look"}]},"e":{"type":"leaf","weight":753,"entries":[{"key":"looked","weight":753,"content":"looked"}]},"i":{"type":"leaf","weight":448,"entries":[{"key":"looking","weight":448,"content":"looking"}]}}}}},"c":{"type":"leaf","weight":690,"entries":[{"key":"local","weight":690,"content":"local"}]},"v":{"type":"leaf","weight":609,"entries":[{"key":"love","weight":609,"content":"love"}]},"w":{"type":"internal","weight":451,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":451,"entries":[{"key":"low","weight":451,"content":"low"}]},"e":{"type":"leaf","weight":187,"entries":[{"key":"lower","weight":187,"content":"lower"}]}}},"s":{"type":"leaf","weight":449,"entries":[{"key":"lost","weight":449,"content":"lost"}]},"t":{"type":"leaf","weight":207,"entries":[{"key":"lot","weight":207,"content":"lot"}]}}},"a":{"type":"internal","weight":866,"values":["s","t","r","w","n","b","y","c"],"children":{"s":{"type":"leaf","weight":866,"entries":[{"key":"last","weight":866,"content":"last"}]},"t":{"type":"internal","weight":785,"values":["e","t"],"children":{"e":{"type":"leaf","weight":785,"entries":[{"key":"later","weight":785,"content":"later"},{"key":"late","weight":472,"content":"late"}]},"t":{"type":"leaf","weight":115,"entries":[{"key":"latter","weight":115,"content":"latter"}]}}},"r":{"type":"internal","weight":748,"values":["g"],"children":{"g":{"type":"internal","weight":748,"values":["e"],"children":{"e":{"type":"internal","weight":748,"values":["\ufdd0","r"],"children":{"\ufdd0":{"type":"leaf","weight":748,"entries":[{"key":"large","weight":748,"content":"large"}]},"r":{"type":"leaf","weight":182,"entries":[{"key":"larger","weight":182,"content":"larger"}]}}}}}}},"w":{"type":"leaf","weight":698,"entries":[{"key":"law","weight":698,"content":"law"}]},"n":{"type":"internal","weight":582,"values":["d","g"],"children":{"d":{"type":"leaf","weight":582,"entries":[{"key":"land","weight":582,"content":"land"}]},"g":{"type":"leaf","weight":74,"entries":[{"key":"language","weight":74,"content":"language"}]}}},"b":{"type":"leaf","weight":354,"entries":[{"key":"labor","weight":354,"content":"labor"}]},"y":{"type":"leaf","weight":289,"entries":[{"key":"lay","weight":289,"content":"lay"}]},"c":{"type":"leaf","weight":82,"entries":[{"key":"lack","weight":82,"content":"lack"}]}}},"e":{"type":"internal","weight":822,"values":["f","s","t","a","v","d","n"],"children":{"f":{"type":"leaf","weight":822,"entries":[{"key":"left","weight":822,"content":"left"}]},"s":{"type":"leaf","weight":809,"entries":[{"key":"less","weight":809,"content":"less"}]},"t":{"type":"internal","weight":774,"values":["\ufdd0","t"],"children":{"\ufdd0":{"type":"leaf","weight":774,"entries":[{"key":"let","weight":774,"content":"let"}]},"t":{"type":"internal","weight":335,"values":["e"],"children":{"e":{"type":"internal","weight":335,"values":["r"],"children":{"r":{"type":"internal","weight":335,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":335,"entries":[{"key":"letter","weight":335,"content":"letter"}]},"s":{"type":"leaf","weight":128,"entries":[{"key":"letters","weight":128,"content":"letters"}]}}}}}}}}},"a":{"type":"internal","weight":735,"values":["s","v","d","r"],"children":{"s":{"type":"leaf","weight":735,"entries":[{"key":"least","weight":735,"content":"least"}]},"v":{"type":"leaf","weight":553,"entries":[{"key":"leave","weight":553,"content":"leave"}]},"d":{"type":"internal","weight":235,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":235,"entries":[{"key":"lead","weight":235,"content":"lead"}]},"e":{"type":"leaf","weight":53,"entries":[{"key":"leaders","weight":53,"content":"leaders"}]}}},"r":{"type":"leaf","weight":136,"entries":[{"key":"learned","weight":136,"content":"learned"}]}}},"v":{"type":"leaf","weight":573,"entries":[{"key":"level","weight":573,"content":"level"}]},"d":{"type":"leaf","weight":253,"entries":[{"key":"led","weight":253,"content":"led"}]},"n":{"type":"leaf","weight":129,"entries":[{"key":"length","weight":129,"content":"length"}]}}}}},"e":{"type":"internal","weight":918,"values":["v","a","n","y","x","i","c","d","f","l","q","s","u"],"children":{"v":{"type":"internal","weight":918,"values":["e","i"],"children":{"e":{"type":"internal","weight":918,"values":["n","r"],"children":{"n":{"type":"internal","weight":918,"values":["\ufdd0","i"],"children":{"\ufdd0":{"type":"leaf","weight":918,"entries":[{"key":"even","weight":918,"content":"even"}]},"i":{"type":"leaf","weight":257,"entries":[{"key":"evening","weight":257,"content":"evening"}]}}},"r":{"type":"internal","weight":826,"values":["y","\ufdd0"],"children":{"y":{"type":"internal","weight":826,"values":["\ufdd0","t"],"children":{"\ufdd0":{"type":"leaf","weight":826,"entries":[{"key":"every","weight":826,"content":"every"}]},"t":{"type":"leaf","weight":492,"entries":[{"key":"everything","weight":492,"content":"everything"}]}}},"\ufdd0":{"type":"leaf","weight":736,"entries":[{"key":"ever","weight":736,"content":"ever"}]}}}}},"i":{"type":"leaf","weight":549,"entries":[{"key":"evidence","weight":549,"content":"evidence"}]}}},"a":{"type":"internal","weight":897,"values":["c","r","s"],"children":{"c":{"type":"leaf","weight":897,"entries":[{"key":"each","weight":897,"content":"each"}]},"r":{"type":"internal","weight":752,"values":["l","t"],"children":{"l":{"type":"internal","weight":752,"values":["y","i"],"children":{"y":{"type":"leaf","weight":752,"entries":[{"key":"early","weight":752,"content":"early"}]},"i":{"type":"leaf","weight":340,"entries":[{"key":"earlier","weight":340,"content":"earlier"}]}}},"t":{"type":"leaf","weight":359,"entries":[{"key":"earth","weight":359,"content":"earth"}]}}},"s":{"type":"internal","weight":486,"values":["t","y","i"],"children":{"t":{"type":"leaf","weight":486,"entries":[{"key":"east","weight":486,"content":"east"}]},"y":{"type":"leaf","weight":191,"entries":[{"key":"easy","weight":191,"content":"easy"}]},"i":{"type":"leaf","weight":45,"entries":[{"key":"easily","weight":45,"content":"easily"}]}}}}},"n":{"type":"internal","weight":805,"values":["o","d","g","t"],"children":{"o":{"type":"leaf","weight":805,"entries":[{"key":"enough","weight":805,"content":"enough"}]},"d":{"type":"leaf","weight":793,"entries":[{"key":"end","weight":793,"content":"end"}]},"g":{"type":"internal","weight":517,"values":["l"],"children":{"l":{"type":"internal","weight":517,"values":["i","a"],"children":{"i":{"type":"leaf","weight":517,"entries":[{"key":"english","weight":517,"content":"english"}]},"a":{"type":"leaf","weight":375,"entries":[{"key":"england","weight":375,"content":"england"}]}}}}},"t":{"type":"leaf","weight":357,"entries":[{"key":"entire","weight":357,"content":"entire"}]}}},"y":{"type":"internal","weight":790,"values":["e"],"children":{"e":{"type":"leaf","weight":790,"entries":[{"key":"eyes","weight":790,"content":"eyes"},{"key":"eye","weight":177,"content":"eye"}]}}},"x":{"type":"internal","weight":694,"values":["a","p","c","t","i"],"children":{"a":{"type":"internal","weight":694,"values":["m","c"],"children":{"m":{"type":"leaf","weight":694,"entries":[{"key":"example","weight":694,"content":"example"}]},"c":{"type":"leaf","weight":5,"entries":[{"key":"exactly","weight":5,"content":"exactly"}]}}},"p":{"type":"internal","weight":672,"values":["e"],"children":{"e":{"type":"internal","weight":672,"values":["r","c"],"children":{"r":{"type":"leaf","weight":672,"entries":[{"key":"experience","weight":672,"content":"experience"}]},"c":{"type":"internal","weight":497,"values":["t"],"children":{"t":{"type":"leaf","weight":497,"entries":[{"key":"expected","weight":497,"content":"expected"},{"key":"expect","weight":56,"content":"expect"}]}}}}}}},"c":{"type":"leaf","weight":480,"entries":[{"key":"except","weight":480,"content":"except"}]},"t":{"type":"leaf","weight":86,"entries":[{"key":"extent","weight":86,"content":"extent"}]},"i":{"type":"leaf","weight":52,"entries":[{"key":"existence","weight":52,"content":"existence"}]}}},"i":{"type":"internal","weight":684,"values":["t","g"],"children":{"t":{"type":"leaf","weight":684,"entries":[{"key":"either","weight":684,"content":"either"}]},"g":{"type":"leaf","weight":16,"entries":[{"key":"eight","weight":16,"content":"eight"}]}}},"c":{"type":"leaf","weight":624,"entries":[{"key":"economic","weight":624,"content":"economic"}]},"d":{"type":"leaf","weight":574,"entries":[{"key":"education","weight":574,"content":"education"}]},"f":{"type":"internal","weight":570,"values":["f"],"children":{"f":{"type":"internal","weight":570,"values":["e","o"],"children":{"e":{"type":"internal","weight":570,"values":["c"],"children":{"c":{"type":"internal","weight":570,"values":["t"],"children":{"t":{"type":"internal","weight":570,"values":["\ufdd0","i","s"],"children":{"\ufdd0":{"type":"leaf","weight":570,"entries":[{"key":"effect","weight":570,"content":"effect"}]},"i":{"type":"leaf","weight":226,"entries":[{"key":"effective","weight":226,"content":"effective"}]},"s":{"type":"leaf","weight":63,"entries":[{"key":"effects","weight":63,"content":"effects"}]}}}}}}},"o":{"type":"internal","weight":332,"values":["r"],"children":{"r":{"type":"internal","weight":332,"values":["t"],"children":{"t":{"type":"internal","weight":332,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":332,"entries":[{"key":"effort","weight":332,"content":"effort"}]},"s":{"type":"leaf","weight":205,"entries":[{"key":"efforts","weight":205,"content":"efforts"}]}}}}}}}}}}},"l":{"type":"internal","weight":469,"values":["s","e"],"children":{"s":{"type":"leaf","weight":469,"entries":[{"key":"else","weight":469,"content":"else"}]},"e":{"type":"leaf","weight":46,"entries":[{"key":"elements","weight":46,"content":"elements"}]}}},"q":{"type":"leaf","weight":425,"entries":[{"key":"equipment","weight":425,"content":"equipment"}]},"s":{"type":"internal","weight":403,"values":["p","t"],"children":{"p":{"type":"leaf","weight":403,"entries":[{"key":"especially","weight":403,"content":"especially"}]},"t":{"type":"leaf","weight":58,"entries":[{"key":"established","weight":58,"content":"established"}]}}},"u":{"type":"leaf","weight":141,"entries":[{"key":"europe","weight":141,"content":"europe"}]}}},"j":{"type":"internal","weight":896,"values":["u","o"],"children":{"u":{"type":"internal","weight":896,"values":["s"],"children":{"s":{"type":"internal","weight":896,"values":["t"],"children":{"t":{"type":"internal","weight":896,"values":["\ufdd0","i"],"children":{"\ufdd0":{"type":"leaf","weight":896,"entries":[{"key":"just","weight":896,"content":"just"}]},"i":{"type":"leaf","weight":117,"entries":[{"key":"justice","weight":117,"content":"justice"}]}}}}}}},"o":{"type":"internal","weight":749,"values":["h","b"],"children":{"h":{"type":"leaf","weight":749,"entries":[{"key":"john","weight":749,"content":"john"}]},"b":{"type":"leaf","weight":616,"entries":[{"key":"job","weight":616,"content":"job"}]}}}}},"p":{"type":"internal","weight":894,"values":["e","l","a","u","o","r","i","h"],"children":{"e":{"type":"internal","weight":894,"values":["o","r","a"],"children":{"o":{"type":"leaf","weight":894,"entries":[{"key":"people","weight":894,"content":"people"}]},"r":{"type":"internal","weight":759,"values":["\ufdd0","h","i","s","f"],"children":{"\ufdd0":{"type":"leaf","weight":759,"entries":[{"key":"per","weight":759,"content":"per"}]},"h":{"type":"leaf","weight":703,"entries":[{"key":"perhaps","weight":703,"content":"perhaps"}]},"i":{"type":"leaf","weight":655,"entries":[{"key":"period","weight":655,"content":"period"}]},"s":{"type":"internal","weight":524,"values":["o"],"children":{"o":{"type":"internal","weight":524,"values":["n"],"children":{"n":{"type":"internal","weight":524,"values":["a","\ufdd0","s"],"children":{"a":{"type":"leaf","weight":524,"entries":[{"key":"personal","weight":524,"content":"personal"}]},"\ufdd0":{"type":"leaf","weight":455,"entries":[{"key":"person","weight":455,"content":"person"}]},"s":{"type":"leaf","weight":172,"entries":[{"key":"persons","weight":172,"content":"persons"}]}}}}}}},"f":{"type":"leaf","weight":175,"entries":[{"key":"performance","weight":175,"content":"performance"}]}}},"a":{"type":"leaf","weight":531,"entries":[{"key":"peace","weight":531,"content":"peace"}]}}},"l":{"type":"internal","weight":842,"values":["a"],"children":{"a":{"type":"internal","weight":842,"values":["c","n","y"],"children":{"c":{"type":"internal","weight":842,"values":["e"],"children":{"e":{"type":"internal","weight":842,"values":["\ufdd0","d"],"children":{"\ufdd0":{"type":"leaf","weight":842,"entries":[{"key":"place","weight":842,"content":"place"}]},"d":{"type":"leaf","weight":202,"entries":[{"key":"placed","weight":202,"content":"placed"}]}}}}},"n":{"type":"internal","weight":551,"values":["\ufdd0","n","t","e","s"],"children":{"\ufdd0":{"type":"leaf","weight":551,"entries":[{"key":"plan","weight":551,"content":"plan"}]},"n":{"type":"leaf","weight":232,"entries":[{"key":"planning","weight":232,"content":"planning"}]},"t":{"type":"leaf","weight":197,"entries":[{"key":"plant","weight":197,"content":"plant"}]},"e":{"type":"leaf","weight":113,"entries":[{"key":"plane","weight":113,"content":"plane"}]},"s":{"type":"leaf","weight":94,"entries":[{"key":"plans","weight":94,"content":"plans"}]}}},"y":{"type":"internal","weight":537,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":537,"entries":[{"key":"play","weight":537,"content":"play"}]},"e":{"type":"leaf","weight":14,"entries":[{"key":"played","weight":14,"content":"played"}]}}}}}}},"a":{"type":"internal","weight":832,"values":["r","s","y","p","i","t"],"children":{"r":{"type":"internal","weight":832,"values":["t"],"children":{"t":{"type":"internal","weight":832,"values":["\ufdd0","y","i","s"],"children":{"\ufdd0":{"type":"leaf","weight":832,"entries":[{"key":"part","weight":832,"content":"part"}]},"y":{"type":"leaf","weight":577,"entries":[{"key":"party","weight":577,"content":"party"}]},"i":{"type":"internal","weight":474,"values":["c"],"children":{"c":{"type":"internal","weight":474,"values":["u"],"children":{"u":{"type":"internal","weight":474,"values":["l"],"children":{"l":{"type":"internal","weight":474,"values":["a"],"children":{"a":{"type":"internal","weight":474,"values":["r"],"children":{"r":{"type":"internal","weight":474,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":474,"entries":[{"key":"particular","weight":474,"content":"particular"}]},"l":{"type":"leaf","weight":338,"entries":[{"key":"particularly","weight":338,"content":"particularly"}]}}}}}}}}}}}}},"s":{"type":"leaf","weight":98,"entries":[{"key":"parts","weight":98,"content":"parts"}]}}}}},"s":{"type":"internal","weight":677,"values":["t","s"],"children":{"t":{"type":"leaf","weight":677,"entries":[{"key":"past","weight":677,"content":"past"}]},"s":{"type":"leaf","weight":389,"entries":[{"key":"passed","weight":389,"content":"passed"}]}}},"y":{"type":"leaf","weight":441,"entries":[{"key":"pay","weight":441,"content":"pay"}]},"p":{"type":"leaf","weight":387,"entries":[{"key":"paper","weight":387,"content":"paper"}]},"i":{"type":"leaf","weight":329,"entries":[{"key":"paid","weight":329,"content":"paid"}]},"t":{"type":"leaf","weight":101,"entries":[{"key":"pattern","weight":101,"content":"pattern"}]}}},"u":{"type":"internal","weight":811,"values":["b","t","r"],"children":{"b":{"type":"leaf","weight":811,"entries":[{"key":"public","weight":811,"content":"public"}]},"t":{"type":"leaf","weight":810,"entries":[{"key":"put","weight":810,"content":"put"}]},"r":{"type":"leaf","weight":355,"entries":[{"key":"purpose","weight":355,"content":"purpose"}]}}},"o":{"type":"internal","weight":784,"values":["i","s","w","l","p","o"],"children":{"i":{"type":"internal","weight":784,"values":["n"],"children":{"n":{"type":"internal","weight":784,"values":["t"],"children":{"t":{"type":"internal","weight":784,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":784,"entries":[{"key":"point","weight":784,"content":"point"}]},"s":{"type":"leaf","weight":325,"entries":[{"key":"points","weight":325,"content":"points"}]}}}}}}},"s":{"type":"internal","weight":763,"values":["s","i"],"children":{"s":{"type":"leaf","weight":763,"entries":[{"key":"possible","weight":763,"content":"possible"}]},"i":{"type":"leaf","weight":621,"entries":[{"key":"position","weight":621,"content":"position"}]}}},"w":{"type":"leaf","weight":734,"entries":[{"key":"power","weight":734,"content":"power"}]},"l":{"type":"internal","weight":645,"values":["i"],"children":{"i":{"type":"internal","weight":645,"values":["t","c"],"children":{"t":{"type":"leaf","weight":645,"entries":[{"key":"political","weight":645,"content":"political"}]},"c":{"type":"internal","weight":590,"values":["y","e"],"children":{"y":{"type":"leaf","weight":590,"entries":[{"key":"policy","weight":590,"content":"policy"}]},"e":{"type":"leaf","weight":381,"entries":[{"key":"police","weight":381,"content":"police"}]}}}}}}},"p":{"type":"leaf","weight":276,"entries":[{"key":"population","weight":276,"content":"population"}]},"o":{"type":"internal","weight":95,"values":["r","l"],"children":{"r":{"type":"leaf","weight":95,"entries":[{"key":"poor","weight":95,"content":"poor"}]},"l":{"type":"leaf","weight":87,"entries":[{"key":"pool","weight":87,"content":"pool"}]}}}}},"r":{"type":"internal","weight":781,"values":["o","e","i"],"children":{"o":{"type":"internal","weight":781,"values":["g","b","v","c","p","d","f"],"children":{"g":{"type":"internal","weight":781,"values":["r"],"children":{"r":{"type":"internal","weight":781,"values":["a","e"],"children":{"a":{"type":"internal","weight":781,"values":["m"],"children":{"m":{"type":"internal","weight":781,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":781,"entries":[{"key":"program","weight":781,"content":"program"}]},"s":{"type":"leaf","weight":292,"entries":[{"key":"programs","weight":292,"content":"programs"}]}}}}},"e":{"type":"leaf","weight":165,"entries":[{"key":"progress","weight":165,"content":"progress"}]}}}}},"b":{"type":"internal","weight":715,"values":["l","a"],"children":{"l":{"type":"internal","weight":715,"values":["e"],"children":{"e":{"type":"internal","weight":715,"values":["m"],"children":{"m":{"type":"internal","weight":715,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":715,"entries":[{"key":"problem","weight":715,"content":"problem"}]},"s":{"type":"leaf","weight":636,"entries":[{"key":"problems","weight":636,"content":"problems"}]}}}}}}},"a":{"type":"leaf","weight":651,"entries":[{"key":"probably","weight":651,"content":"probably"}]}}},"v":{"type":"internal","weight":576,"values":["i"],"children":{"i":{"type":"internal","weight":576,"values":["d"],"children":{"d":{"type":"internal","weight":576,"values":["e"],"children":{"e":{"type":"internal","weight":576,"values":["\ufdd0","d"],"children":{"\ufdd0":{"type":"leaf","weight":576,"entries":[{"key":"provide","weight":576,"content":"provide"}]},"d":{"type":"leaf","weight":252,"entries":[{"key":"provided","weight":252,"content":"provided"}]}}}}}}}}},"c":{"type":"leaf","weight":522,"entries":[{"key":"process","weight":522,"content":"process"}]},"p":{"type":"leaf","weight":383,"entries":[{"key":"property","weight":383,"content":"property"}]},"d":{"type":"internal","weight":346,"values":["u"],"children":{"u":{"type":"internal","weight":346,"values":["c"],"children":{"c":{"type":"internal","weight":346,"values":["t"],"children":{"t":{"type":"internal","weight":346,"values":["i","s"],"children":{"i":{"type":"leaf","weight":346,"entries":[{"key":"production","weight":346,"content":"production"}]},"s":{"type":"leaf","weight":57,"entries":[{"key":"products","weight":57,"content":"products"}]}}}}}}}}},"f":{"type":"leaf","weight":29,"entries":[{"key":"professional","weight":29,"content":"professional"}]}}},"e":{"type":"internal","weight":771,"values":["s","t"],"children":{"s":{"type":"internal","weight":771,"values":["i","e","s"],"children":{"i":{"type":"leaf","weight":771,"entries":[{"key":"president","weight":771,"content":"president"}]},"e":{"type":"leaf","weight":767,"entries":[{"key":"present","weight":767,"content":"present"}]},"s":{"type":"leaf","weight":491,"entries":[{"key":"pressure","weight":491,"content":"pressure"},{"key":"press","weight":208,"content":"press"}]}}},"t":{"type":"leaf","weight":47,"entries":[{"key":"pretty","weight":47,"content":"pretty"}]}}},"i":{"type":"internal","weight":507,"values":["v","n","c"],"children":{"v":{"type":"leaf","weight":507,"entries":[{"key":"private","weight":507,"content":"private"}]},"n":{"type":"leaf","weight":70,"entries":[{"key":"principle","weight":70,"content":"principle"}]},"c":{"type":"leaf","weight":62,"entries":[{"key":"price","weight":62,"content":"price"}]}}}}},"i":{"type":"internal","weight":404,"values":["c","e"],"children":{"c":{"type":"leaf","weight":404,"entries":[{"key":"picture","weight":404,"content":"picture"}]},"e":{"type":"leaf","weight":228,"entries":[{"key":"piece","weight":228,"content":"piece"}]}}},"h":{"type":"leaf","weight":286,"entries":[{"key":"physical","weight":286,"content":"physical"}]}}},"g":{"type":"internal","weight":889,"values":["o","e","r","i","a","u"],"children":{"o":{"type":"internal","weight":889,"values":["o","\ufdd0","t","v","i","d","n"],"children":{"o":{"type":"leaf","weight":889,"entries":[{"key":"good","weight":889,"content":"good"}]},"\ufdd0":{"type":"leaf","weight":856,"entries":[{"key":"go","weight":856,"content":"go"}]},"t":{"type":"leaf","weight":824,"entries":[{"key":"got","weight":824,"content":"got"}]},"v":{"type":"leaf","weight":800,"entries":[{"key":"government","weight":800,"content":"government"}]},"i":{"type":"leaf","weight":787,"entries":[{"key":"going","weight":787,"content":"going"}]},"d":{"type":"leaf","weight":717,"entries":[{"key":"god","weight":717,"content":"god"}]},"n":{"type":"leaf","weight":515,"entries":[{"key":"gone","weight":515,"content":"gone"}]}}},"e":{"type":"internal","weight":878,"values":["t","n","o"],"children":{"t":{"type":"internal","weight":878,"values":["\ufdd0","t"],"children":{"\ufdd0":{"type":"leaf","weight":878,"entries":[{"key":"get","weight":878,"content":"get"}]},"t":{"type":"leaf","weight":417,"entries":[{"key":"getting","weight":417,"content":"getting"}]}}},"n":{"type":"internal","weight":830,"values":["e"],"children":{"e":{"type":"internal","weight":830,"values":["r"],"children":{"r":{"type":"internal","weight":830,"values":["a"],"children":{"a":{"type":"internal","weight":830,"values":["l"],"children":{"l":{"type":"internal","weight":830,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":830,"entries":[{"key":"general","weight":830,"content":"general"}]},"l":{"type":"leaf","weight":255,"entries":[{"key":"generally","weight":255,"content":"generally"}]}}}}}}}}}}},"o":{"type":"leaf","weight":225,"entries":[{"key":"george","weight":225,"content":"george"}]}}},"r":{"type":"internal","weight":863,"values":["e","o"],"children":{"e":{"type":"internal","weight":863,"values":["a","e"],"children":{"a":{"type":"internal","weight":863,"values":["t"],"children":{"t":{"type":"internal","weight":863,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":863,"entries":[{"key":"great","weight":863,"content":"great"}]},"e":{"type":"leaf","weight":501,"entries":[{"key":"greater","weight":501,"content":"greater"}]}}}}},"e":{"type":"leaf","weight":130,"entries":[{"key":"green","weight":130,"content":"green"}]}}},"o":{"type":"internal","weight":778,"values":["u","w"],"children":{"u":{"type":"internal","weight":778,"values":["p","n"],"children":{"p":{"type":"internal","weight":778,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":778,"entries":[{"key":"group","weight":778,"content":"group"}]},"s":{"type":"leaf","weight":194,"entries":[{"key":"groups","weight":194,"content":"groups"}]}}},"n":{"type":"leaf","weight":493,"entries":[{"key":"ground","weight":493,"content":"ground"}]}}},"w":{"type":"internal","weight":376,"values":["t","i"],"children":{"t":{"type":"leaf","weight":376,"entries":[{"key":"growth","weight":376,"content":"growth"}]},"i":{"type":"leaf","weight":66,"entries":[{"key":"growing","weight":66,"content":"growing"}]}}}}}}},"i":{"type":"internal","weight":777,"values":["v","r"],"children":{"v":{"type":"internal","weight":777,"values":["e"],"children":{"e":{"type":"internal","weight":777,"values":["\ufdd0","n","s"],"children":{"\ufdd0":{"type":"leaf","weight":777,"entries":[{"key":"give","weight":777,"content":"give"}]},"n":{"type":"leaf","weight":768,"entries":[{"key":"given","weight":768,"content":"given"}]},"s":{"type":"leaf","weight":112,"entries":[{"key":"gives","weight":112,"content":"gives"}]}}}}},"r":{"type":"internal","weight":586,"values":["l"],"children":{"l":{"type":"internal","weight":586,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":586,"entries":[{"key":"girl","weight":586,"content":"girl"}]},"s":{"type":"leaf","weight":310,"entries":[{"key":"girls","weight":310,"content":"girls"}]}}}}}}},"a":{"type":"internal","weight":685,"values":["v","m"],"children":{"v":{"type":"leaf","weight":685,"entries":[{"key":"gave","weight":685,"content":"gave"}]},"m":{"type":"leaf","weight":183,"entries":[{"key":"game","weight":183,"content":"game"}]}}},"u":{"type":"leaf","weight":140,"entries":[{"key":"gun","weight":140,"content":"gun"}]}}},"v":{"type":"internal","weight":888,"values":["e","o","a","i"],"children":{"e":{"type":"leaf","weight":888,"entries":[{"key":"very","weight":888,"content":"very"}]},"o":{"type":"internal","weight":597,"values":["i","l"],"children":{"i":{"type":"leaf","weight":597,"entries":[{"key":"voice","weight":597,"content":"voice"}]},"l":{"type":"leaf","weight":271,"entries":[{"key":"volume","weight":271,"content":"volume"}]}}},"a":{"type":"internal","weight":543,"values":["r","l"],"children":{"r":{"type":"leaf","weight":543,"entries":[{"key":"various","weight":543,"content":"various"}]},"l":{"type":"internal","weight":539,"values":["u"],"children":{"u":{"type":"internal","weight":539,"values":["e"],"children":{"e":{"type":"internal","weight":539,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":539,"entries":[{"key":"value","weight":539,"content":"value"}]},"s":{"type":"leaf","weight":495,"entries":[{"key":"values","weight":495,"content":"values"}]}}}}}}}}},"i":{"type":"internal","weight":496,"values":["e","s"],"children":{"e":{"type":"leaf","weight":496,"entries":[{"key":"view","weight":496,"content":"view"}]},"s":{"type":"leaf","weight":75,"entries":[{"key":"visit","weight":75,"content":"visit"}]}}}}},"k":{"type":"internal","weight":868,"values":["n","i","e"],"children":{"n":{"type":"internal","weight":868,"values":["o","e"],"children":{"o":{"type":"internal","weight":868,"values":["w"],"children":{"w":{"type":"internal","weight":868,"values":["\ufdd0","n","l"],"children":{"\ufdd0":{"type":"leaf","weight":868,"entries":[{"key":"know","weight":868,"content":"know"}]},"n":{"type":"leaf","weight":628,"entries":[{"key":"known","weight":628,"content":"known"}]},"l":{"type":"leaf","weight":334,"entries":[{"key":"knowledge","weight":334,"content":"knowledge"}]}}}}},"e":{"type":"leaf","weight":783,"entries":[{"key":"knew","weight":783,"content":"knew"}]}}},"i":{"type":"leaf","weight":714,"entries":[{"key":"kind","weight":714,"content":"kind"}]},"e":{"type":"internal","weight":654,"values":["e","p","n"],"children":{"e":{"type":"leaf","weight":654,"entries":[{"key":"keep","weight":654,"content":"keep"}]},"p":{"type":"leaf","weight":494,"entries":[{"key":"kept","weight":494,"content":"kept"}]},"n":{"type":"leaf","weight":293,"entries":[{"key":"kennedy","weight":293,"content":"kennedy"}]}}}}},"r":{"type":"internal","weight":854,"values":["i","o","a","e","u","h"],"children":{"i":{"type":"internal","weight":854,"values":["g","v"],"children":{"g":{"type":"leaf","weight":854,"entries":[{"key":"right","weight":854,"content":"right"}]},"v":{"type":"leaf","weight":418,"entries":[{"key":"river","weight":418,"content":"river"}]}}},"o":{"type":"internal","weight":773,"values":["o","a","l"],"children":{"o":{"type":"leaf","weight":773,"entries":[{"key":"room","weight":773,"content":"room"}]},"a":{"type":"leaf","weight":527,"entries":[{"key":"road","weight":527,"content":"road"}]},"l":{"type":"leaf","weight":18,"entries":[{"key":"role","weight":18,"content":"role"}]}}},"a":{"type":"internal","weight":762,"values":["t","n","d","c"],"children":{"t":{"type":"internal","weight":762,"values":["h","e"],"children":{"h":{"type":"leaf","weight":762,"entries":[{"key":"rather","weight":762,"content":"rather"}]},"e":{"type":"leaf","weight":561,"entries":[{"key":"rate","weight":561,"content":"rate"}]}}},"n":{"type":"leaf","weight":386,"entries":[{"key":"range","weight":386,"content":"range"},{"key":"ran","weight":264,"content":"ran"}]},"d":{"type":"leaf","weight":159,"entries":[{"key":"radio","weight":159,"content":"radio"}]},"c":{"type":"leaf","weight":2,"entries":[{"key":"race","weight":2,"content":"race"}]}}},"e":{"type":"internal","weight":670,"values":["a","s","d","q","t","c","p","l","m"],"children":{"a":{"type":"internal","weight":670,"values":["l","s","d","c"],"children":{"l":{"type":"leaf","weight":670,"entries":[{"key":"really","weight":670,"content":"really"},{"key":"real","weight":647,"content":"real"}]},"s":{"type":"internal","weight":622,"values":["o"],"children":{"o":{"type":"internal","weight":622,"values":["n"],"children":{"n":{"type":"internal","weight":622,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":622,"entries":[{"key":"reason","weight":622,"content":"reason"}]},"s":{"type":"leaf","weight":12,"entries":[{"key":"reasons","weight":12,"content":"reasons"}]}}}}}}},"d":{"type":"internal","weight":457,"values":["\ufdd0","y","i"],"children":{"\ufdd0":{"type":"leaf","weight":457,"entries":[{"key":"read","weight":457,"content":"read"}]},"y":{"type":"leaf","weight":320,"entries":[{"key":"ready","weight":320,"content":"ready"}]},"i":{"type":"leaf","weight":300,"entries":[{"key":"reading","weight":300,"content":"reading"}]}}},"c":{"type":"internal","weight":429,"values":["h","t"],"children":{"h":{"type":"leaf","weight":429,"entries":[{"key":"reached","weight":429,"content":"reached"},{"key":"reach","weight":27,"content":"reach"}]},"t":{"type":"leaf","weight":189,"entries":[{"key":"reaction","weight":189,"content":"reaction"}]}}}}},"s":{"type":"internal","weight":625,"values":["u","e","t","p"],"children":{"u":{"type":"internal","weight":625,"values":["l"],"children":{"l":{"type":"internal","weight":625,"values":["t"],"children":{"t":{"type":"internal","weight":625,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":625,"entries":[{"key":"result","weight":625,"content":"result"}]},"s":{"type":"leaf","weight":352,"entries":[{"key":"results","weight":352,"content":"results"}]}}}}}}},"e":{"type":"leaf","weight":433,"entries":[{"key":"research","weight":433,"content":"research"}]},"t":{"type":"leaf","weight":412,"entries":[{"key":"rest","weight":412,"content":"rest"}]},"p":{"type":"internal","weight":198,"values":["e","o"],"children":{"e":{"type":"leaf","weight":198,"entries":[{"key":"respect","weight":198,"content":"respect"}]},"o":{"type":"leaf","weight":146,"entries":[{"key":"responsibility","weight":146,"content":"responsibility"}]}}}}},"d":{"type":"leaf","weight":526,"entries":[{"key":"red","weight":526,"content":"red"}]},"q":{"type":"leaf","weight":484,"entries":[{"key":"required","weight":484,"content":"required"}]},"t":{"type":"internal","weight":477,"values":["u"],"children":{"u":{"type":"internal","weight":477,"values":["r"],"children":{"r":{"type":"internal","weight":477,"values":["n"],"children":{"n":{"type":"internal","weight":477,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":477,"entries":[{"key":"return","weight":477,"content":"return"}]},"e":{"type":"leaf","weight":123,"entries":[{"key":"returned","weight":123,"content":"returned"}]}}}}}}}}},"c":{"type":"internal","weight":475,"values":["e","o"],"children":{"e":{"type":"internal","weight":475,"values":["n","i"],"children":{"n":{"type":"internal","weight":475,"values":["t"],"children":{"t":{"type":"internal","weight":475,"values":["\ufdd0","l"],"children":{"\ufdd0":{"type":"leaf","weight":475,"entries":[{"key":"recent","weight":475,"content":"recent"}]},"l":{"type":"leaf","weight":186,"entries":[{"key":"recently","weight":186,"content":"recently"}]}}}}},"i":{"type":"leaf","weight":413,"entries":[{"key":"received","weight":413,"content":"received"}]}}},"o":{"type":"leaf","weight":280,"entries":[{"key":"record","weight":280,"content":"record"}]}}},"p":{"type":"internal","weight":460,"values":["o"],"children":{"o":{"type":"internal","weight":460,"values":["r"],"children":{"r":{"type":"internal","weight":460,"values":["t"],"children":{"t":{"type":"internal","weight":460,"values":["\ufdd0","e"],"children":{"\ufdd0":{"type":"leaf","weight":460,"entries":[{"key":"report","weight":460,"content":"report"}]},"e":{"type":"leaf","weight":156,"entries":[{"key":"reported","weight":156,"content":"reported"}]}}}}}}}}},"l":{"type":"internal","weight":419,"values":["i"],"children":{"i":{"type":"internal","weight":419,"values":["g"],"children":{"g":{"type":"internal","weight":419,"values":["i"],"children":{"i":{"type":"internal","weight":419,"values":["o"],"children":{"o":{"type":"internal","weight":419,"values":["u","n"],"children":{"u":{"type":"leaf","weight":419,"entries":[{"key":"religious","weight":419,"content":"religious"}]},"n":{"type":"leaf","weight":158,"entries":[{"key":"religion","weight":158,"content":"religion"}]}}}}}}}}}}},"m":{"type":"internal","weight":287,"values":["e","a"],"children":{"e":{"type":"leaf","weight":287,"entries":[{"key":"remember","weight":287,"content":"remember"}]},"a":{"type":"leaf","weight":42,"entries":[{"key":"remained","weight":42,"content":"remained"}]}}}}},"u":{"type":"internal","weight":572,"values":["n"],"children":{"n":{"type":"internal","weight":572,"values":["\ufdd0","n"],"children":{"\ufdd0":{"type":"leaf","weight":572,"entries":[{"key":"run","weight":572,"content":"run"}]},"n":{"type":"leaf","weight":181,"entries":[{"key":"running","weight":181,"content":"running"}]}}}}},"h":{"type":"leaf","weight":22,"entries":[{"key":"rhode","weight":22,"content":"rhode"}]}}},"q":{"type":"internal","weight":679,"values":["u"],"children":{"u":{"type":"internal","weight":679,"values":["i","e","a"],"children":{"i":{"type":"leaf","weight":679,"entries":[{"key":"quite","weight":679,"content":"quite"}]},"e":{"type":"internal","weight":644,"values":["s"],"children":{"s":{"type":"internal","weight":644,"values":["t"],"children":{"t":{"type":"internal","weight":644,"values":["i"],"children":{"i":{"type":"internal","weight":644,"values":["o"],"children":{"o":{"type":"internal","weight":644,"values":["n"],"children":{"n":{"type":"internal","weight":644,"values":["\ufdd0","s"],"children":{"\ufdd0":{"type":"leaf","weight":644,"entries":[{"key":"question","weight":644,"content":"question"}]},"s":{"type":"leaf","weight":297,"entries":[{"key":"questions","weight":297,"content":"questions"}]}}}}}}}}}}}}},"a":{"type":"leaf","weight":107,"entries":[{"key":"quality","weight":107,"content":"quality"}]}}}}}}} +} diff --git a/common/models/templates/test/fixtures/tries/smp-apple.json b/common/models/templates/test/fixtures/tries/smp-apple.json new file mode 100644 index 0000000000000000000000000000000000000000..05b9ec4ed93208b37889730ec761a4b31505eb3b --- /dev/null +++ b/common/models/templates/test/fixtures/tries/smp-apple.json @@ -0,0 +1,47 @@ +{ + "totalWeight":2, + "root": { + "type":"internal","weight":1, + "values":["\ud835"], + "children": { + "\ud835": { + "type":"internal", + "weight":1, + "values":["\uddba"], + "children":{ + "\uddba": { + "type":"internal", + "weight":1, + "values":["\ud835"], + "children":{ + "\ud835": { + "type":"internal", + "weight":1, + "values":["\uddc9"], + "children": { + "\uddc9":{ + "type":"internal", + "weight":1, + "values":["p","\ud835"], + "children":{ + "p": { + "type":"leaf", + "weight":1, + "entries":[{"key":"𝖺𝗉pl𝖾","weight":1,"content":"𝖺𝗉pl𝖾"}] + }, + "\ud835": { + "type":"leaf", + "weight":1, + "entries":[{"key":"𝖺𝗉𝗉𝗅𝖾","weight":1,"content":"𝖺𝗉𝗉𝗅𝖾"}] + } + } + } + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/common/models/templates/test/helpers.js b/common/models/templates/test/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..e3931d648ac157651007a2a0fa8c6f2828f48ea4 --- /dev/null +++ b/common/models/templates/test/helpers.js @@ -0,0 +1,45 @@ +const path = require('path'); +const assert = require('assert'); + +var _ = global; + +// TODO: move this to its own package; e.g., @keymanapp/models-test-helpers +// TODO: then mocha invocation is as follows: +// TODO: mocha -r @keymanapp/models-test-helpers test/ + +// KMW string must be included, so do it here: +require('@keymanapp/web-utils'); +assert.ok('💩'.kmwLength); + +/** + * Load JSON fixtures from a well-known place. + */ +_.jsonFixture = function (name) { + return require(path.join(__dirname, 'fixtures', `${name}.json`)); +} + +/** + * Returns the Context of an empty buffer; no text, at both the start and + * end of the buffer. + * + * @returns {Context} + */ +_.emptyContext = function emptyContext() { + return { + left: '', + startOfBuffer: true, + endOfBuffer: true + }; +} + +/** + * Returns a Transform that, when applied, makes no changes to the buffer. + * + * @returns {Transform} + */ +_.zeroTransform = function zeroTransform() { + return { + insert: '', + deleteLeft: 0, + }; +} diff --git a/common/models/templates/test/test-priority-queue.js b/common/models/templates/test/test-priority-queue.js new file mode 100644 index 0000000000000000000000000000000000000000..9f2e48e1d29ddebd677dd5ef4bdd5d458f744098 --- /dev/null +++ b/common/models/templates/test/test-priority-queue.js @@ -0,0 +1,116 @@ +/* + * Unit tests for the priority queue. + */ + +var assert = require('chai').assert; +var PriorityQueue = require('../').models.PriorityQueue; + +describe('Priority queue', function() { + it('can act as a min-heap', function () { + let input = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6]; + + let queue = new PriorityQueue((a, b) => a - b); + input.forEach((input) => queue.enqueue(input)); + + assert.equal(queue.peek(), 1); + assert.equal(queue.count, 10); + + for(let i = 1; i <= 10; i++) { + assert.equal(queue.dequeue(), i); + } + + assert.equal(queue.count, 0); + }); + + it('initializes well from pre-existing values', function() { + let input = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6]; + let originalInput = Array.from(input); + let queue = new PriorityQueue((a, b) => a - b, input); + + assert.deepEqual(input, originalInput); + + assert.equal(queue.peek(), 1); + assert.equal(queue.count, 10); + + for(let i = 1; i <= 10; i++) { + assert.equal(queue.dequeue(), i); + } + + assert.equal(queue.count, 0); + }); + + it('can act as a max-heap', function () { + let input = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6]; + + let queue = new PriorityQueue((a, b) => b - a); + input.forEach((input) => queue.enqueue(input)); + + assert.equal(queue.peek(), 10); + assert.equal(queue.count, 10); + + for(let i = 10; i >= 1; i--) { + assert.equal(queue.dequeue(), i); + } + + assert.equal(queue.count, 0); + }); + + it('operates correctly when used interactively', function() { + // min-heap version. + let queue = new PriorityQueue((a, b) => a - b); + + queue.enqueueAll([1, 10, 3, 8, 5]); + assert.equal(queue.count, 5); + + assert.equal(queue.dequeue(), 1); + assert.equal(queue.count, 4); + + queue.enqueue(2); + assert.equal(queue.count, 5); + + assert.equal(queue.dequeue(), 2); + assert.equal(queue.count, 4); + + queue.enqueue(7); + queue.enqueue(6); + assert.equal(queue.count, 6); + + assert.equal(queue.dequeue(), 3); + assert.equal(queue.count, 5); + + queue.enqueue(13); + queue.enqueue(0); + assert.equal(queue.count, 7); + + assert.equal(queue.dequeue(), 0); + assert.equal(queue.count, 6); + + queue.enqueue(1); + queue.enqueue(1); + assert.equal(queue.count, 8); + + assert.equal(queue.dequeue(), 1); + assert.equal(queue.count, 7); + + assert.equal(queue.dequeue(), 1); + assert.equal(queue.count, 6); + }); + + it('properly batch-enqueues', function() { + let queue = new PriorityQueue((a, b) => a - b); + + queue.enqueueAll([1, 10, 3, 8, 5]); + assert.equal(queue.count, 5); + + assert.equal(queue.dequeue(), 1); + assert.equal(queue.count, 4); + + let batch2 = [2, 7, 6, 13, 0, 1, 1]; + queue.enqueueAll(batch2); + + let correctOrder = [0, 1, 1, 2, 3, 5, 6, 7, 8, 10, 13]; + while(correctOrder.length > 0) { + assert.equal(queue.dequeue(), correctOrder.shift()); + } + }); +}); \ No newline at end of file diff --git a/common/predictive-text/unit_tests/headless/worker-predict-trie.js b/common/models/templates/test/test-trie-model.js similarity index 99% rename from common/predictive-text/unit_tests/headless/worker-predict-trie.js rename to common/models/templates/test/test-trie-model.js index 306efb925854c81f4d2b6050fbd855d7c9fa342b..36a5944b84081e86aa0e70ff02187b93360a04df 100644 --- a/common/predictive-text/unit_tests/headless/worker-predict-trie.js +++ b/common/models/templates/test/test-trie-model.js @@ -3,7 +3,7 @@ */ var assert = require('chai').assert; -var TrieModel = require('../../build/intermediate').models.TrieModel; +var TrieModel = require('../').models.TrieModel; describe('LMLayerWorker trie model for word lists', function() { describe('instantiation', function () { diff --git a/common/models/templates/test/test-trie-traversal.js b/common/models/templates/test/test-trie-traversal.js new file mode 100644 index 0000000000000000000000000000000000000000..09d1361525b2d88147b60eb84a647b02ae02edf5 --- /dev/null +++ b/common/models/templates/test/test-trie-traversal.js @@ -0,0 +1,252 @@ +/* + * Unit tests for the Trie prediction model. + */ + +var assert = require('chai').assert; +var TrieModel = require('../').models.TrieModel; + +// Useful for tests related to strings with supplementary pairs. +var smpForUnicode = function(code){ + var H = Math.floor((code - 0x10000) / 0x400) + 0xD800; + var L = (code - 0x10000) % 0x400 + 0xDC00; + + return String.fromCharCode(H, L); +} + +describe('Trie traversal abstractions', function() { + it('root-level iteration over child nodes', function() { + var model = new TrieModel(jsonFixture('tries/english-1000')); + + let rootTraversal = model.traverseFromRoot(); + assert.isDefined(rootTraversal); + + let rootKeys = ['t', 'o', 'a', 'i', 'w', 'h', 'f', 'b', 'n', 'y', 's', 'm', + 'u', 'c', 'd', 'l', 'e', 'j', 'p', 'g', 'v', 'k', 'r', 'q'] + + for(child of rootTraversal.children()) { + let keyIndex = rootKeys.indexOf(child.char); + assert.notEqual(keyIndex, -1); + rootKeys.splice(keyIndex, 1); + } + + assert.isEmpty(rootKeys); + }); + + it('traversal with simple internal nodes', function() { + var model = new TrieModel(jsonFixture('tries/english-1000')); + + let rootTraversal = model.traverseFromRoot(); + assert.isDefined(rootTraversal); + + let eKeys = ['y', 'r', 'i', 'm', 's', 'n', 'o']; + + let tSuccess = false; + let hSuccess = false; + let eSuccess = false; + for(child of rootTraversal.children()) { + if(child.char == 't') { + tSuccess = true; + let traversalInner1 = child.traversal(); + assert.isDefined(traversalInner1); + assert.isArray(child.traversal().entries); + assert.isEmpty(child.traversal().entries); + + for(tChild of traversalInner1.children()) { + if(tChild.char == 'h') { + hSuccess = true; + let traversalInner2 = tChild.traversal(); + assert.isDefined(traversalInner2); + assert.isEmpty(tChild.traversal().entries); + assert.isArray(tChild.traversal().entries); + + for(hChild of traversalInner2.children()) { + if(hChild.char == 'e') { + eSuccess = true; + let traversalInner3 = hChild.traversal(); + assert.isDefined(traversalInner3); + + assert.isDefined(traversalInner3.entries); + assert.equal(traversalInner3.entries[0], "the"); + + for(eChild of traversalInner3.children()) { + let keyIndex = eKeys.indexOf(eChild.char); + assert.notEqual(keyIndex, -1, "Did not find char '" + eChild.char + "' in array!"); + eKeys.splice(keyIndex, 1); + } + } + } + } + } + } + } + + assert.isTrue(tSuccess); + assert.isTrue(hSuccess); + assert.isTrue(eSuccess); + + assert.isEmpty(eKeys); + }); + + it('traversal over compact leaf node', function() { + var model = new TrieModel(jsonFixture('tries/english-1000')); + + let rootTraversal = model.traverseFromRoot(); + assert.isDefined(rootTraversal); + + // 't', 'r', 'o' have siblings, but these don't. + let leafChildSequence = ['u', 'b', 'l', 'e']; + let eSuccess = false; + for(child of rootTraversal.children()) { + if(child.char == 't') { + let traversalInner1 = child.traversal(); + assert.isDefined(traversalInner1); + assert.isArray(child.traversal().entries); + assert.isEmpty(child.traversal().entries); + + for(tChild of traversalInner1.children()) { + if(tChild.char == 'r') { + let traversalInner2 = tChild.traversal(); + assert.isDefined(traversalInner2); + assert.isArray(tChild.traversal().entries); + assert.isEmpty(tChild.traversal().entries); + + for(rChild of traversalInner2.children()) { + if(rChild.char == 'o') { + let curChild = rChild; + + // At this point, we're already at the trie's actual leaf node for "trouble". + // But for edit-distance trie traversal, we want to decompress this and model + // an uncompacted Trie. + do { + assert.isNotEmpty(leafChildSequence); + + let iter = curChild.traversal().children(); + let curr = iter.next(); + curChild = curr.value; + + // Test generator behavior - there should be one child, then the 'done' state. + assert.isDefined(curChild); + assert.equal(curChild.char, leafChildSequence[0]); + curr = iter.next(); + assert.isTrue(curr.done); + + // Prepare for iteration. + leafChildSequence.shift(); + + // Conditional test - if that was not the final character, entries should be undefined. + if(leafChildSequence.length > 0) { + assert.isArray(curChild.traversal().entries); + assert.isEmpty(curChild.traversal().entries); + } else { + let finalTraversal = curChild.traversal(); + assert.isDefined(finalTraversal.entries); + assert.equal(finalTraversal.entries[0], 'trouble'); + eSuccess = true; + } + } while (leafChildSequence.length > 0); + } + } + } + } + } + } + + assert.isTrue(eSuccess); + }); + + + it('traversal with SMP entries', function() { + // Two entries, both of which read "apple" to native English speakers. + // One solely uses SMP characters, the other of which uses a mix of SMP and standard. + var model = new TrieModel(jsonFixture('tries/smp-apple')); + + let rootTraversal = model.traverseFromRoot(); + assert.isDefined(rootTraversal); + + let smpA = smpForUnicode(0x1d5ba); + let smpP = smpForUnicode(0x1d5c9); + let smpE = smpForUnicode(0x1d5be); + + // Just to be sure our utility function is working right. + assert.equal(smpA + smpP + 'pl' + smpE, "𝖺𝗉pl𝖾"); + + let pKeys = ['p', smpP]; + let leafChildSequence = ['l', smpE]; + + let aSuccess = false; + let pSuccess = false; + let eSuccess = false; + for(child of rootTraversal.children()) { + if(child.char == smpA) { + aSuccess = true; + let traversalInner1 = child.traversal(); + assert.isDefined(traversalInner1); + assert.isArray(child.traversal().entries); + assert.isEmpty(child.traversal().entries); + + for(aChild of traversalInner1.children()) { + if(aChild.char == smpP) { + pSuccess = true; + let traversalInner2 = aChild.traversal(); + assert.isDefined(traversalInner2); + assert.isArray(aChild.traversal().entries); + assert.isEmpty(aChild.traversal().entries); + + for(pChild of traversalInner2.children()) { + let keyIndex = pKeys.indexOf(pChild.char); + assert.notEqual(keyIndex, -1, "Did not find char '" + pChild.char + "' in array!"); + pKeys.splice(keyIndex, 1); + + if(pChild.char == 'p') { // We'll test traversal with the 'mixed' entry from here. + let traversalInner3 = pChild.traversal(); + assert.isDefined(traversalInner3); + assert.isArray(pChild.traversal().entries); + assert.isEmpty(pChild.traversal().entries); + + // Now to handle the rest, knowing it's backed by a leaf node. + let curChild = pChild; + + // At this point, we're already at the trie's actual leaf node for "trouble". + // But for edit-distance trie traversal, we want to decompress this and model + // an uncompacted Trie. + do { + assert.isNotEmpty(leafChildSequence); + + let iter = curChild.traversal().children(); + let curr = iter.next(); + curChild = curr.value; + + // Test generator behavior - there should be one child, then the 'done' state. + assert.isDefined(curChild); + assert.equal(curChild.char, leafChildSequence[0]); + curr = iter.next(); + assert.isTrue(curr.done); + + // Prepare for iteration. + leafChildSequence.shift(); + + // Conditional test - if that was not the final character, entries should be undefined. + if(leafChildSequence.length > 0) { + assert.isArray(curChild.traversal().entries); + assert.isEmpty(curChild.traversal().entries); + } else { + let finalTraversal = curChild.traversal(); + assert.isDefined(finalTraversal.entries); + assert.equal(finalTraversal.entries[0], smpA + smpP + 'pl' + smpE); + eSuccess = true; + } + } while (leafChildSequence.length > 0); + } + } + } + } + } + } + + assert.isTrue(aSuccess); + assert.isTrue(pSuccess); + assert.isTrue(eSuccess); + + assert.isEmpty(pKeys); + }); +}); diff --git a/common/models/templates/tsconfig.json b/common/models/templates/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..b4b57f5a336a842623a8eff3267cd7bab35b91b6 --- /dev/null +++ b/common/models/templates/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "declaration": true, + "module": "none", + "outFile": "index.js", + "sourceMap": true, + "lib": ["es6"], + "target": "es5", + "typeRoots": [ + "./node_modules/@keymanapp", + "./node_modules/@types" + ] + }, + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "test" + ] +} diff --git a/common/lexical-model-types/.gitignore b/common/models/types/.gitignore similarity index 100% rename from common/lexical-model-types/.gitignore rename to common/models/types/.gitignore diff --git a/common/models/types/README.md b/common/models/types/README.md new file mode 100644 index 0000000000000000000000000000000000000000..df86c7d1ab9258d5761b418c71b0d038aa2506c0 --- /dev/null +++ b/common/models/types/README.md @@ -0,0 +1,68 @@ +`@keymanapp/models-types` +========================= + +Declares TypeScript types and interfaces required to define **Lexical +Models**, **Word breaking functions**, and all things in between. + +Install +------- + +> (see below if you are working in the keymanapp/keyman repo!) + + npm install --save-dev @keymanapp/models-types + +Usage +----- + +Say you are creating a **custom lexical model**. Then import this module +in your lexical model file! + +```Typescript +// my-nifty-model.ts + +import "@keymanapp/models-types"; + +export class MyNiftyClass implements LexicalModel { + configure(capabilities: Capabilities): Configuration { + // TODO: implement me! + throw new Error("Method not implemented."); + } + predict(transform: Transform, context: Context): ProbabilityMass[] { + // TODO: implement me! + throw new Error("Method not implemented."); + } + wordbreak(context: Context): string { + // TODO: implement me! + throw new Error("Method not implemented."); + } + punctuation?: LexicalModelPunctuation; +} +``` + +If your are creating a **custom word breaker**, you would do the same: + +```typescript +import "@keymanapp/models-types"; + +export let myShinyWordBreaker: WordBreakingFunction; +myShinyWordBreaker = function (phrase: string): Span[] { + // TODO: implement me! + throw new Error("Function not implemented") +} +``` + +Look at [index.d.ts](./index.d.ts) for documentation on each and every +type! + + +Usage within keymanapp/keyman repo +---------------------------------- + +To use it in other subprojects within keymanapp/keyman, ensure that this +package is linked using **Lerna**. From the root of the repository, run: + + npx lerna bootstrap + +Add this dependency to your subproject like so: + + npx lerna add @keymanapp/models-types path/to/your/subproject diff --git a/common/lexical-model-types/build.sh b/common/models/types/build.sh similarity index 90% rename from common/lexical-model-types/build.sh rename to common/models/types/build.sh index 039d7798007536f6c7ba6989e07e5ae8d8d613b6..d141d9d2c70f170d50f2065096f83aeeeaa6db4e 100755 --- a/common/lexical-model-types/build.sh +++ b/common/models/types/build.sh @@ -1,13 +1,18 @@ #!/bin/bash # -# Packages the lexical-model-types package. +# Packages the @keymanapp/models-types package. # # Exit on command failure and when using unset variables: set -eu -# Include some helper functions from resources -. ../../resources/shellHelperFunctions.sh +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../../resources/build/build-utils.sh" +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +## END STANDARD BUILD SCRIPT INCLUDE + EX_USAGE=64 diff --git a/common/models/types/index.d.ts b/common/models/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5807d74c2dc90341e93343f97646f081f34c5b5 --- /dev/null +++ b/common/models/types/index.d.ts @@ -0,0 +1,432 @@ +/** + * TypeScript interfaces and types required in both within the LMLayer, and for + * tools that create lexical models. + */ + +/****************************** Lexical Models ******************************/ + +/** + * A JavaScript string with the restriction that it must only + * contain Unicode scalar values. + * + * This means that any lone high surrogate must be paired with + * a low surrogate, if it exists. Lone surrogate code units are + * forbidden. + * + * See also: https://developer.mozilla.org/en-US/docs/Web/API/USVString + */ +declare type USVString = string; + +/** + * Used to facilitate edit-distance calculations by allowing the LMLayer to + * efficiently search the model's lexicon in a Trie-like manner. + */ +declare interface LexiconTraversal { + /** + * Provides an iterable pattern used to search for words with a prefix matching + * the current traversal state's prefix when a new character is appended. Iterating + * across `children` provides 'breadth' to a lexical search. + * + * For an example with English, if the current traversal state corresponds to 'th', + * children() may return an iterator with states corresponding 'e' + * (for 'the', 'then', 'there'), 'a' (for 'than', 'that'), etc. + * + * @param char A full character (a UTF-16 code point, which may be comprised of two + * code units) corresponding to the child node, appended to the current + * node's prefix to produce the child node's prefix. + *

+ * Example: if the current traversal's represented prefix is 'th', + * char = 'e' would indicate a child node with prefix = 'the'. + * @param traversal a LexiconTraversal starting from (or "rooted at") the child node. Use + * of the returned object provides 'depth' to a lexical search. + *

+ * Example: + * + * - Suppose our current LexiconTraversal represents a prefix of 'th'. + * - If `char` = 'e', the child represents a prefix of 'the'. + * - Then `traversal` allows traversing the part of the lexicon prefixed by 'the'. + */ + children(): Generator<{char: USVString, traversal: () => LexiconTraversal}>; + + /** + * Any entries directly keyed by the currently-represented lookup prefix. Entries and + * children may exist simultaneously, but `entries` must always exist when no children are + * available in the returned `children()` iterable. + * + * Examples for English: + * - search prefix of 'th': [] - an empty array. 'th' is not a valid English word. + * - search prefix of 'the': ['the']. 'then' and 'there' may also exist within the lexicon, + * but they most directly belong to deeper traversal states. + * + * May contain multiple children if a lexical model performs 'keying' operations, such as + * may result from stripping accent markers from Spanish or French. In this case, all entries + * transformed to the same 'key' should be listed by their key's traversal node. + * + * Example using French "accent homographs", where keying operations strip accents: + * + * - prefix of 'acre': ['acre', 'âcre'] + * - prefix of 'crepe': ['crêpe', 'crêpé'] + * - other examples: https://www.thoughtco.com/french-accent-homographs-1371072 + */ + entries: USVString[]; +} + +/** + * The model implementation, within the Worker. + */ +declare interface LexicalModel { + /** + * Processes `config` messages, configuring the newly-loaded model based on the host + * platform's capability restrictions. + * + * This allows the model to configure its suggestions according to what the platform + * allows the host to actually perform - for example, if post-caret deletions are not + * supported, no suggestions requiring this feature should be produced by the model. + * + * Returns a `Configuration` object detailing the capabilities the model plans to + * actually utilize, which must be as restrictive or more restrictive than those + * indicated within the provided `Capabilities` object. + * @param capabilities + */ + configure(capabilities: Capabilities): Configuration; + + /** + * Generates predictive suggestions corresponding to the state of context after the proposed + * transform is applied to it. This transform may correspond to a 'correction' of a recent + * keystroke rather than one actually received. + * + * This method should NOT attempt to perform any form of correction; this is modeled within a + * separate component of the LMLayer predictive engine. That is, "th" + "e" should not be + * have "this" for a suggestion ("e" has been 'corrected' to "i"), while "there" would be + * a reasonable prediction. + * + * However, addition of diacritics to characters (which may transform the underlying char code + * when Unicode-normalized) is permitted. For example, "pur" + "e" may reasonably predict + * "purée", where "e" has been transformed to "é" as part of the suggestion. + * + * When both prediction and correction are permitted, said component (the `ModelCompositor`) will + * generally call this method once per 'likely' generated corrected state of the context, + * utilizing the results to compute an overall likelihood across all possible suggestions. + * @param transform A Transform corresponding to a recent input keystroke + * @param context A depiction of the context to which `transform` is applied. + * @returns A probability distribution (`Distribution`) on the resulting `Suggestion` + * space for use in determining the most optimal overall suggestions. + */ + predict(transform: Transform, context: Context): Distribution; + + /** + * Performs a wordbreak operation given the current context state, returning whatever word + * or word fragment exists that starts before the caret but after the most recent whitespace + * preceding the caret. If no such text exists, the empty string is returned. + * + * This function is designed for use in generating display text for 'keep' `Suggestions` + * and display text for reverting any previously-applied `Suggestions`. + * @param context + */ + wordbreak(context: Context): USVString; + + /** + * Punctuation and presentational settings that the underlying lexical model + * expects to be applied at higher levels. e.g., the ModelCompositor. + * + * @see LexicalModelPunctuation + */ + readonly punctuation?: LexicalModelPunctuation; + + /** + * Lexical models _may_ provide a LexiconTraversal object usable to enhance + * prediction and correction results. The returned object represents the + * unfiltered lexicon (with an empty prefix). + */ + traverseFromRoot?(): LexiconTraversal; +} + +/** + * Describes how to change a buffer at the cursor position. + * first, you delete the specified amount amount from the left + * and right, then you insert the provided text. + */ +declare interface Transform { + /** + * Facilitates use of unique identifiers for tracking the Transform and + * any related data from its original source, as the reference cannot be + * preserved across WebWorker boundaries. + * + * This is *separate* from any LMLayer-internal identification values. + */ + id?: number; + + /** + * The Unicode scalar values (i.e., characters) to be inserted at the + * cursor position. + * + * Corresponds to `s` in com.keyman.KeyboardInterface.output. + */ + insert: USVString; + + /** + * The number of code units to delete to the left of the cursor. + * + * Corresponds to `dn` in com.keyman.KeyboardInterface.output. + */ + deleteLeft: number; + + /** + * The number of code units to delete to the right of the cursor. + * Not available on all platforms. + */ + deleteRight?: number; +} + +/** + * A concrete suggestion + */ +declare interface Suggestion { + /** + * Indicates the externally-supplied id of the Transform that prompted + * the Suggestion. Automatically handled by the LMLayer; models should + * not handle this field. + */ + transformId?: number; + + /** + * The suggested update to the buffer. Note that this transform should + * be applied AFTER the instigating transform, if any. + */ + readonly transform: Transform; + + /** + * A string to display the suggestion to the typist. + * This should aid the typist understand what the transform + * will do to their text. + * + * When suggesting a word, `displayAs` should be that entire word. + */ + displayAs: string; + + /** + * A single metalabel data describing the relation of the suggestion + * to the input text. Ex: 'keep', 'emoji', 'correction', etc. + */ + tag?: SuggestionTag; +} + +/** + * A tag indicating the nature of the current suggestion. + * + * Tags include: + * * 'keep' -- suggest the word as what was typed in the first place. + * This tends to be presented as the leftmost suggestion. + * @see LexicalModelPunctuation.quotesForKeepSuggestion + * * 'correction' -- this suggests a correction to the current phrase + * * 'emoji' -- replaces whatever is typed in with an appropriate emoji. + * This tends to be presented as the rightmost suggestion. + * + * If left undefined, the consumers will assume this is a prediction. + */ +type SuggestionTag = undefined | 'keep' | 'correction' | 'emoji'; + + +/** + * The text and environment surrounding the insertion point (text cursor). + */ +declare interface Context { + /** + * Up to maxLeftContextCodeUnits code units of Unicode scalar value + * (i. e., characters) to the left of the insertion point in the + * buffer. If there is nothing to the left of the buffer, this is + * an empty string. + */ + readonly left: USVString; + + /** + * Up to maxRightContextCodeUnits code units of Unicode scalar value + * (i. e., characters) to the right of the insertion point in the + * buffer. If there is nothing to the right of the buffer, this is + * an empty string. + * + * This property may be missing entirely. + */ + readonly right?: USVString; + + /** + * Whether the insertion point is at the start of the buffer. + */ + readonly startOfBuffer: boolean; + + /** + * Whether the insertion point is at the end of the buffer. + */ + readonly endOfBuffer: boolean; +} + +/** + * Represents members of a probability distribution over potential outputs + * from ambiguous text sequences. Designed for use with fat-finger correction + * and similar typing ambiguities. + */ +interface ProbabilityMass { + /** + * An individual sample from a Distribution over the same type. + */ + readonly sample: T; + + /** + * The probability mass for this member of the distribution, + * calculated devoid of any language-modeling influences. + */ + p: number; +} + +declare type Distribution = ProbabilityMass[]; + + +/******************************** Messaging ********************************/ + +/** + * Describes the capabilities of the keyboard's platform. + * This includes upper bounds for how much text will be sent on each + * prediction, as well as what operations the keyboard is allowed to do on the + * underlying buffer. + */ +declare interface Capabilities { + /** + * The maximum amount of UTF-16 code points that the keyboard will provide to + * the left of the cursor, as an integer. + */ + readonly maxLeftContextCodePoints: number, + + /** + * The maximum amount of code points that the keyboard will provide to the + * right of the cursor, as an integer. The value 0 or the absence of this + * rule implies that the right contexts are not supported. + */ + readonly maxRightContextCodePoints?: number, + + /** + * Whether the platform supports deleting to the right. The absence of this + * rule implies false. + */ + readonly supportsDeleteRight?: false, +} + +/** + * Configuration of the LMLayer, sent back to the keyboard. + */ +declare interface Configuration { + /** + * How many UTF-16 code units maximum to send as the context to the + * left of the cursor ("left" in the Unicode character stream). + * + * Affects the `context` property sent in `predict` messages. + * + * While the left context MUST NOT bisect surrogate pairs, they MAY + * bisect graphical clusters. + */ + leftContextCodePoints: number; + /** deprecated; use `leftContextCodePoints` instead! */ + leftContextCodeUnits?: number, + + /** + * How many UTF-16 code units maximum to send as the context to the + * right of the cursor ("right" in the Unicode character stream). + * + * Affects the `context` property sent in `predict` messages. + * + * While the right context MUST NOT bisect surrogate pairs, they MAY + * bisect graphical clusters. + */ + rightContextCodePoints: number; + /** deprecated; use `leftContextCodePoints` instead! */ + rightContextCodeUnits?: number, +} + + +/****************************** Word breaking ******************************/ + +/** + * A simple word breaking function takes a phrase, and splits it into "words", + * for whatever definition of "word" is usable for the language model. + * + * For example: + * + * getText(breakWordsEnglish("Hello, world!")) == ["Hello", "world"] + * getText(breakWordsCree("ᑕᐻ ᒥᔪ ᑮᓯᑲᐤ ᐊᓄᐦᐨ᙮")) == ["ᑕᐻ", "ᒥᔪ ᑮᓯᑲᐤ""", "ᐊᓄᐦᐨ"] + * getText(breakWordsJapanese("英語を話せますか?")) == ["英語", "を", "話せます", "か"] + * + * Not all language models take in a configurable word breaking function. + * + * @returns an array of spans from the phrase, in order as they appear in the + * phrase, each span which representing a word. + */ +declare interface WordBreakingFunction { + // invariant: span[i].end <= span[i + 1].start + // invariant: for all span[i] and span[i + 1], there does not exist a span[k] + // where span[i].end <= span[k].start AND span[k].end <= span[i + 1].start + (phrase: string): Span[]; +} + +/** + * A span of text in a phrase. This is usually meant to represent words from a + * pharse. + */ +declare interface Span { + // invariant: start < end (empty spans not allowed) + readonly start: number; + // invariant: end > end (empty spans not allowed) + readonly end: number; + // invariant: length === end - start + readonly length: number; + // invariant: text.length === length + // invariant: each character is BMP UTF-16 code unit, or is a high surrogate + // UTF-16 code unit followed by a low surrogate UTF-16 code unit. + readonly text: string; +} + + +/********************************** OTHER **********************************/ + +/** + * Options for various punctuation to use in suggestions. + */ +interface LexicalModelPunctuation { + /** + * The quotes that appear in "keep" suggestions, e.g., keep what the user + * typed verbatim. + * + * The keep suggestion is often the leftmost one, when suggested. + * + * [ “Hrllo” ] [ Hello ] [ Heck ] + */ + readonly quotesForKeepSuggestion: { + /** + * What will appear on the opening side of the quote. + * (left side for LTR scripts; right side for RTL scripts) + * + * Default: `“` + */ + readonly open: string; + /** + * What will appear on the closing side of the quote. + * (right side for LTR scripts; left side for RTL scripts) + * + * Default: `”` + */ + readonly close: string; + }; + /** + * What punctuation or spacing to insert after every complete word + * prediction. This can be set to the empty string when the script does not + * use spaces to separate words. + * + * Default: ` ` + */ + readonly insertAfterWord: string; + + /** + * Whether or not the model's language is typically displayed in RTL form. + * + * Default: false (or undefined) + */ + readonly isRTL?: boolean; +} diff --git a/common/models/types/package-lock.json b/common/models/types/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..2aeb64b784564088e60e427fe2369918b4aa41a9 --- /dev/null +++ b/common/models/types/package-lock.json @@ -0,0 +1,14 @@ +{ + "name": "@keymanapp/models-types", + "version": "14.0.144", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "typescript": { + "version": "3.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.3.tgz", + "integrity": "sha512-D/wqnB2xzNFIcoBG9FG8cXRDjiqSTbG2wd8DMZeQyJlP1vfTkIxH4GKveWaEBYySKIg+USu+E+EDIR47SqnaMQ==", + "dev": true + } + } +} diff --git a/common/models/types/package.json b/common/models/types/package.json new file mode 100644 index 0000000000000000000000000000000000000000..505bbbaf7f6919a6233dd7b1e3dbfe2e770f6cae --- /dev/null +++ b/common/models/types/package.json @@ -0,0 +1,39 @@ +{ + "name": "@keymanapp/models-types", + "version": "14.0.144", + "description": "Type definitions in used in the modeling (lexical model/predictive text) component of Keyman.", + "types": "./index.d.ts", + "scripts": { + "test": "tsc test.ts" + }, + "repository": { + "type": "git", + "url": "https://github.com/keymanapp/keyman" + }, + "keywords": [ + "lmlayer", + "keyman", + "predictive", + "text", + "types", + "typing", + "typescript" + ], + "author": "Marc Durdin (https://github.com/mcdurdin)", + "contributors": [ + "Eddie Antonio Santos (https://github.com/eddieantonio)", + "Joshua Horton" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/keymanapp/keyman/issues" + }, + "homepage": "https://github.com/keymanapp/keyman/tree/master/common/models/types#readme", + "devDependencies": { + "typescript": "^3.8.3" + }, + "files": [ + "README.md", + "index.d.ts" + ] +} diff --git a/common/lexical-model-types/test.ts b/common/models/types/test.ts similarity index 100% rename from common/lexical-model-types/test.ts rename to common/models/types/test.ts diff --git a/common/models/wordbreakers/.gitignore b/common/models/wordbreakers/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..75871e6dc27dea5d443593f69d0c3800fb838000 --- /dev/null +++ b/common/models/wordbreakers/.gitignore @@ -0,0 +1,3 @@ +*.js +*.js.map +*.d.ts diff --git a/common/models/wordbreakers/README.md b/common/models/wordbreakers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..29ba5d51c73d854e964678aaf1462b846db983e6 --- /dev/null +++ b/common/models/wordbreakers/README.md @@ -0,0 +1,19 @@ +# `@keymanapp/models-wordbreakers` + +The word breakers bundled in Keyman's modeling layer (common/models). + +Includes: + + - `default` — a word breaker based on the Unicode default word boundary specification + - _deprecated_ `ascii` — an example word breaker + - _deprecated_ `placeholder` — an example word breaker + +## Usage + +``` +import {wordBreakers} from '@keymanapp/models-wordbreakers'; +const breakWords = wordBreakers['default']; + +console.log(breakWords('Hello, World!').map(span => span.text)); +// prints: [ 'Hello', ',', 'World', '!' ] +``` diff --git a/common/models/wordbreakers/package-lock.json b/common/models/wordbreakers/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..b4812e12b84633caf14f54ef97ad3be770a55940 --- /dev/null +++ b/common/models/wordbreakers/package-lock.json @@ -0,0 +1,327 @@ +{ + "name": "@keymanapp/models-wordbreakers", + "version": "14.0.144", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/chai": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.2.11.tgz", + "integrity": "sha512-t7uW6eFafjO+qJ3BIV2gGUyZs27egcNRkUdalkud+Qa3+kg//f129iuOFivHDXQ+vnU3fDXuwgv0cqMCbcE8sw==", + "dev": true + }, + "@types/mocha": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-7.0.2.tgz", + "integrity": "sha512-ZvO2tAcjmMi8V/5Z3JsyofMe3hasRcaw88cto5etSVMwVQfeivGAlEYmaQgceUSVYFofVjT+ioHsATjdWcFt1w==", + "dev": true + }, + "@types/node": { + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.3.tgz", + "integrity": "sha512-a8TR2N5VEJCL9HEJrAfwv3UI1bZq50HydowDDVV6pfnY7ZwG5Pjii+nSDhrDtGW3XKMoVKOgG8zS/Kv5j399uA==" + }, + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true + }, + "assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "browser-stdout": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", + "dev": true + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "chai": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.2.0.tgz", + "integrity": "sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw==", + "dev": true, + "requires": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^3.0.1", + "get-func-name": "^2.0.0", + "pathval": "^1.1.0", + "type-detect": "^4.0.5" + } + }, + "check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", + "dev": true + }, + "commander": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz", + "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-eql": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", + "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "dev": true, + "requires": { + "type-detect": "^4.0.0" + } + }, + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "get-func-name": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", + "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "growl": { + "version": "1.10.5", + "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", + "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "he": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "mocha": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-5.2.0.tgz", + "integrity": "sha512-2IUgKDhc3J7Uug+FxMXuqIyYzH7gJjXECKe/w43IGgQHTSj3InJi+yAA7T24L9bQMRKiUEHxEX37G5JpVUGLcQ==", + "dev": true, + "requires": { + "browser-stdout": "1.3.1", + "commander": "2.15.1", + "debug": "3.1.0", + "diff": "3.5.0", + "escape-string-regexp": "1.0.5", + "glob": "7.1.2", + "growl": "1.10.5", + "he": "1.1.1", + "minimatch": "3.0.4", + "mkdirp": "0.5.1", + "supports-color": "5.4.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "pathval": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz", + "integrity": "sha1-uULm1L3mUwBe9rcTYd74cn0GReA=", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-support": { + "version": "0.5.19", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz", + "integrity": "sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "ts-node": { + "version": "8.10.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-8.10.1.tgz", + "integrity": "sha512-bdNz1L4ekHiJul6SHtZWs1ujEKERJnHs4HxN7rjTyyVOFf3HaJ6sLqe6aPG62XTzAB/63pKRh5jTSWL0D7bsvw==", + "dev": true, + "requires": { + "arg": "^4.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "source-map-support": "^0.5.17", + "yn": "3.1.1" + }, + "dependencies": { + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true + } + } + }, + "type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true + } + } +} diff --git a/common/models/wordbreakers/package.json b/common/models/wordbreakers/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8e1c03e24d95cfa7984a42bf89e2f00a0ca1ba2a --- /dev/null +++ b/common/models/wordbreakers/package.json @@ -0,0 +1,54 @@ +{ + "name": "@keymanapp/models-wordbreakers", + "version": "14.0.144", + "description": "Word breakers bundled in the modeling layer", + "keywords": [ + "lexical model", + "models", + "word", + "breaker", + "breaking", + "lmlayer" + ], + "contributors": [ + "Eddie Antonio Santos " + ], + "homepage": "https://github.com/keymanapp/keyman", + "license": "MIT", + "main": "lib/index.js", + "directories": { + "lib": "lib", + "test": "test" + }, + "files": [ + "lib" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/keymanapp/keyman.git" + }, + "scripts": { + "build": "tsc", + "prepublish": "npm run build", + "pretest": "npm run build", + "test": "mocha" + }, + "bugs": { + "url": "https://github.com/keymanapp/keyman/issues" + }, + "devDependencies": { + "@keymanapp/models-types": "^14.0.144", + "@types/chai": "^4.2.11", + "@types/mocha": "^7.0.2", + "chai": "^4.2.0", + "mocha": "^5.2.0", + "ts-node": "^8.10.1", + "typescript": "^3.8.3" + }, + "dependencies": { + "@types/node": "^14.0.3" + } +} diff --git a/common/predictive-text/worker/word_breaking/ascii-word-breaker.ts b/common/models/wordbreakers/src/ascii.ts similarity index 92% rename from common/predictive-text/worker/word_breaking/ascii-word-breaker.ts rename to common/models/wordbreakers/src/ascii.ts index c7c10726bb6bd48026c8848f7ee8520d7e5c3751..81be11f3957a9c9372832446911e19e7df4e0514 100644 --- a/common/predictive-text/worker/word_breaking/ascii-word-breaker.ts +++ b/common/models/wordbreakers/src/ascii.ts @@ -1,4 +1,20 @@ namespace wordBreakers { + /** + * Splits ASCII words. + * + * @param phrase + */ + export function ascii(phrase: string): Span[] { + let matchWord = /[A-Za-z0-9']+/g; + let words: Span[] = []; + let match: RegExpExecArray | null; + while ((match = matchWord.exec(phrase)) !== null) { + words.push(new RegExpDerivedSpan(match[0], match.index)); + } + + return words; + } + /** * A concrete span class that derives its properties from the result of * RegExp.exec() array. @@ -20,20 +36,4 @@ namespace wordBreakers { return this.start + this.text.length; } } - - /** - * Splits ASCII words. - * - * @param phrase - */ - export function ascii(phrase: string): Span[] { - let matchWord = /[A-Za-z0-9']+/g; - let words: Span[] = []; - let match: RegExpExecArray; - while ((match = matchWord.exec(phrase)) !== null) { - words.push(new RegExpDerivedSpan(match[0], match.index)); - } - - return words; - } -} \ No newline at end of file +} diff --git a/common/models/wordbreakers/src/default/data.ts b/common/models/wordbreakers/src/default/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffb6b8e79a2e4bf580057516b8720875e89c920f --- /dev/null +++ b/common/models/wordbreakers/src/default/data.ts @@ -0,0 +1,1779 @@ +namespace wordBreakers { +export namespace data { +// Automatically generated file. DO NOT MODIFY. +/** + * Valid values for a word break property. + */ +export const enum WordBreakProperty { + Other, + LF, + Newline, + CR, + WSegSpace, + Double_Quote, + Single_Quote, + MidNum, + MidNumLet, + Numeric, + MidLetter, + ALetter, + ExtendNumLet, + Format, + Extend, + Hebrew_Letter, + ZWJ, + Katakana, + Regional_Indicator, + sot, + eot +}; + +/** + * Constants for indexing values in WORD_BREAK_PROPERTY. + */ +export const enum I { + Start = 0, + Value = 1 +} + +export const WORD_BREAK_PROPERTY: [number, WordBreakProperty][] = [ + [/*start*/ 0x0, WordBreakProperty.Other], + [/*start*/ 0xA, WordBreakProperty.LF], + [/*start*/ 0xB, WordBreakProperty.Newline], + [/*start*/ 0xD, WordBreakProperty.CR], + [/*start*/ 0xE, WordBreakProperty.Other], + [/*start*/ 0x20, WordBreakProperty.WSegSpace], + [/*start*/ 0x21, WordBreakProperty.Other], + [/*start*/ 0x22, WordBreakProperty.Double_Quote], + [/*start*/ 0x23, WordBreakProperty.Other], + [/*start*/ 0x27, WordBreakProperty.Single_Quote], + [/*start*/ 0x28, WordBreakProperty.Other], + [/*start*/ 0x2C, WordBreakProperty.MidNum], + [/*start*/ 0x2D, WordBreakProperty.Other], + [/*start*/ 0x2E, WordBreakProperty.MidNumLet], + [/*start*/ 0x2F, WordBreakProperty.Other], + [/*start*/ 0x30, WordBreakProperty.Numeric], + [/*start*/ 0x3A, WordBreakProperty.MidLetter], + [/*start*/ 0x3B, WordBreakProperty.MidNum], + [/*start*/ 0x3C, WordBreakProperty.Other], + [/*start*/ 0x41, WordBreakProperty.ALetter], + [/*start*/ 0x5B, WordBreakProperty.Other], + [/*start*/ 0x5F, WordBreakProperty.ExtendNumLet], + [/*start*/ 0x60, WordBreakProperty.Other], + [/*start*/ 0x61, WordBreakProperty.ALetter], + [/*start*/ 0x7B, WordBreakProperty.Other], + [/*start*/ 0x85, WordBreakProperty.Newline], + [/*start*/ 0x86, WordBreakProperty.Other], + [/*start*/ 0xAA, WordBreakProperty.ALetter], + [/*start*/ 0xAB, WordBreakProperty.Other], + [/*start*/ 0xAD, WordBreakProperty.Format], + [/*start*/ 0xAE, WordBreakProperty.Other], + [/*start*/ 0xB5, WordBreakProperty.ALetter], + [/*start*/ 0xB6, WordBreakProperty.Other], + [/*start*/ 0xB7, WordBreakProperty.MidLetter], + [/*start*/ 0xB8, WordBreakProperty.Other], + [/*start*/ 0xBA, WordBreakProperty.ALetter], + [/*start*/ 0xBB, WordBreakProperty.Other], + [/*start*/ 0xC0, WordBreakProperty.ALetter], + [/*start*/ 0xD7, WordBreakProperty.Other], + [/*start*/ 0xD8, WordBreakProperty.ALetter], + [/*start*/ 0xF7, WordBreakProperty.Other], + [/*start*/ 0xF8, WordBreakProperty.ALetter], + [/*start*/ 0x2D8, WordBreakProperty.Other], + [/*start*/ 0x2DE, WordBreakProperty.ALetter], + [/*start*/ 0x300, WordBreakProperty.Extend], + [/*start*/ 0x370, WordBreakProperty.ALetter], + [/*start*/ 0x375, WordBreakProperty.Other], + [/*start*/ 0x376, WordBreakProperty.ALetter], + [/*start*/ 0x378, WordBreakProperty.Other], + [/*start*/ 0x37A, WordBreakProperty.ALetter], + [/*start*/ 0x37E, WordBreakProperty.MidNum], + [/*start*/ 0x37F, WordBreakProperty.ALetter], + [/*start*/ 0x380, WordBreakProperty.Other], + [/*start*/ 0x386, WordBreakProperty.ALetter], + [/*start*/ 0x387, WordBreakProperty.MidLetter], + [/*start*/ 0x388, WordBreakProperty.ALetter], + [/*start*/ 0x38B, WordBreakProperty.Other], + [/*start*/ 0x38C, WordBreakProperty.ALetter], + [/*start*/ 0x38D, WordBreakProperty.Other], + [/*start*/ 0x38E, WordBreakProperty.ALetter], + [/*start*/ 0x3A2, WordBreakProperty.Other], + [/*start*/ 0x3A3, WordBreakProperty.ALetter], + [/*start*/ 0x3F6, WordBreakProperty.Other], + [/*start*/ 0x3F7, WordBreakProperty.ALetter], + [/*start*/ 0x482, WordBreakProperty.Other], + [/*start*/ 0x483, WordBreakProperty.Extend], + [/*start*/ 0x48A, WordBreakProperty.ALetter], + [/*start*/ 0x530, WordBreakProperty.Other], + [/*start*/ 0x531, WordBreakProperty.ALetter], + [/*start*/ 0x557, WordBreakProperty.Other], + [/*start*/ 0x559, WordBreakProperty.ALetter], + [/*start*/ 0x55D, WordBreakProperty.Other], + [/*start*/ 0x55E, WordBreakProperty.ALetter], + [/*start*/ 0x55F, WordBreakProperty.MidLetter], + [/*start*/ 0x560, WordBreakProperty.ALetter], + [/*start*/ 0x589, WordBreakProperty.MidNum], + [/*start*/ 0x58A, WordBreakProperty.ALetter], + [/*start*/ 0x58B, WordBreakProperty.Other], + [/*start*/ 0x591, WordBreakProperty.Extend], + [/*start*/ 0x5BE, WordBreakProperty.Other], + [/*start*/ 0x5BF, WordBreakProperty.Extend], + [/*start*/ 0x5C0, WordBreakProperty.Other], + [/*start*/ 0x5C1, WordBreakProperty.Extend], + [/*start*/ 0x5C3, WordBreakProperty.Other], + [/*start*/ 0x5C4, WordBreakProperty.Extend], + [/*start*/ 0x5C6, WordBreakProperty.Other], + [/*start*/ 0x5C7, WordBreakProperty.Extend], + [/*start*/ 0x5C8, WordBreakProperty.Other], + [/*start*/ 0x5D0, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0x5EB, WordBreakProperty.Other], + [/*start*/ 0x5EF, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0x5F3, WordBreakProperty.ALetter], + [/*start*/ 0x5F4, WordBreakProperty.MidLetter], + [/*start*/ 0x5F5, WordBreakProperty.Other], + [/*start*/ 0x600, WordBreakProperty.Format], + [/*start*/ 0x606, WordBreakProperty.Other], + [/*start*/ 0x60C, WordBreakProperty.MidNum], + [/*start*/ 0x60E, WordBreakProperty.Other], + [/*start*/ 0x610, WordBreakProperty.Extend], + [/*start*/ 0x61B, WordBreakProperty.Other], + [/*start*/ 0x61C, WordBreakProperty.Format], + [/*start*/ 0x61D, WordBreakProperty.Other], + [/*start*/ 0x620, WordBreakProperty.ALetter], + [/*start*/ 0x64B, WordBreakProperty.Extend], + [/*start*/ 0x660, WordBreakProperty.Numeric], + [/*start*/ 0x66A, WordBreakProperty.Other], + [/*start*/ 0x66B, WordBreakProperty.Numeric], + [/*start*/ 0x66C, WordBreakProperty.MidNum], + [/*start*/ 0x66D, WordBreakProperty.Other], + [/*start*/ 0x66E, WordBreakProperty.ALetter], + [/*start*/ 0x670, WordBreakProperty.Extend], + [/*start*/ 0x671, WordBreakProperty.ALetter], + [/*start*/ 0x6D4, WordBreakProperty.Other], + [/*start*/ 0x6D5, WordBreakProperty.ALetter], + [/*start*/ 0x6D6, WordBreakProperty.Extend], + [/*start*/ 0x6DD, WordBreakProperty.Format], + [/*start*/ 0x6DE, WordBreakProperty.Other], + [/*start*/ 0x6DF, WordBreakProperty.Extend], + [/*start*/ 0x6E5, WordBreakProperty.ALetter], + [/*start*/ 0x6E7, WordBreakProperty.Extend], + [/*start*/ 0x6E9, WordBreakProperty.Other], + [/*start*/ 0x6EA, WordBreakProperty.Extend], + [/*start*/ 0x6EE, WordBreakProperty.ALetter], + [/*start*/ 0x6F0, WordBreakProperty.Numeric], + [/*start*/ 0x6FA, WordBreakProperty.ALetter], + [/*start*/ 0x6FD, WordBreakProperty.Other], + [/*start*/ 0x6FF, WordBreakProperty.ALetter], + [/*start*/ 0x700, WordBreakProperty.Other], + [/*start*/ 0x70F, WordBreakProperty.Format], + [/*start*/ 0x710, WordBreakProperty.ALetter], + [/*start*/ 0x711, WordBreakProperty.Extend], + [/*start*/ 0x712, WordBreakProperty.ALetter], + [/*start*/ 0x730, WordBreakProperty.Extend], + [/*start*/ 0x74B, WordBreakProperty.Other], + [/*start*/ 0x74D, WordBreakProperty.ALetter], + [/*start*/ 0x7A6, WordBreakProperty.Extend], + [/*start*/ 0x7B1, WordBreakProperty.ALetter], + [/*start*/ 0x7B2, WordBreakProperty.Other], + [/*start*/ 0x7C0, WordBreakProperty.Numeric], + [/*start*/ 0x7CA, WordBreakProperty.ALetter], + [/*start*/ 0x7EB, WordBreakProperty.Extend], + [/*start*/ 0x7F4, WordBreakProperty.ALetter], + [/*start*/ 0x7F6, WordBreakProperty.Other], + [/*start*/ 0x7F8, WordBreakProperty.MidNum], + [/*start*/ 0x7F9, WordBreakProperty.Other], + [/*start*/ 0x7FA, WordBreakProperty.ALetter], + [/*start*/ 0x7FB, WordBreakProperty.Other], + [/*start*/ 0x7FD, WordBreakProperty.Extend], + [/*start*/ 0x7FE, WordBreakProperty.Other], + [/*start*/ 0x800, WordBreakProperty.ALetter], + [/*start*/ 0x816, WordBreakProperty.Extend], + [/*start*/ 0x81A, WordBreakProperty.ALetter], + [/*start*/ 0x81B, WordBreakProperty.Extend], + [/*start*/ 0x824, WordBreakProperty.ALetter], + [/*start*/ 0x825, WordBreakProperty.Extend], + [/*start*/ 0x828, WordBreakProperty.ALetter], + [/*start*/ 0x829, WordBreakProperty.Extend], + [/*start*/ 0x82E, WordBreakProperty.Other], + [/*start*/ 0x840, WordBreakProperty.ALetter], + [/*start*/ 0x859, WordBreakProperty.Extend], + [/*start*/ 0x85C, WordBreakProperty.Other], + [/*start*/ 0x860, WordBreakProperty.ALetter], + [/*start*/ 0x86B, WordBreakProperty.Other], + [/*start*/ 0x8A0, WordBreakProperty.ALetter], + [/*start*/ 0x8B5, WordBreakProperty.Other], + [/*start*/ 0x8B6, WordBreakProperty.ALetter], + [/*start*/ 0x8C8, WordBreakProperty.Other], + [/*start*/ 0x8D3, WordBreakProperty.Extend], + [/*start*/ 0x8E2, WordBreakProperty.Format], + [/*start*/ 0x8E3, WordBreakProperty.Extend], + [/*start*/ 0x904, WordBreakProperty.ALetter], + [/*start*/ 0x93A, WordBreakProperty.Extend], + [/*start*/ 0x93D, WordBreakProperty.ALetter], + [/*start*/ 0x93E, WordBreakProperty.Extend], + [/*start*/ 0x950, WordBreakProperty.ALetter], + [/*start*/ 0x951, WordBreakProperty.Extend], + [/*start*/ 0x958, WordBreakProperty.ALetter], + [/*start*/ 0x962, WordBreakProperty.Extend], + [/*start*/ 0x964, WordBreakProperty.Other], + [/*start*/ 0x966, WordBreakProperty.Numeric], + [/*start*/ 0x970, WordBreakProperty.Other], + [/*start*/ 0x971, WordBreakProperty.ALetter], + [/*start*/ 0x981, WordBreakProperty.Extend], + [/*start*/ 0x984, WordBreakProperty.Other], + [/*start*/ 0x985, WordBreakProperty.ALetter], + [/*start*/ 0x98D, WordBreakProperty.Other], + [/*start*/ 0x98F, WordBreakProperty.ALetter], + [/*start*/ 0x991, WordBreakProperty.Other], + [/*start*/ 0x993, WordBreakProperty.ALetter], + [/*start*/ 0x9A9, WordBreakProperty.Other], + [/*start*/ 0x9AA, WordBreakProperty.ALetter], + [/*start*/ 0x9B1, WordBreakProperty.Other], + [/*start*/ 0x9B2, WordBreakProperty.ALetter], + [/*start*/ 0x9B3, WordBreakProperty.Other], + [/*start*/ 0x9B6, WordBreakProperty.ALetter], + [/*start*/ 0x9BA, WordBreakProperty.Other], + [/*start*/ 0x9BC, WordBreakProperty.Extend], + [/*start*/ 0x9BD, WordBreakProperty.ALetter], + [/*start*/ 0x9BE, WordBreakProperty.Extend], + [/*start*/ 0x9C5, WordBreakProperty.Other], + [/*start*/ 0x9C7, WordBreakProperty.Extend], + [/*start*/ 0x9C9, WordBreakProperty.Other], + [/*start*/ 0x9CB, WordBreakProperty.Extend], + [/*start*/ 0x9CE, WordBreakProperty.ALetter], + [/*start*/ 0x9CF, WordBreakProperty.Other], + [/*start*/ 0x9D7, WordBreakProperty.Extend], + [/*start*/ 0x9D8, WordBreakProperty.Other], + [/*start*/ 0x9DC, WordBreakProperty.ALetter], + [/*start*/ 0x9DE, WordBreakProperty.Other], + [/*start*/ 0x9DF, WordBreakProperty.ALetter], + [/*start*/ 0x9E2, WordBreakProperty.Extend], + [/*start*/ 0x9E4, WordBreakProperty.Other], + [/*start*/ 0x9E6, WordBreakProperty.Numeric], + [/*start*/ 0x9F0, WordBreakProperty.ALetter], + [/*start*/ 0x9F2, WordBreakProperty.Other], + [/*start*/ 0x9FC, WordBreakProperty.ALetter], + [/*start*/ 0x9FD, WordBreakProperty.Other], + [/*start*/ 0x9FE, WordBreakProperty.Extend], + [/*start*/ 0x9FF, WordBreakProperty.Other], + [/*start*/ 0xA01, WordBreakProperty.Extend], + [/*start*/ 0xA04, WordBreakProperty.Other], + [/*start*/ 0xA05, WordBreakProperty.ALetter], + [/*start*/ 0xA0B, WordBreakProperty.Other], + [/*start*/ 0xA0F, WordBreakProperty.ALetter], + [/*start*/ 0xA11, WordBreakProperty.Other], + [/*start*/ 0xA13, WordBreakProperty.ALetter], + [/*start*/ 0xA29, WordBreakProperty.Other], + [/*start*/ 0xA2A, WordBreakProperty.ALetter], + [/*start*/ 0xA31, WordBreakProperty.Other], + [/*start*/ 0xA32, WordBreakProperty.ALetter], + [/*start*/ 0xA34, WordBreakProperty.Other], + [/*start*/ 0xA35, WordBreakProperty.ALetter], + [/*start*/ 0xA37, WordBreakProperty.Other], + [/*start*/ 0xA38, WordBreakProperty.ALetter], + [/*start*/ 0xA3A, WordBreakProperty.Other], + [/*start*/ 0xA3C, WordBreakProperty.Extend], + [/*start*/ 0xA3D, WordBreakProperty.Other], + [/*start*/ 0xA3E, WordBreakProperty.Extend], + [/*start*/ 0xA43, WordBreakProperty.Other], + [/*start*/ 0xA47, WordBreakProperty.Extend], + [/*start*/ 0xA49, WordBreakProperty.Other], + [/*start*/ 0xA4B, WordBreakProperty.Extend], + [/*start*/ 0xA4E, WordBreakProperty.Other], + [/*start*/ 0xA51, WordBreakProperty.Extend], + [/*start*/ 0xA52, WordBreakProperty.Other], + [/*start*/ 0xA59, WordBreakProperty.ALetter], + [/*start*/ 0xA5D, WordBreakProperty.Other], + [/*start*/ 0xA5E, WordBreakProperty.ALetter], + [/*start*/ 0xA5F, WordBreakProperty.Other], + [/*start*/ 0xA66, WordBreakProperty.Numeric], + [/*start*/ 0xA70, WordBreakProperty.Extend], + [/*start*/ 0xA72, WordBreakProperty.ALetter], + [/*start*/ 0xA75, WordBreakProperty.Extend], + [/*start*/ 0xA76, WordBreakProperty.Other], + [/*start*/ 0xA81, WordBreakProperty.Extend], + [/*start*/ 0xA84, WordBreakProperty.Other], + [/*start*/ 0xA85, WordBreakProperty.ALetter], + [/*start*/ 0xA8E, WordBreakProperty.Other], + [/*start*/ 0xA8F, WordBreakProperty.ALetter], + [/*start*/ 0xA92, WordBreakProperty.Other], + [/*start*/ 0xA93, WordBreakProperty.ALetter], + [/*start*/ 0xAA9, WordBreakProperty.Other], + [/*start*/ 0xAAA, WordBreakProperty.ALetter], + [/*start*/ 0xAB1, WordBreakProperty.Other], + [/*start*/ 0xAB2, WordBreakProperty.ALetter], + [/*start*/ 0xAB4, WordBreakProperty.Other], + [/*start*/ 0xAB5, WordBreakProperty.ALetter], + [/*start*/ 0xABA, WordBreakProperty.Other], + [/*start*/ 0xABC, WordBreakProperty.Extend], + [/*start*/ 0xABD, WordBreakProperty.ALetter], + [/*start*/ 0xABE, WordBreakProperty.Extend], + [/*start*/ 0xAC6, WordBreakProperty.Other], + [/*start*/ 0xAC7, WordBreakProperty.Extend], + [/*start*/ 0xACA, WordBreakProperty.Other], + [/*start*/ 0xACB, WordBreakProperty.Extend], + [/*start*/ 0xACE, WordBreakProperty.Other], + [/*start*/ 0xAD0, WordBreakProperty.ALetter], + [/*start*/ 0xAD1, WordBreakProperty.Other], + [/*start*/ 0xAE0, WordBreakProperty.ALetter], + [/*start*/ 0xAE2, WordBreakProperty.Extend], + [/*start*/ 0xAE4, WordBreakProperty.Other], + [/*start*/ 0xAE6, WordBreakProperty.Numeric], + [/*start*/ 0xAF0, WordBreakProperty.Other], + [/*start*/ 0xAF9, WordBreakProperty.ALetter], + [/*start*/ 0xAFA, WordBreakProperty.Extend], + [/*start*/ 0xB00, WordBreakProperty.Other], + [/*start*/ 0xB01, WordBreakProperty.Extend], + [/*start*/ 0xB04, WordBreakProperty.Other], + [/*start*/ 0xB05, WordBreakProperty.ALetter], + [/*start*/ 0xB0D, WordBreakProperty.Other], + [/*start*/ 0xB0F, WordBreakProperty.ALetter], + [/*start*/ 0xB11, WordBreakProperty.Other], + [/*start*/ 0xB13, WordBreakProperty.ALetter], + [/*start*/ 0xB29, WordBreakProperty.Other], + [/*start*/ 0xB2A, WordBreakProperty.ALetter], + [/*start*/ 0xB31, WordBreakProperty.Other], + [/*start*/ 0xB32, WordBreakProperty.ALetter], + [/*start*/ 0xB34, WordBreakProperty.Other], + [/*start*/ 0xB35, WordBreakProperty.ALetter], + [/*start*/ 0xB3A, WordBreakProperty.Other], + [/*start*/ 0xB3C, WordBreakProperty.Extend], + [/*start*/ 0xB3D, WordBreakProperty.ALetter], + [/*start*/ 0xB3E, WordBreakProperty.Extend], + [/*start*/ 0xB45, WordBreakProperty.Other], + [/*start*/ 0xB47, WordBreakProperty.Extend], + [/*start*/ 0xB49, WordBreakProperty.Other], + [/*start*/ 0xB4B, WordBreakProperty.Extend], + [/*start*/ 0xB4E, WordBreakProperty.Other], + [/*start*/ 0xB55, WordBreakProperty.Extend], + [/*start*/ 0xB58, WordBreakProperty.Other], + [/*start*/ 0xB5C, WordBreakProperty.ALetter], + [/*start*/ 0xB5E, WordBreakProperty.Other], + [/*start*/ 0xB5F, WordBreakProperty.ALetter], + [/*start*/ 0xB62, WordBreakProperty.Extend], + [/*start*/ 0xB64, WordBreakProperty.Other], + [/*start*/ 0xB66, WordBreakProperty.Numeric], + [/*start*/ 0xB70, WordBreakProperty.Other], + [/*start*/ 0xB71, WordBreakProperty.ALetter], + [/*start*/ 0xB72, WordBreakProperty.Other], + [/*start*/ 0xB82, WordBreakProperty.Extend], + [/*start*/ 0xB83, WordBreakProperty.ALetter], + [/*start*/ 0xB84, WordBreakProperty.Other], + [/*start*/ 0xB85, WordBreakProperty.ALetter], + [/*start*/ 0xB8B, WordBreakProperty.Other], + [/*start*/ 0xB8E, WordBreakProperty.ALetter], + [/*start*/ 0xB91, WordBreakProperty.Other], + [/*start*/ 0xB92, WordBreakProperty.ALetter], + [/*start*/ 0xB96, WordBreakProperty.Other], + [/*start*/ 0xB99, WordBreakProperty.ALetter], + [/*start*/ 0xB9B, WordBreakProperty.Other], + [/*start*/ 0xB9C, WordBreakProperty.ALetter], + [/*start*/ 0xB9D, WordBreakProperty.Other], + [/*start*/ 0xB9E, WordBreakProperty.ALetter], + [/*start*/ 0xBA0, WordBreakProperty.Other], + [/*start*/ 0xBA3, WordBreakProperty.ALetter], + [/*start*/ 0xBA5, WordBreakProperty.Other], + [/*start*/ 0xBA8, WordBreakProperty.ALetter], + [/*start*/ 0xBAB, WordBreakProperty.Other], + [/*start*/ 0xBAE, WordBreakProperty.ALetter], + [/*start*/ 0xBBA, WordBreakProperty.Other], + [/*start*/ 0xBBE, WordBreakProperty.Extend], + [/*start*/ 0xBC3, WordBreakProperty.Other], + [/*start*/ 0xBC6, WordBreakProperty.Extend], + [/*start*/ 0xBC9, WordBreakProperty.Other], + [/*start*/ 0xBCA, WordBreakProperty.Extend], + [/*start*/ 0xBCE, WordBreakProperty.Other], + [/*start*/ 0xBD0, WordBreakProperty.ALetter], + [/*start*/ 0xBD1, WordBreakProperty.Other], + [/*start*/ 0xBD7, WordBreakProperty.Extend], + [/*start*/ 0xBD8, WordBreakProperty.Other], + [/*start*/ 0xBE6, WordBreakProperty.Numeric], + [/*start*/ 0xBF0, WordBreakProperty.Other], + [/*start*/ 0xC00, WordBreakProperty.Extend], + [/*start*/ 0xC05, WordBreakProperty.ALetter], + [/*start*/ 0xC0D, WordBreakProperty.Other], + [/*start*/ 0xC0E, WordBreakProperty.ALetter], + [/*start*/ 0xC11, WordBreakProperty.Other], + [/*start*/ 0xC12, WordBreakProperty.ALetter], + [/*start*/ 0xC29, WordBreakProperty.Other], + [/*start*/ 0xC2A, WordBreakProperty.ALetter], + [/*start*/ 0xC3A, WordBreakProperty.Other], + [/*start*/ 0xC3D, WordBreakProperty.ALetter], + [/*start*/ 0xC3E, WordBreakProperty.Extend], + [/*start*/ 0xC45, WordBreakProperty.Other], + [/*start*/ 0xC46, WordBreakProperty.Extend], + [/*start*/ 0xC49, WordBreakProperty.Other], + [/*start*/ 0xC4A, WordBreakProperty.Extend], + [/*start*/ 0xC4E, WordBreakProperty.Other], + [/*start*/ 0xC55, WordBreakProperty.Extend], + [/*start*/ 0xC57, WordBreakProperty.Other], + [/*start*/ 0xC58, WordBreakProperty.ALetter], + [/*start*/ 0xC5B, WordBreakProperty.Other], + [/*start*/ 0xC60, WordBreakProperty.ALetter], + [/*start*/ 0xC62, WordBreakProperty.Extend], + [/*start*/ 0xC64, WordBreakProperty.Other], + [/*start*/ 0xC66, WordBreakProperty.Numeric], + [/*start*/ 0xC70, WordBreakProperty.Other], + [/*start*/ 0xC80, WordBreakProperty.ALetter], + [/*start*/ 0xC81, WordBreakProperty.Extend], + [/*start*/ 0xC84, WordBreakProperty.Other], + [/*start*/ 0xC85, WordBreakProperty.ALetter], + [/*start*/ 0xC8D, WordBreakProperty.Other], + [/*start*/ 0xC8E, WordBreakProperty.ALetter], + [/*start*/ 0xC91, WordBreakProperty.Other], + [/*start*/ 0xC92, WordBreakProperty.ALetter], + [/*start*/ 0xCA9, WordBreakProperty.Other], + [/*start*/ 0xCAA, WordBreakProperty.ALetter], + [/*start*/ 0xCB4, WordBreakProperty.Other], + [/*start*/ 0xCB5, WordBreakProperty.ALetter], + [/*start*/ 0xCBA, WordBreakProperty.Other], + [/*start*/ 0xCBC, WordBreakProperty.Extend], + [/*start*/ 0xCBD, WordBreakProperty.ALetter], + [/*start*/ 0xCBE, WordBreakProperty.Extend], + [/*start*/ 0xCC5, WordBreakProperty.Other], + [/*start*/ 0xCC6, WordBreakProperty.Extend], + [/*start*/ 0xCC9, WordBreakProperty.Other], + [/*start*/ 0xCCA, WordBreakProperty.Extend], + [/*start*/ 0xCCE, WordBreakProperty.Other], + [/*start*/ 0xCD5, WordBreakProperty.Extend], + [/*start*/ 0xCD7, WordBreakProperty.Other], + [/*start*/ 0xCDE, WordBreakProperty.ALetter], + [/*start*/ 0xCDF, WordBreakProperty.Other], + [/*start*/ 0xCE0, WordBreakProperty.ALetter], + [/*start*/ 0xCE2, WordBreakProperty.Extend], + [/*start*/ 0xCE4, WordBreakProperty.Other], + [/*start*/ 0xCE6, WordBreakProperty.Numeric], + [/*start*/ 0xCF0, WordBreakProperty.Other], + [/*start*/ 0xCF1, WordBreakProperty.ALetter], + [/*start*/ 0xCF3, WordBreakProperty.Other], + [/*start*/ 0xD00, WordBreakProperty.Extend], + [/*start*/ 0xD04, WordBreakProperty.ALetter], + [/*start*/ 0xD0D, WordBreakProperty.Other], + [/*start*/ 0xD0E, WordBreakProperty.ALetter], + [/*start*/ 0xD11, WordBreakProperty.Other], + [/*start*/ 0xD12, WordBreakProperty.ALetter], + [/*start*/ 0xD3B, WordBreakProperty.Extend], + [/*start*/ 0xD3D, WordBreakProperty.ALetter], + [/*start*/ 0xD3E, WordBreakProperty.Extend], + [/*start*/ 0xD45, WordBreakProperty.Other], + [/*start*/ 0xD46, WordBreakProperty.Extend], + [/*start*/ 0xD49, WordBreakProperty.Other], + [/*start*/ 0xD4A, WordBreakProperty.Extend], + [/*start*/ 0xD4E, WordBreakProperty.ALetter], + [/*start*/ 0xD4F, WordBreakProperty.Other], + [/*start*/ 0xD54, WordBreakProperty.ALetter], + [/*start*/ 0xD57, WordBreakProperty.Extend], + [/*start*/ 0xD58, WordBreakProperty.Other], + [/*start*/ 0xD5F, WordBreakProperty.ALetter], + [/*start*/ 0xD62, WordBreakProperty.Extend], + [/*start*/ 0xD64, WordBreakProperty.Other], + [/*start*/ 0xD66, WordBreakProperty.Numeric], + [/*start*/ 0xD70, WordBreakProperty.Other], + [/*start*/ 0xD7A, WordBreakProperty.ALetter], + [/*start*/ 0xD80, WordBreakProperty.Other], + [/*start*/ 0xD81, WordBreakProperty.Extend], + [/*start*/ 0xD84, WordBreakProperty.Other], + [/*start*/ 0xD85, WordBreakProperty.ALetter], + [/*start*/ 0xD97, WordBreakProperty.Other], + [/*start*/ 0xD9A, WordBreakProperty.ALetter], + [/*start*/ 0xDB2, WordBreakProperty.Other], + [/*start*/ 0xDB3, WordBreakProperty.ALetter], + [/*start*/ 0xDBC, WordBreakProperty.Other], + [/*start*/ 0xDBD, WordBreakProperty.ALetter], + [/*start*/ 0xDBE, WordBreakProperty.Other], + [/*start*/ 0xDC0, WordBreakProperty.ALetter], + [/*start*/ 0xDC7, WordBreakProperty.Other], + [/*start*/ 0xDCA, WordBreakProperty.Extend], + [/*start*/ 0xDCB, WordBreakProperty.Other], + [/*start*/ 0xDCF, WordBreakProperty.Extend], + [/*start*/ 0xDD5, WordBreakProperty.Other], + [/*start*/ 0xDD6, WordBreakProperty.Extend], + [/*start*/ 0xDD7, WordBreakProperty.Other], + [/*start*/ 0xDD8, WordBreakProperty.Extend], + [/*start*/ 0xDE0, WordBreakProperty.Other], + [/*start*/ 0xDE6, WordBreakProperty.Numeric], + [/*start*/ 0xDF0, WordBreakProperty.Other], + [/*start*/ 0xDF2, WordBreakProperty.Extend], + [/*start*/ 0xDF4, WordBreakProperty.Other], + [/*start*/ 0xE31, WordBreakProperty.Extend], + [/*start*/ 0xE32, WordBreakProperty.Other], + [/*start*/ 0xE34, WordBreakProperty.Extend], + [/*start*/ 0xE3B, WordBreakProperty.Other], + [/*start*/ 0xE47, WordBreakProperty.Extend], + [/*start*/ 0xE4F, WordBreakProperty.Other], + [/*start*/ 0xE50, WordBreakProperty.Numeric], + [/*start*/ 0xE5A, WordBreakProperty.Other], + [/*start*/ 0xEB1, WordBreakProperty.Extend], + [/*start*/ 0xEB2, WordBreakProperty.Other], + [/*start*/ 0xEB4, WordBreakProperty.Extend], + [/*start*/ 0xEBD, WordBreakProperty.Other], + [/*start*/ 0xEC8, WordBreakProperty.Extend], + [/*start*/ 0xECE, WordBreakProperty.Other], + [/*start*/ 0xED0, WordBreakProperty.Numeric], + [/*start*/ 0xEDA, WordBreakProperty.Other], + [/*start*/ 0xF00, WordBreakProperty.ALetter], + [/*start*/ 0xF01, WordBreakProperty.Other], + [/*start*/ 0xF18, WordBreakProperty.Extend], + [/*start*/ 0xF1A, WordBreakProperty.Other], + [/*start*/ 0xF20, WordBreakProperty.Numeric], + [/*start*/ 0xF2A, WordBreakProperty.Other], + [/*start*/ 0xF35, WordBreakProperty.Extend], + [/*start*/ 0xF36, WordBreakProperty.Other], + [/*start*/ 0xF37, WordBreakProperty.Extend], + [/*start*/ 0xF38, WordBreakProperty.Other], + [/*start*/ 0xF39, WordBreakProperty.Extend], + [/*start*/ 0xF3A, WordBreakProperty.Other], + [/*start*/ 0xF3E, WordBreakProperty.Extend], + [/*start*/ 0xF40, WordBreakProperty.ALetter], + [/*start*/ 0xF48, WordBreakProperty.Other], + [/*start*/ 0xF49, WordBreakProperty.ALetter], + [/*start*/ 0xF6D, WordBreakProperty.Other], + [/*start*/ 0xF71, WordBreakProperty.Extend], + [/*start*/ 0xF85, WordBreakProperty.Other], + [/*start*/ 0xF86, WordBreakProperty.Extend], + [/*start*/ 0xF88, WordBreakProperty.ALetter], + [/*start*/ 0xF8D, WordBreakProperty.Extend], + [/*start*/ 0xF98, WordBreakProperty.Other], + [/*start*/ 0xF99, WordBreakProperty.Extend], + [/*start*/ 0xFBD, WordBreakProperty.Other], + [/*start*/ 0xFC6, WordBreakProperty.Extend], + [/*start*/ 0xFC7, WordBreakProperty.Other], + [/*start*/ 0x102B, WordBreakProperty.Extend], + [/*start*/ 0x103F, WordBreakProperty.Other], + [/*start*/ 0x1040, WordBreakProperty.Numeric], + [/*start*/ 0x104A, WordBreakProperty.Other], + [/*start*/ 0x1056, WordBreakProperty.Extend], + [/*start*/ 0x105A, WordBreakProperty.Other], + [/*start*/ 0x105E, WordBreakProperty.Extend], + [/*start*/ 0x1061, WordBreakProperty.Other], + [/*start*/ 0x1062, WordBreakProperty.Extend], + [/*start*/ 0x1065, WordBreakProperty.Other], + [/*start*/ 0x1067, WordBreakProperty.Extend], + [/*start*/ 0x106E, WordBreakProperty.Other], + [/*start*/ 0x1071, WordBreakProperty.Extend], + [/*start*/ 0x1075, WordBreakProperty.Other], + [/*start*/ 0x1082, WordBreakProperty.Extend], + [/*start*/ 0x108E, WordBreakProperty.Other], + [/*start*/ 0x108F, WordBreakProperty.Extend], + [/*start*/ 0x1090, WordBreakProperty.Numeric], + [/*start*/ 0x109A, WordBreakProperty.Extend], + [/*start*/ 0x109E, WordBreakProperty.Other], + [/*start*/ 0x10A0, WordBreakProperty.ALetter], + [/*start*/ 0x10C6, WordBreakProperty.Other], + [/*start*/ 0x10C7, WordBreakProperty.ALetter], + [/*start*/ 0x10C8, WordBreakProperty.Other], + [/*start*/ 0x10CD, WordBreakProperty.ALetter], + [/*start*/ 0x10CE, WordBreakProperty.Other], + [/*start*/ 0x10D0, WordBreakProperty.ALetter], + [/*start*/ 0x10FB, WordBreakProperty.Other], + [/*start*/ 0x10FC, WordBreakProperty.ALetter], + [/*start*/ 0x1249, WordBreakProperty.Other], + [/*start*/ 0x124A, WordBreakProperty.ALetter], + [/*start*/ 0x124E, WordBreakProperty.Other], + [/*start*/ 0x1250, WordBreakProperty.ALetter], + [/*start*/ 0x1257, WordBreakProperty.Other], + [/*start*/ 0x1258, WordBreakProperty.ALetter], + [/*start*/ 0x1259, WordBreakProperty.Other], + [/*start*/ 0x125A, WordBreakProperty.ALetter], + [/*start*/ 0x125E, WordBreakProperty.Other], + [/*start*/ 0x1260, WordBreakProperty.ALetter], + [/*start*/ 0x1289, WordBreakProperty.Other], + [/*start*/ 0x128A, WordBreakProperty.ALetter], + [/*start*/ 0x128E, WordBreakProperty.Other], + [/*start*/ 0x1290, WordBreakProperty.ALetter], + [/*start*/ 0x12B1, WordBreakProperty.Other], + [/*start*/ 0x12B2, WordBreakProperty.ALetter], + [/*start*/ 0x12B6, WordBreakProperty.Other], + [/*start*/ 0x12B8, WordBreakProperty.ALetter], + [/*start*/ 0x12BF, WordBreakProperty.Other], + [/*start*/ 0x12C0, WordBreakProperty.ALetter], + [/*start*/ 0x12C1, WordBreakProperty.Other], + [/*start*/ 0x12C2, WordBreakProperty.ALetter], + [/*start*/ 0x12C6, WordBreakProperty.Other], + [/*start*/ 0x12C8, WordBreakProperty.ALetter], + [/*start*/ 0x12D7, WordBreakProperty.Other], + [/*start*/ 0x12D8, WordBreakProperty.ALetter], + [/*start*/ 0x1311, WordBreakProperty.Other], + [/*start*/ 0x1312, WordBreakProperty.ALetter], + [/*start*/ 0x1316, WordBreakProperty.Other], + [/*start*/ 0x1318, WordBreakProperty.ALetter], + [/*start*/ 0x135B, WordBreakProperty.Other], + [/*start*/ 0x135D, WordBreakProperty.Extend], + [/*start*/ 0x1360, WordBreakProperty.Other], + [/*start*/ 0x1380, WordBreakProperty.ALetter], + [/*start*/ 0x1390, WordBreakProperty.Other], + [/*start*/ 0x13A0, WordBreakProperty.ALetter], + [/*start*/ 0x13F6, WordBreakProperty.Other], + [/*start*/ 0x13F8, WordBreakProperty.ALetter], + [/*start*/ 0x13FE, WordBreakProperty.Other], + [/*start*/ 0x1401, WordBreakProperty.ALetter], + [/*start*/ 0x166D, WordBreakProperty.Other], + [/*start*/ 0x166F, WordBreakProperty.ALetter], + [/*start*/ 0x1680, WordBreakProperty.WSegSpace], + [/*start*/ 0x1681, WordBreakProperty.ALetter], + [/*start*/ 0x169B, WordBreakProperty.Other], + [/*start*/ 0x16A0, WordBreakProperty.ALetter], + [/*start*/ 0x16EB, WordBreakProperty.Other], + [/*start*/ 0x16EE, WordBreakProperty.ALetter], + [/*start*/ 0x16F9, WordBreakProperty.Other], + [/*start*/ 0x1700, WordBreakProperty.ALetter], + [/*start*/ 0x170D, WordBreakProperty.Other], + [/*start*/ 0x170E, WordBreakProperty.ALetter], + [/*start*/ 0x1712, WordBreakProperty.Extend], + [/*start*/ 0x1715, WordBreakProperty.Other], + [/*start*/ 0x1720, WordBreakProperty.ALetter], + [/*start*/ 0x1732, WordBreakProperty.Extend], + [/*start*/ 0x1735, WordBreakProperty.Other], + [/*start*/ 0x1740, WordBreakProperty.ALetter], + [/*start*/ 0x1752, WordBreakProperty.Extend], + [/*start*/ 0x1754, WordBreakProperty.Other], + [/*start*/ 0x1760, WordBreakProperty.ALetter], + [/*start*/ 0x176D, WordBreakProperty.Other], + [/*start*/ 0x176E, WordBreakProperty.ALetter], + [/*start*/ 0x1771, WordBreakProperty.Other], + [/*start*/ 0x1772, WordBreakProperty.Extend], + [/*start*/ 0x1774, WordBreakProperty.Other], + [/*start*/ 0x17B4, WordBreakProperty.Extend], + [/*start*/ 0x17D4, WordBreakProperty.Other], + [/*start*/ 0x17DD, WordBreakProperty.Extend], + [/*start*/ 0x17DE, WordBreakProperty.Other], + [/*start*/ 0x17E0, WordBreakProperty.Numeric], + [/*start*/ 0x17EA, WordBreakProperty.Other], + [/*start*/ 0x180B, WordBreakProperty.Extend], + [/*start*/ 0x180E, WordBreakProperty.Format], + [/*start*/ 0x180F, WordBreakProperty.Other], + [/*start*/ 0x1810, WordBreakProperty.Numeric], + [/*start*/ 0x181A, WordBreakProperty.Other], + [/*start*/ 0x1820, WordBreakProperty.ALetter], + [/*start*/ 0x1879, WordBreakProperty.Other], + [/*start*/ 0x1880, WordBreakProperty.ALetter], + [/*start*/ 0x1885, WordBreakProperty.Extend], + [/*start*/ 0x1887, WordBreakProperty.ALetter], + [/*start*/ 0x18A9, WordBreakProperty.Extend], + [/*start*/ 0x18AA, WordBreakProperty.ALetter], + [/*start*/ 0x18AB, WordBreakProperty.Other], + [/*start*/ 0x18B0, WordBreakProperty.ALetter], + [/*start*/ 0x18F6, WordBreakProperty.Other], + [/*start*/ 0x1900, WordBreakProperty.ALetter], + [/*start*/ 0x191F, WordBreakProperty.Other], + [/*start*/ 0x1920, WordBreakProperty.Extend], + [/*start*/ 0x192C, WordBreakProperty.Other], + [/*start*/ 0x1930, WordBreakProperty.Extend], + [/*start*/ 0x193C, WordBreakProperty.Other], + [/*start*/ 0x1946, WordBreakProperty.Numeric], + [/*start*/ 0x1950, WordBreakProperty.Other], + [/*start*/ 0x19D0, WordBreakProperty.Numeric], + [/*start*/ 0x19DA, WordBreakProperty.Other], + [/*start*/ 0x1A00, WordBreakProperty.ALetter], + [/*start*/ 0x1A17, WordBreakProperty.Extend], + [/*start*/ 0x1A1C, WordBreakProperty.Other], + [/*start*/ 0x1A55, WordBreakProperty.Extend], + [/*start*/ 0x1A5F, WordBreakProperty.Other], + [/*start*/ 0x1A60, WordBreakProperty.Extend], + [/*start*/ 0x1A7D, WordBreakProperty.Other], + [/*start*/ 0x1A7F, WordBreakProperty.Extend], + [/*start*/ 0x1A80, WordBreakProperty.Numeric], + [/*start*/ 0x1A8A, WordBreakProperty.Other], + [/*start*/ 0x1A90, WordBreakProperty.Numeric], + [/*start*/ 0x1A9A, WordBreakProperty.Other], + [/*start*/ 0x1AB0, WordBreakProperty.Extend], + [/*start*/ 0x1AC1, WordBreakProperty.Other], + [/*start*/ 0x1B00, WordBreakProperty.Extend], + [/*start*/ 0x1B05, WordBreakProperty.ALetter], + [/*start*/ 0x1B34, WordBreakProperty.Extend], + [/*start*/ 0x1B45, WordBreakProperty.ALetter], + [/*start*/ 0x1B4C, WordBreakProperty.Other], + [/*start*/ 0x1B50, WordBreakProperty.Numeric], + [/*start*/ 0x1B5A, WordBreakProperty.Other], + [/*start*/ 0x1B6B, WordBreakProperty.Extend], + [/*start*/ 0x1B74, WordBreakProperty.Other], + [/*start*/ 0x1B80, WordBreakProperty.Extend], + [/*start*/ 0x1B83, WordBreakProperty.ALetter], + [/*start*/ 0x1BA1, WordBreakProperty.Extend], + [/*start*/ 0x1BAE, WordBreakProperty.ALetter], + [/*start*/ 0x1BB0, WordBreakProperty.Numeric], + [/*start*/ 0x1BBA, WordBreakProperty.ALetter], + [/*start*/ 0x1BE6, WordBreakProperty.Extend], + [/*start*/ 0x1BF4, WordBreakProperty.Other], + [/*start*/ 0x1C00, WordBreakProperty.ALetter], + [/*start*/ 0x1C24, WordBreakProperty.Extend], + [/*start*/ 0x1C38, WordBreakProperty.Other], + [/*start*/ 0x1C40, WordBreakProperty.Numeric], + [/*start*/ 0x1C4A, WordBreakProperty.Other], + [/*start*/ 0x1C4D, WordBreakProperty.ALetter], + [/*start*/ 0x1C50, WordBreakProperty.Numeric], + [/*start*/ 0x1C5A, WordBreakProperty.ALetter], + [/*start*/ 0x1C7E, WordBreakProperty.Other], + [/*start*/ 0x1C80, WordBreakProperty.ALetter], + [/*start*/ 0x1C89, WordBreakProperty.Other], + [/*start*/ 0x1C90, WordBreakProperty.ALetter], + [/*start*/ 0x1CBB, WordBreakProperty.Other], + [/*start*/ 0x1CBD, WordBreakProperty.ALetter], + [/*start*/ 0x1CC0, WordBreakProperty.Other], + [/*start*/ 0x1CD0, WordBreakProperty.Extend], + [/*start*/ 0x1CD3, WordBreakProperty.Other], + [/*start*/ 0x1CD4, WordBreakProperty.Extend], + [/*start*/ 0x1CE9, WordBreakProperty.ALetter], + [/*start*/ 0x1CED, WordBreakProperty.Extend], + [/*start*/ 0x1CEE, WordBreakProperty.ALetter], + [/*start*/ 0x1CF4, WordBreakProperty.Extend], + [/*start*/ 0x1CF5, WordBreakProperty.ALetter], + [/*start*/ 0x1CF7, WordBreakProperty.Extend], + [/*start*/ 0x1CFA, WordBreakProperty.ALetter], + [/*start*/ 0x1CFB, WordBreakProperty.Other], + [/*start*/ 0x1D00, WordBreakProperty.ALetter], + [/*start*/ 0x1DC0, WordBreakProperty.Extend], + [/*start*/ 0x1DFA, WordBreakProperty.Other], + [/*start*/ 0x1DFB, WordBreakProperty.Extend], + [/*start*/ 0x1E00, WordBreakProperty.ALetter], + [/*start*/ 0x1F16, WordBreakProperty.Other], + [/*start*/ 0x1F18, WordBreakProperty.ALetter], + [/*start*/ 0x1F1E, WordBreakProperty.Other], + [/*start*/ 0x1F20, WordBreakProperty.ALetter], + [/*start*/ 0x1F46, WordBreakProperty.Other], + [/*start*/ 0x1F48, WordBreakProperty.ALetter], + [/*start*/ 0x1F4E, WordBreakProperty.Other], + [/*start*/ 0x1F50, WordBreakProperty.ALetter], + [/*start*/ 0x1F58, WordBreakProperty.Other], + [/*start*/ 0x1F59, WordBreakProperty.ALetter], + [/*start*/ 0x1F5A, WordBreakProperty.Other], + [/*start*/ 0x1F5B, WordBreakProperty.ALetter], + [/*start*/ 0x1F5C, WordBreakProperty.Other], + [/*start*/ 0x1F5D, WordBreakProperty.ALetter], + [/*start*/ 0x1F5E, WordBreakProperty.Other], + [/*start*/ 0x1F5F, WordBreakProperty.ALetter], + [/*start*/ 0x1F7E, WordBreakProperty.Other], + [/*start*/ 0x1F80, WordBreakProperty.ALetter], + [/*start*/ 0x1FB5, WordBreakProperty.Other], + [/*start*/ 0x1FB6, WordBreakProperty.ALetter], + [/*start*/ 0x1FBD, WordBreakProperty.Other], + [/*start*/ 0x1FBE, WordBreakProperty.ALetter], + [/*start*/ 0x1FBF, WordBreakProperty.Other], + [/*start*/ 0x1FC2, WordBreakProperty.ALetter], + [/*start*/ 0x1FC5, WordBreakProperty.Other], + [/*start*/ 0x1FC6, WordBreakProperty.ALetter], + [/*start*/ 0x1FCD, WordBreakProperty.Other], + [/*start*/ 0x1FD0, WordBreakProperty.ALetter], + [/*start*/ 0x1FD4, WordBreakProperty.Other], + [/*start*/ 0x1FD6, WordBreakProperty.ALetter], + [/*start*/ 0x1FDC, WordBreakProperty.Other], + [/*start*/ 0x1FE0, WordBreakProperty.ALetter], + [/*start*/ 0x1FED, WordBreakProperty.Other], + [/*start*/ 0x1FF2, WordBreakProperty.ALetter], + [/*start*/ 0x1FF5, WordBreakProperty.Other], + [/*start*/ 0x1FF6, WordBreakProperty.ALetter], + [/*start*/ 0x1FFD, WordBreakProperty.Other], + [/*start*/ 0x2000, WordBreakProperty.WSegSpace], + [/*start*/ 0x2007, WordBreakProperty.Other], + [/*start*/ 0x2008, WordBreakProperty.WSegSpace], + [/*start*/ 0x200B, WordBreakProperty.Other], + [/*start*/ 0x200C, WordBreakProperty.Extend], + [/*start*/ 0x200D, WordBreakProperty.ZWJ], + [/*start*/ 0x200E, WordBreakProperty.Format], + [/*start*/ 0x2010, WordBreakProperty.Other], + [/*start*/ 0x2018, WordBreakProperty.MidNumLet], + [/*start*/ 0x201A, WordBreakProperty.Other], + [/*start*/ 0x2024, WordBreakProperty.MidNumLet], + [/*start*/ 0x2025, WordBreakProperty.Other], + [/*start*/ 0x2027, WordBreakProperty.MidLetter], + [/*start*/ 0x2028, WordBreakProperty.Newline], + [/*start*/ 0x202A, WordBreakProperty.Format], + [/*start*/ 0x202F, WordBreakProperty.ExtendNumLet], + [/*start*/ 0x2030, WordBreakProperty.Other], + [/*start*/ 0x203F, WordBreakProperty.ExtendNumLet], + [/*start*/ 0x2041, WordBreakProperty.Other], + [/*start*/ 0x2044, WordBreakProperty.MidNum], + [/*start*/ 0x2045, WordBreakProperty.Other], + [/*start*/ 0x2054, WordBreakProperty.ExtendNumLet], + [/*start*/ 0x2055, WordBreakProperty.Other], + [/*start*/ 0x205F, WordBreakProperty.WSegSpace], + [/*start*/ 0x2060, WordBreakProperty.Format], + [/*start*/ 0x2065, WordBreakProperty.Other], + [/*start*/ 0x2066, WordBreakProperty.Format], + [/*start*/ 0x2070, WordBreakProperty.Other], + [/*start*/ 0x2071, WordBreakProperty.ALetter], + [/*start*/ 0x2072, WordBreakProperty.Other], + [/*start*/ 0x207F, WordBreakProperty.ALetter], + [/*start*/ 0x2080, WordBreakProperty.Other], + [/*start*/ 0x2090, WordBreakProperty.ALetter], + [/*start*/ 0x209D, WordBreakProperty.Other], + [/*start*/ 0x20D0, WordBreakProperty.Extend], + [/*start*/ 0x20F1, WordBreakProperty.Other], + [/*start*/ 0x2102, WordBreakProperty.ALetter], + [/*start*/ 0x2103, WordBreakProperty.Other], + [/*start*/ 0x2107, WordBreakProperty.ALetter], + [/*start*/ 0x2108, WordBreakProperty.Other], + [/*start*/ 0x210A, WordBreakProperty.ALetter], + [/*start*/ 0x2114, WordBreakProperty.Other], + [/*start*/ 0x2115, WordBreakProperty.ALetter], + [/*start*/ 0x2116, WordBreakProperty.Other], + [/*start*/ 0x2119, WordBreakProperty.ALetter], + [/*start*/ 0x211E, WordBreakProperty.Other], + [/*start*/ 0x2124, WordBreakProperty.ALetter], + [/*start*/ 0x2125, WordBreakProperty.Other], + [/*start*/ 0x2126, WordBreakProperty.ALetter], + [/*start*/ 0x2127, WordBreakProperty.Other], + [/*start*/ 0x2128, WordBreakProperty.ALetter], + [/*start*/ 0x2129, WordBreakProperty.Other], + [/*start*/ 0x212A, WordBreakProperty.ALetter], + [/*start*/ 0x212E, WordBreakProperty.Other], + [/*start*/ 0x212F, WordBreakProperty.ALetter], + [/*start*/ 0x213A, WordBreakProperty.Other], + [/*start*/ 0x213C, WordBreakProperty.ALetter], + [/*start*/ 0x2140, WordBreakProperty.Other], + [/*start*/ 0x2145, WordBreakProperty.ALetter], + [/*start*/ 0x214A, WordBreakProperty.Other], + [/*start*/ 0x214E, WordBreakProperty.ALetter], + [/*start*/ 0x214F, WordBreakProperty.Other], + [/*start*/ 0x2160, WordBreakProperty.ALetter], + [/*start*/ 0x2189, WordBreakProperty.Other], + [/*start*/ 0x24B6, WordBreakProperty.ALetter], + [/*start*/ 0x24EA, WordBreakProperty.Other], + [/*start*/ 0x2C00, WordBreakProperty.ALetter], + [/*start*/ 0x2C2F, WordBreakProperty.Other], + [/*start*/ 0x2C30, WordBreakProperty.ALetter], + [/*start*/ 0x2C5F, WordBreakProperty.Other], + [/*start*/ 0x2C60, WordBreakProperty.ALetter], + [/*start*/ 0x2CE5, WordBreakProperty.Other], + [/*start*/ 0x2CEB, WordBreakProperty.ALetter], + [/*start*/ 0x2CEF, WordBreakProperty.Extend], + [/*start*/ 0x2CF2, WordBreakProperty.ALetter], + [/*start*/ 0x2CF4, WordBreakProperty.Other], + [/*start*/ 0x2D00, WordBreakProperty.ALetter], + [/*start*/ 0x2D26, WordBreakProperty.Other], + [/*start*/ 0x2D27, WordBreakProperty.ALetter], + [/*start*/ 0x2D28, WordBreakProperty.Other], + [/*start*/ 0x2D2D, WordBreakProperty.ALetter], + [/*start*/ 0x2D2E, WordBreakProperty.Other], + [/*start*/ 0x2D30, WordBreakProperty.ALetter], + [/*start*/ 0x2D68, WordBreakProperty.Other], + [/*start*/ 0x2D6F, WordBreakProperty.ALetter], + [/*start*/ 0x2D70, WordBreakProperty.Other], + [/*start*/ 0x2D7F, WordBreakProperty.Extend], + [/*start*/ 0x2D80, WordBreakProperty.ALetter], + [/*start*/ 0x2D97, WordBreakProperty.Other], + [/*start*/ 0x2DA0, WordBreakProperty.ALetter], + [/*start*/ 0x2DA7, WordBreakProperty.Other], + [/*start*/ 0x2DA8, WordBreakProperty.ALetter], + [/*start*/ 0x2DAF, WordBreakProperty.Other], + [/*start*/ 0x2DB0, WordBreakProperty.ALetter], + [/*start*/ 0x2DB7, WordBreakProperty.Other], + [/*start*/ 0x2DB8, WordBreakProperty.ALetter], + [/*start*/ 0x2DBF, WordBreakProperty.Other], + [/*start*/ 0x2DC0, WordBreakProperty.ALetter], + [/*start*/ 0x2DC7, WordBreakProperty.Other], + [/*start*/ 0x2DC8, WordBreakProperty.ALetter], + [/*start*/ 0x2DCF, WordBreakProperty.Other], + [/*start*/ 0x2DD0, WordBreakProperty.ALetter], + [/*start*/ 0x2DD7, WordBreakProperty.Other], + [/*start*/ 0x2DD8, WordBreakProperty.ALetter], + [/*start*/ 0x2DDF, WordBreakProperty.Other], + [/*start*/ 0x2DE0, WordBreakProperty.Extend], + [/*start*/ 0x2E00, WordBreakProperty.Other], + [/*start*/ 0x2E2F, WordBreakProperty.ALetter], + [/*start*/ 0x2E30, WordBreakProperty.Other], + [/*start*/ 0x3000, WordBreakProperty.WSegSpace], + [/*start*/ 0x3001, WordBreakProperty.Other], + [/*start*/ 0x3005, WordBreakProperty.ALetter], + [/*start*/ 0x3006, WordBreakProperty.Other], + [/*start*/ 0x302A, WordBreakProperty.Extend], + [/*start*/ 0x3030, WordBreakProperty.Other], + [/*start*/ 0x3031, WordBreakProperty.Katakana], + [/*start*/ 0x3036, WordBreakProperty.Other], + [/*start*/ 0x303B, WordBreakProperty.ALetter], + [/*start*/ 0x303D, WordBreakProperty.Other], + [/*start*/ 0x3099, WordBreakProperty.Extend], + [/*start*/ 0x309B, WordBreakProperty.Katakana], + [/*start*/ 0x309D, WordBreakProperty.Other], + [/*start*/ 0x30A0, WordBreakProperty.Katakana], + [/*start*/ 0x30FB, WordBreakProperty.Other], + [/*start*/ 0x30FC, WordBreakProperty.Katakana], + [/*start*/ 0x3100, WordBreakProperty.Other], + [/*start*/ 0x3105, WordBreakProperty.ALetter], + [/*start*/ 0x3130, WordBreakProperty.Other], + [/*start*/ 0x3131, WordBreakProperty.ALetter], + [/*start*/ 0x318F, WordBreakProperty.Other], + [/*start*/ 0x31A0, WordBreakProperty.ALetter], + [/*start*/ 0x31C0, WordBreakProperty.Other], + [/*start*/ 0x31F0, WordBreakProperty.Katakana], + [/*start*/ 0x3200, WordBreakProperty.Other], + [/*start*/ 0x32D0, WordBreakProperty.Katakana], + [/*start*/ 0x32FF, WordBreakProperty.Other], + [/*start*/ 0x3300, WordBreakProperty.Katakana], + [/*start*/ 0x3358, WordBreakProperty.Other], + [/*start*/ 0xA000, WordBreakProperty.ALetter], + [/*start*/ 0xA48D, WordBreakProperty.Other], + [/*start*/ 0xA4D0, WordBreakProperty.ALetter], + [/*start*/ 0xA4FE, WordBreakProperty.Other], + [/*start*/ 0xA500, WordBreakProperty.ALetter], + [/*start*/ 0xA60D, WordBreakProperty.Other], + [/*start*/ 0xA610, WordBreakProperty.ALetter], + [/*start*/ 0xA620, WordBreakProperty.Numeric], + [/*start*/ 0xA62A, WordBreakProperty.ALetter], + [/*start*/ 0xA62C, WordBreakProperty.Other], + [/*start*/ 0xA640, WordBreakProperty.ALetter], + [/*start*/ 0xA66F, WordBreakProperty.Extend], + [/*start*/ 0xA673, WordBreakProperty.Other], + [/*start*/ 0xA674, WordBreakProperty.Extend], + [/*start*/ 0xA67E, WordBreakProperty.Other], + [/*start*/ 0xA67F, WordBreakProperty.ALetter], + [/*start*/ 0xA69E, WordBreakProperty.Extend], + [/*start*/ 0xA6A0, WordBreakProperty.ALetter], + [/*start*/ 0xA6F0, WordBreakProperty.Extend], + [/*start*/ 0xA6F2, WordBreakProperty.Other], + [/*start*/ 0xA708, WordBreakProperty.ALetter], + [/*start*/ 0xA7C0, WordBreakProperty.Other], + [/*start*/ 0xA7C2, WordBreakProperty.ALetter], + [/*start*/ 0xA7CB, WordBreakProperty.Other], + [/*start*/ 0xA7F5, WordBreakProperty.ALetter], + [/*start*/ 0xA802, WordBreakProperty.Extend], + [/*start*/ 0xA803, WordBreakProperty.ALetter], + [/*start*/ 0xA806, WordBreakProperty.Extend], + [/*start*/ 0xA807, WordBreakProperty.ALetter], + [/*start*/ 0xA80B, WordBreakProperty.Extend], + [/*start*/ 0xA80C, WordBreakProperty.ALetter], + [/*start*/ 0xA823, WordBreakProperty.Extend], + [/*start*/ 0xA828, WordBreakProperty.Other], + [/*start*/ 0xA82C, WordBreakProperty.Extend], + [/*start*/ 0xA82D, WordBreakProperty.Other], + [/*start*/ 0xA840, WordBreakProperty.ALetter], + [/*start*/ 0xA874, WordBreakProperty.Other], + [/*start*/ 0xA880, WordBreakProperty.Extend], + [/*start*/ 0xA882, WordBreakProperty.ALetter], + [/*start*/ 0xA8B4, WordBreakProperty.Extend], + [/*start*/ 0xA8C6, WordBreakProperty.Other], + [/*start*/ 0xA8D0, WordBreakProperty.Numeric], + [/*start*/ 0xA8DA, WordBreakProperty.Other], + [/*start*/ 0xA8E0, WordBreakProperty.Extend], + [/*start*/ 0xA8F2, WordBreakProperty.ALetter], + [/*start*/ 0xA8F8, WordBreakProperty.Other], + [/*start*/ 0xA8FB, WordBreakProperty.ALetter], + [/*start*/ 0xA8FC, WordBreakProperty.Other], + [/*start*/ 0xA8FD, WordBreakProperty.ALetter], + [/*start*/ 0xA8FF, WordBreakProperty.Extend], + [/*start*/ 0xA900, WordBreakProperty.Numeric], + [/*start*/ 0xA90A, WordBreakProperty.ALetter], + [/*start*/ 0xA926, WordBreakProperty.Extend], + [/*start*/ 0xA92E, WordBreakProperty.Other], + [/*start*/ 0xA930, WordBreakProperty.ALetter], + [/*start*/ 0xA947, WordBreakProperty.Extend], + [/*start*/ 0xA954, WordBreakProperty.Other], + [/*start*/ 0xA960, WordBreakProperty.ALetter], + [/*start*/ 0xA97D, WordBreakProperty.Other], + [/*start*/ 0xA980, WordBreakProperty.Extend], + [/*start*/ 0xA984, WordBreakProperty.ALetter], + [/*start*/ 0xA9B3, WordBreakProperty.Extend], + [/*start*/ 0xA9C1, WordBreakProperty.Other], + [/*start*/ 0xA9CF, WordBreakProperty.ALetter], + [/*start*/ 0xA9D0, WordBreakProperty.Numeric], + [/*start*/ 0xA9DA, WordBreakProperty.Other], + [/*start*/ 0xA9E5, WordBreakProperty.Extend], + [/*start*/ 0xA9E6, WordBreakProperty.Other], + [/*start*/ 0xA9F0, WordBreakProperty.Numeric], + [/*start*/ 0xA9FA, WordBreakProperty.Other], + [/*start*/ 0xAA00, WordBreakProperty.ALetter], + [/*start*/ 0xAA29, WordBreakProperty.Extend], + [/*start*/ 0xAA37, WordBreakProperty.Other], + [/*start*/ 0xAA40, WordBreakProperty.ALetter], + [/*start*/ 0xAA43, WordBreakProperty.Extend], + [/*start*/ 0xAA44, WordBreakProperty.ALetter], + [/*start*/ 0xAA4C, WordBreakProperty.Extend], + [/*start*/ 0xAA4E, WordBreakProperty.Other], + [/*start*/ 0xAA50, WordBreakProperty.Numeric], + [/*start*/ 0xAA5A, WordBreakProperty.Other], + [/*start*/ 0xAA7B, WordBreakProperty.Extend], + [/*start*/ 0xAA7E, WordBreakProperty.Other], + [/*start*/ 0xAAB0, WordBreakProperty.Extend], + [/*start*/ 0xAAB1, WordBreakProperty.Other], + [/*start*/ 0xAAB2, WordBreakProperty.Extend], + [/*start*/ 0xAAB5, WordBreakProperty.Other], + [/*start*/ 0xAAB7, WordBreakProperty.Extend], + [/*start*/ 0xAAB9, WordBreakProperty.Other], + [/*start*/ 0xAABE, WordBreakProperty.Extend], + [/*start*/ 0xAAC0, WordBreakProperty.Other], + [/*start*/ 0xAAC1, WordBreakProperty.Extend], + [/*start*/ 0xAAC2, WordBreakProperty.Other], + [/*start*/ 0xAAE0, WordBreakProperty.ALetter], + [/*start*/ 0xAAEB, WordBreakProperty.Extend], + [/*start*/ 0xAAF0, WordBreakProperty.Other], + [/*start*/ 0xAAF2, WordBreakProperty.ALetter], + [/*start*/ 0xAAF5, WordBreakProperty.Extend], + [/*start*/ 0xAAF7, WordBreakProperty.Other], + [/*start*/ 0xAB01, WordBreakProperty.ALetter], + [/*start*/ 0xAB07, WordBreakProperty.Other], + [/*start*/ 0xAB09, WordBreakProperty.ALetter], + [/*start*/ 0xAB0F, WordBreakProperty.Other], + [/*start*/ 0xAB11, WordBreakProperty.ALetter], + [/*start*/ 0xAB17, WordBreakProperty.Other], + [/*start*/ 0xAB20, WordBreakProperty.ALetter], + [/*start*/ 0xAB27, WordBreakProperty.Other], + [/*start*/ 0xAB28, WordBreakProperty.ALetter], + [/*start*/ 0xAB2F, WordBreakProperty.Other], + [/*start*/ 0xAB30, WordBreakProperty.ALetter], + [/*start*/ 0xAB6A, WordBreakProperty.Other], + [/*start*/ 0xAB70, WordBreakProperty.ALetter], + [/*start*/ 0xABE3, WordBreakProperty.Extend], + [/*start*/ 0xABEB, WordBreakProperty.Other], + [/*start*/ 0xABEC, WordBreakProperty.Extend], + [/*start*/ 0xABEE, WordBreakProperty.Other], + [/*start*/ 0xABF0, WordBreakProperty.Numeric], + [/*start*/ 0xABFA, WordBreakProperty.Other], + [/*start*/ 0xAC00, WordBreakProperty.ALetter], + [/*start*/ 0xD7A4, WordBreakProperty.Other], + [/*start*/ 0xD7B0, WordBreakProperty.ALetter], + [/*start*/ 0xD7C7, WordBreakProperty.Other], + [/*start*/ 0xD7CB, WordBreakProperty.ALetter], + [/*start*/ 0xD7FC, WordBreakProperty.Other], + [/*start*/ 0xFB00, WordBreakProperty.ALetter], + [/*start*/ 0xFB07, WordBreakProperty.Other], + [/*start*/ 0xFB13, WordBreakProperty.ALetter], + [/*start*/ 0xFB18, WordBreakProperty.Other], + [/*start*/ 0xFB1D, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0xFB1E, WordBreakProperty.Extend], + [/*start*/ 0xFB1F, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0xFB29, WordBreakProperty.Other], + [/*start*/ 0xFB2A, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0xFB37, WordBreakProperty.Other], + [/*start*/ 0xFB38, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0xFB3D, WordBreakProperty.Other], + [/*start*/ 0xFB3E, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0xFB3F, WordBreakProperty.Other], + [/*start*/ 0xFB40, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0xFB42, WordBreakProperty.Other], + [/*start*/ 0xFB43, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0xFB45, WordBreakProperty.Other], + [/*start*/ 0xFB46, WordBreakProperty.Hebrew_Letter], + [/*start*/ 0xFB50, WordBreakProperty.ALetter], + [/*start*/ 0xFBB2, WordBreakProperty.Other], + [/*start*/ 0xFBD3, WordBreakProperty.ALetter], + [/*start*/ 0xFD3E, WordBreakProperty.Other], + [/*start*/ 0xFD50, WordBreakProperty.ALetter], + [/*start*/ 0xFD90, WordBreakProperty.Other], + [/*start*/ 0xFD92, WordBreakProperty.ALetter], + [/*start*/ 0xFDC8, WordBreakProperty.Other], + [/*start*/ 0xFDF0, WordBreakProperty.ALetter], + [/*start*/ 0xFDFC, WordBreakProperty.Other], + [/*start*/ 0xFE00, WordBreakProperty.Extend], + [/*start*/ 0xFE10, WordBreakProperty.MidNum], + [/*start*/ 0xFE11, WordBreakProperty.Other], + [/*start*/ 0xFE13, WordBreakProperty.MidLetter], + [/*start*/ 0xFE14, WordBreakProperty.MidNum], + [/*start*/ 0xFE15, WordBreakProperty.Other], + [/*start*/ 0xFE20, WordBreakProperty.Extend], + [/*start*/ 0xFE30, WordBreakProperty.Other], + [/*start*/ 0xFE33, WordBreakProperty.ExtendNumLet], + [/*start*/ 0xFE35, WordBreakProperty.Other], + [/*start*/ 0xFE4D, WordBreakProperty.ExtendNumLet], + [/*start*/ 0xFE50, WordBreakProperty.MidNum], + [/*start*/ 0xFE51, WordBreakProperty.Other], + [/*start*/ 0xFE52, WordBreakProperty.MidNumLet], + [/*start*/ 0xFE53, WordBreakProperty.Other], + [/*start*/ 0xFE54, WordBreakProperty.MidNum], + [/*start*/ 0xFE55, WordBreakProperty.MidLetter], + [/*start*/ 0xFE56, WordBreakProperty.Other], + [/*start*/ 0xFE70, WordBreakProperty.ALetter], + [/*start*/ 0xFE75, WordBreakProperty.Other], + [/*start*/ 0xFE76, WordBreakProperty.ALetter], + [/*start*/ 0xFEFD, WordBreakProperty.Other], + [/*start*/ 0xFEFF, WordBreakProperty.Format], + [/*start*/ 0xFF00, WordBreakProperty.Other], + [/*start*/ 0xFF07, WordBreakProperty.MidNumLet], + [/*start*/ 0xFF08, WordBreakProperty.Other], + [/*start*/ 0xFF0C, WordBreakProperty.MidNum], + [/*start*/ 0xFF0D, WordBreakProperty.Other], + [/*start*/ 0xFF0E, WordBreakProperty.MidNumLet], + [/*start*/ 0xFF0F, WordBreakProperty.Other], + [/*start*/ 0xFF10, WordBreakProperty.Numeric], + [/*start*/ 0xFF1A, WordBreakProperty.MidLetter], + [/*start*/ 0xFF1B, WordBreakProperty.MidNum], + [/*start*/ 0xFF1C, WordBreakProperty.Other], + [/*start*/ 0xFF21, WordBreakProperty.ALetter], + [/*start*/ 0xFF3B, WordBreakProperty.Other], + [/*start*/ 0xFF3F, WordBreakProperty.ExtendNumLet], + [/*start*/ 0xFF40, WordBreakProperty.Other], + [/*start*/ 0xFF41, WordBreakProperty.ALetter], + [/*start*/ 0xFF5B, WordBreakProperty.Other], + [/*start*/ 0xFF66, WordBreakProperty.Katakana], + [/*start*/ 0xFF9E, WordBreakProperty.Extend], + [/*start*/ 0xFFA0, WordBreakProperty.ALetter], + [/*start*/ 0xFFBF, WordBreakProperty.Other], + [/*start*/ 0xFFC2, WordBreakProperty.ALetter], + [/*start*/ 0xFFC8, WordBreakProperty.Other], + [/*start*/ 0xFFCA, WordBreakProperty.ALetter], + [/*start*/ 0xFFD0, WordBreakProperty.Other], + [/*start*/ 0xFFD2, WordBreakProperty.ALetter], + [/*start*/ 0xFFD8, WordBreakProperty.Other], + [/*start*/ 0xFFDA, WordBreakProperty.ALetter], + [/*start*/ 0xFFDD, WordBreakProperty.Other], + [/*start*/ 0xFFF9, WordBreakProperty.Format], + [/*start*/ 0xFFFC, WordBreakProperty.Other], + [/*start*/ 0x10000, WordBreakProperty.ALetter], + [/*start*/ 0x1000C, WordBreakProperty.Other], + [/*start*/ 0x1000D, WordBreakProperty.ALetter], + [/*start*/ 0x10027, WordBreakProperty.Other], + [/*start*/ 0x10028, WordBreakProperty.ALetter], + [/*start*/ 0x1003B, WordBreakProperty.Other], + [/*start*/ 0x1003C, WordBreakProperty.ALetter], + [/*start*/ 0x1003E, WordBreakProperty.Other], + [/*start*/ 0x1003F, WordBreakProperty.ALetter], + [/*start*/ 0x1004E, WordBreakProperty.Other], + [/*start*/ 0x10050, WordBreakProperty.ALetter], + [/*start*/ 0x1005E, WordBreakProperty.Other], + [/*start*/ 0x10080, WordBreakProperty.ALetter], + [/*start*/ 0x100FB, WordBreakProperty.Other], + [/*start*/ 0x10140, WordBreakProperty.ALetter], + [/*start*/ 0x10175, WordBreakProperty.Other], + [/*start*/ 0x101FD, WordBreakProperty.Extend], + [/*start*/ 0x101FE, WordBreakProperty.Other], + [/*start*/ 0x10280, WordBreakProperty.ALetter], + [/*start*/ 0x1029D, WordBreakProperty.Other], + [/*start*/ 0x102A0, WordBreakProperty.ALetter], + [/*start*/ 0x102D1, WordBreakProperty.Other], + [/*start*/ 0x102E0, WordBreakProperty.Extend], + [/*start*/ 0x102E1, WordBreakProperty.Other], + [/*start*/ 0x10300, WordBreakProperty.ALetter], + [/*start*/ 0x10320, WordBreakProperty.Other], + [/*start*/ 0x1032D, WordBreakProperty.ALetter], + [/*start*/ 0x1034B, WordBreakProperty.Other], + [/*start*/ 0x10350, WordBreakProperty.ALetter], + [/*start*/ 0x10376, WordBreakProperty.Extend], + [/*start*/ 0x1037B, WordBreakProperty.Other], + [/*start*/ 0x10380, WordBreakProperty.ALetter], + [/*start*/ 0x1039E, WordBreakProperty.Other], + [/*start*/ 0x103A0, WordBreakProperty.ALetter], + [/*start*/ 0x103C4, WordBreakProperty.Other], + [/*start*/ 0x103C8, WordBreakProperty.ALetter], + [/*start*/ 0x103D0, WordBreakProperty.Other], + [/*start*/ 0x103D1, WordBreakProperty.ALetter], + [/*start*/ 0x103D6, WordBreakProperty.Other], + [/*start*/ 0x10400, WordBreakProperty.ALetter], + [/*start*/ 0x1049E, WordBreakProperty.Other], + [/*start*/ 0x104A0, WordBreakProperty.Numeric], + [/*start*/ 0x104AA, WordBreakProperty.Other], + [/*start*/ 0x104B0, WordBreakProperty.ALetter], + [/*start*/ 0x104D4, WordBreakProperty.Other], + [/*start*/ 0x104D8, WordBreakProperty.ALetter], + [/*start*/ 0x104FC, WordBreakProperty.Other], + [/*start*/ 0x10500, WordBreakProperty.ALetter], + [/*start*/ 0x10528, WordBreakProperty.Other], + [/*start*/ 0x10530, WordBreakProperty.ALetter], + [/*start*/ 0x10564, WordBreakProperty.Other], + [/*start*/ 0x10600, WordBreakProperty.ALetter], + [/*start*/ 0x10737, WordBreakProperty.Other], + [/*start*/ 0x10740, WordBreakProperty.ALetter], + [/*start*/ 0x10756, WordBreakProperty.Other], + [/*start*/ 0x10760, WordBreakProperty.ALetter], + [/*start*/ 0x10768, WordBreakProperty.Other], + [/*start*/ 0x10800, WordBreakProperty.ALetter], + [/*start*/ 0x10806, WordBreakProperty.Other], + [/*start*/ 0x10808, WordBreakProperty.ALetter], + [/*start*/ 0x10809, WordBreakProperty.Other], + [/*start*/ 0x1080A, WordBreakProperty.ALetter], + [/*start*/ 0x10836, WordBreakProperty.Other], + [/*start*/ 0x10837, WordBreakProperty.ALetter], + [/*start*/ 0x10839, WordBreakProperty.Other], + [/*start*/ 0x1083C, WordBreakProperty.ALetter], + [/*start*/ 0x1083D, WordBreakProperty.Other], + [/*start*/ 0x1083F, WordBreakProperty.ALetter], + [/*start*/ 0x10856, WordBreakProperty.Other], + [/*start*/ 0x10860, WordBreakProperty.ALetter], + [/*start*/ 0x10877, WordBreakProperty.Other], + [/*start*/ 0x10880, WordBreakProperty.ALetter], + [/*start*/ 0x1089F, WordBreakProperty.Other], + [/*start*/ 0x108E0, WordBreakProperty.ALetter], + [/*start*/ 0x108F3, WordBreakProperty.Other], + [/*start*/ 0x108F4, WordBreakProperty.ALetter], + [/*start*/ 0x108F6, WordBreakProperty.Other], + [/*start*/ 0x10900, WordBreakProperty.ALetter], + [/*start*/ 0x10916, WordBreakProperty.Other], + [/*start*/ 0x10920, WordBreakProperty.ALetter], + [/*start*/ 0x1093A, WordBreakProperty.Other], + [/*start*/ 0x10980, WordBreakProperty.ALetter], + [/*start*/ 0x109B8, WordBreakProperty.Other], + [/*start*/ 0x109BE, WordBreakProperty.ALetter], + [/*start*/ 0x109C0, WordBreakProperty.Other], + [/*start*/ 0x10A00, WordBreakProperty.ALetter], + [/*start*/ 0x10A01, WordBreakProperty.Extend], + [/*start*/ 0x10A04, WordBreakProperty.Other], + [/*start*/ 0x10A05, WordBreakProperty.Extend], + [/*start*/ 0x10A07, WordBreakProperty.Other], + [/*start*/ 0x10A0C, WordBreakProperty.Extend], + [/*start*/ 0x10A10, WordBreakProperty.ALetter], + [/*start*/ 0x10A14, WordBreakProperty.Other], + [/*start*/ 0x10A15, WordBreakProperty.ALetter], + [/*start*/ 0x10A18, WordBreakProperty.Other], + [/*start*/ 0x10A19, WordBreakProperty.ALetter], + [/*start*/ 0x10A36, WordBreakProperty.Other], + [/*start*/ 0x10A38, WordBreakProperty.Extend], + [/*start*/ 0x10A3B, WordBreakProperty.Other], + [/*start*/ 0x10A3F, WordBreakProperty.Extend], + [/*start*/ 0x10A40, WordBreakProperty.Other], + [/*start*/ 0x10A60, WordBreakProperty.ALetter], + [/*start*/ 0x10A7D, WordBreakProperty.Other], + [/*start*/ 0x10A80, WordBreakProperty.ALetter], + [/*start*/ 0x10A9D, WordBreakProperty.Other], + [/*start*/ 0x10AC0, WordBreakProperty.ALetter], + [/*start*/ 0x10AC8, WordBreakProperty.Other], + [/*start*/ 0x10AC9, WordBreakProperty.ALetter], + [/*start*/ 0x10AE5, WordBreakProperty.Extend], + [/*start*/ 0x10AE7, WordBreakProperty.Other], + [/*start*/ 0x10B00, WordBreakProperty.ALetter], + [/*start*/ 0x10B36, WordBreakProperty.Other], + [/*start*/ 0x10B40, WordBreakProperty.ALetter], + [/*start*/ 0x10B56, WordBreakProperty.Other], + [/*start*/ 0x10B60, WordBreakProperty.ALetter], + [/*start*/ 0x10B73, WordBreakProperty.Other], + [/*start*/ 0x10B80, WordBreakProperty.ALetter], + [/*start*/ 0x10B92, WordBreakProperty.Other], + [/*start*/ 0x10C00, WordBreakProperty.ALetter], + [/*start*/ 0x10C49, WordBreakProperty.Other], + [/*start*/ 0x10C80, WordBreakProperty.ALetter], + [/*start*/ 0x10CB3, WordBreakProperty.Other], + [/*start*/ 0x10CC0, WordBreakProperty.ALetter], + [/*start*/ 0x10CF3, WordBreakProperty.Other], + [/*start*/ 0x10D00, WordBreakProperty.ALetter], + [/*start*/ 0x10D24, WordBreakProperty.Extend], + [/*start*/ 0x10D28, WordBreakProperty.Other], + [/*start*/ 0x10D30, WordBreakProperty.Numeric], + [/*start*/ 0x10D3A, WordBreakProperty.Other], + [/*start*/ 0x10E80, WordBreakProperty.ALetter], + [/*start*/ 0x10EAA, WordBreakProperty.Other], + [/*start*/ 0x10EAB, WordBreakProperty.Extend], + [/*start*/ 0x10EAD, WordBreakProperty.Other], + [/*start*/ 0x10EB0, WordBreakProperty.ALetter], + [/*start*/ 0x10EB2, WordBreakProperty.Other], + [/*start*/ 0x10F00, WordBreakProperty.ALetter], + [/*start*/ 0x10F1D, WordBreakProperty.Other], + [/*start*/ 0x10F27, WordBreakProperty.ALetter], + [/*start*/ 0x10F28, WordBreakProperty.Other], + [/*start*/ 0x10F30, WordBreakProperty.ALetter], + [/*start*/ 0x10F46, WordBreakProperty.Extend], + [/*start*/ 0x10F51, WordBreakProperty.Other], + [/*start*/ 0x10FB0, WordBreakProperty.ALetter], + [/*start*/ 0x10FC5, WordBreakProperty.Other], + [/*start*/ 0x10FE0, WordBreakProperty.ALetter], + [/*start*/ 0x10FF7, WordBreakProperty.Other], + [/*start*/ 0x11000, WordBreakProperty.Extend], + [/*start*/ 0x11003, WordBreakProperty.ALetter], + [/*start*/ 0x11038, WordBreakProperty.Extend], + [/*start*/ 0x11047, WordBreakProperty.Other], + [/*start*/ 0x11066, WordBreakProperty.Numeric], + [/*start*/ 0x11070, WordBreakProperty.Other], + [/*start*/ 0x1107F, WordBreakProperty.Extend], + [/*start*/ 0x11083, WordBreakProperty.ALetter], + [/*start*/ 0x110B0, WordBreakProperty.Extend], + [/*start*/ 0x110BB, WordBreakProperty.Other], + [/*start*/ 0x110BD, WordBreakProperty.Format], + [/*start*/ 0x110BE, WordBreakProperty.Other], + [/*start*/ 0x110CD, WordBreakProperty.Format], + [/*start*/ 0x110CE, WordBreakProperty.Other], + [/*start*/ 0x110D0, WordBreakProperty.ALetter], + [/*start*/ 0x110E9, WordBreakProperty.Other], + [/*start*/ 0x110F0, WordBreakProperty.Numeric], + [/*start*/ 0x110FA, WordBreakProperty.Other], + [/*start*/ 0x11100, WordBreakProperty.Extend], + [/*start*/ 0x11103, WordBreakProperty.ALetter], + [/*start*/ 0x11127, WordBreakProperty.Extend], + [/*start*/ 0x11135, WordBreakProperty.Other], + [/*start*/ 0x11136, WordBreakProperty.Numeric], + [/*start*/ 0x11140, WordBreakProperty.Other], + [/*start*/ 0x11144, WordBreakProperty.ALetter], + [/*start*/ 0x11145, WordBreakProperty.Extend], + [/*start*/ 0x11147, WordBreakProperty.ALetter], + [/*start*/ 0x11148, WordBreakProperty.Other], + [/*start*/ 0x11150, WordBreakProperty.ALetter], + [/*start*/ 0x11173, WordBreakProperty.Extend], + [/*start*/ 0x11174, WordBreakProperty.Other], + [/*start*/ 0x11176, WordBreakProperty.ALetter], + [/*start*/ 0x11177, WordBreakProperty.Other], + [/*start*/ 0x11180, WordBreakProperty.Extend], + [/*start*/ 0x11183, WordBreakProperty.ALetter], + [/*start*/ 0x111B3, WordBreakProperty.Extend], + [/*start*/ 0x111C1, WordBreakProperty.ALetter], + [/*start*/ 0x111C5, WordBreakProperty.Other], + [/*start*/ 0x111C9, WordBreakProperty.Extend], + [/*start*/ 0x111CD, WordBreakProperty.Other], + [/*start*/ 0x111CE, WordBreakProperty.Extend], + [/*start*/ 0x111D0, WordBreakProperty.Numeric], + [/*start*/ 0x111DA, WordBreakProperty.ALetter], + [/*start*/ 0x111DB, WordBreakProperty.Other], + [/*start*/ 0x111DC, WordBreakProperty.ALetter], + [/*start*/ 0x111DD, WordBreakProperty.Other], + [/*start*/ 0x11200, WordBreakProperty.ALetter], + [/*start*/ 0x11212, WordBreakProperty.Other], + [/*start*/ 0x11213, WordBreakProperty.ALetter], + [/*start*/ 0x1122C, WordBreakProperty.Extend], + [/*start*/ 0x11238, WordBreakProperty.Other], + [/*start*/ 0x1123E, WordBreakProperty.Extend], + [/*start*/ 0x1123F, WordBreakProperty.Other], + [/*start*/ 0x11280, WordBreakProperty.ALetter], + [/*start*/ 0x11287, WordBreakProperty.Other], + [/*start*/ 0x11288, WordBreakProperty.ALetter], + [/*start*/ 0x11289, WordBreakProperty.Other], + [/*start*/ 0x1128A, WordBreakProperty.ALetter], + [/*start*/ 0x1128E, WordBreakProperty.Other], + [/*start*/ 0x1128F, WordBreakProperty.ALetter], + [/*start*/ 0x1129E, WordBreakProperty.Other], + [/*start*/ 0x1129F, WordBreakProperty.ALetter], + [/*start*/ 0x112A9, WordBreakProperty.Other], + [/*start*/ 0x112B0, WordBreakProperty.ALetter], + [/*start*/ 0x112DF, WordBreakProperty.Extend], + [/*start*/ 0x112EB, WordBreakProperty.Other], + [/*start*/ 0x112F0, WordBreakProperty.Numeric], + [/*start*/ 0x112FA, WordBreakProperty.Other], + [/*start*/ 0x11300, WordBreakProperty.Extend], + [/*start*/ 0x11304, WordBreakProperty.Other], + [/*start*/ 0x11305, WordBreakProperty.ALetter], + [/*start*/ 0x1130D, WordBreakProperty.Other], + [/*start*/ 0x1130F, WordBreakProperty.ALetter], + [/*start*/ 0x11311, WordBreakProperty.Other], + [/*start*/ 0x11313, WordBreakProperty.ALetter], + [/*start*/ 0x11329, WordBreakProperty.Other], + [/*start*/ 0x1132A, WordBreakProperty.ALetter], + [/*start*/ 0x11331, WordBreakProperty.Other], + [/*start*/ 0x11332, WordBreakProperty.ALetter], + [/*start*/ 0x11334, WordBreakProperty.Other], + [/*start*/ 0x11335, WordBreakProperty.ALetter], + [/*start*/ 0x1133A, WordBreakProperty.Other], + [/*start*/ 0x1133B, WordBreakProperty.Extend], + [/*start*/ 0x1133D, WordBreakProperty.ALetter], + [/*start*/ 0x1133E, WordBreakProperty.Extend], + [/*start*/ 0x11345, WordBreakProperty.Other], + [/*start*/ 0x11347, WordBreakProperty.Extend], + [/*start*/ 0x11349, WordBreakProperty.Other], + [/*start*/ 0x1134B, WordBreakProperty.Extend], + [/*start*/ 0x1134E, WordBreakProperty.Other], + [/*start*/ 0x11350, WordBreakProperty.ALetter], + [/*start*/ 0x11351, WordBreakProperty.Other], + [/*start*/ 0x11357, WordBreakProperty.Extend], + [/*start*/ 0x11358, WordBreakProperty.Other], + [/*start*/ 0x1135D, WordBreakProperty.ALetter], + [/*start*/ 0x11362, WordBreakProperty.Extend], + [/*start*/ 0x11364, WordBreakProperty.Other], + [/*start*/ 0x11366, WordBreakProperty.Extend], + [/*start*/ 0x1136D, WordBreakProperty.Other], + [/*start*/ 0x11370, WordBreakProperty.Extend], + [/*start*/ 0x11375, WordBreakProperty.Other], + [/*start*/ 0x11400, WordBreakProperty.ALetter], + [/*start*/ 0x11435, WordBreakProperty.Extend], + [/*start*/ 0x11447, WordBreakProperty.ALetter], + [/*start*/ 0x1144B, WordBreakProperty.Other], + [/*start*/ 0x11450, WordBreakProperty.Numeric], + [/*start*/ 0x1145A, WordBreakProperty.Other], + [/*start*/ 0x1145E, WordBreakProperty.Extend], + [/*start*/ 0x1145F, WordBreakProperty.ALetter], + [/*start*/ 0x11462, WordBreakProperty.Other], + [/*start*/ 0x11480, WordBreakProperty.ALetter], + [/*start*/ 0x114B0, WordBreakProperty.Extend], + [/*start*/ 0x114C4, WordBreakProperty.ALetter], + [/*start*/ 0x114C6, WordBreakProperty.Other], + [/*start*/ 0x114C7, WordBreakProperty.ALetter], + [/*start*/ 0x114C8, WordBreakProperty.Other], + [/*start*/ 0x114D0, WordBreakProperty.Numeric], + [/*start*/ 0x114DA, WordBreakProperty.Other], + [/*start*/ 0x11580, WordBreakProperty.ALetter], + [/*start*/ 0x115AF, WordBreakProperty.Extend], + [/*start*/ 0x115B6, WordBreakProperty.Other], + [/*start*/ 0x115B8, WordBreakProperty.Extend], + [/*start*/ 0x115C1, WordBreakProperty.Other], + [/*start*/ 0x115D8, WordBreakProperty.ALetter], + [/*start*/ 0x115DC, WordBreakProperty.Extend], + [/*start*/ 0x115DE, WordBreakProperty.Other], + [/*start*/ 0x11600, WordBreakProperty.ALetter], + [/*start*/ 0x11630, WordBreakProperty.Extend], + [/*start*/ 0x11641, WordBreakProperty.Other], + [/*start*/ 0x11644, WordBreakProperty.ALetter], + [/*start*/ 0x11645, WordBreakProperty.Other], + [/*start*/ 0x11650, WordBreakProperty.Numeric], + [/*start*/ 0x1165A, WordBreakProperty.Other], + [/*start*/ 0x11680, WordBreakProperty.ALetter], + [/*start*/ 0x116AB, WordBreakProperty.Extend], + [/*start*/ 0x116B8, WordBreakProperty.ALetter], + [/*start*/ 0x116B9, WordBreakProperty.Other], + [/*start*/ 0x116C0, WordBreakProperty.Numeric], + [/*start*/ 0x116CA, WordBreakProperty.Other], + [/*start*/ 0x1171D, WordBreakProperty.Extend], + [/*start*/ 0x1172C, WordBreakProperty.Other], + [/*start*/ 0x11730, WordBreakProperty.Numeric], + [/*start*/ 0x1173A, WordBreakProperty.Other], + [/*start*/ 0x11800, WordBreakProperty.ALetter], + [/*start*/ 0x1182C, WordBreakProperty.Extend], + [/*start*/ 0x1183B, WordBreakProperty.Other], + [/*start*/ 0x118A0, WordBreakProperty.ALetter], + [/*start*/ 0x118E0, WordBreakProperty.Numeric], + [/*start*/ 0x118EA, WordBreakProperty.Other], + [/*start*/ 0x118FF, WordBreakProperty.ALetter], + [/*start*/ 0x11907, WordBreakProperty.Other], + [/*start*/ 0x11909, WordBreakProperty.ALetter], + [/*start*/ 0x1190A, WordBreakProperty.Other], + [/*start*/ 0x1190C, WordBreakProperty.ALetter], + [/*start*/ 0x11914, WordBreakProperty.Other], + [/*start*/ 0x11915, WordBreakProperty.ALetter], + [/*start*/ 0x11917, WordBreakProperty.Other], + [/*start*/ 0x11918, WordBreakProperty.ALetter], + [/*start*/ 0x11930, WordBreakProperty.Extend], + [/*start*/ 0x11936, WordBreakProperty.Other], + [/*start*/ 0x11937, WordBreakProperty.Extend], + [/*start*/ 0x11939, WordBreakProperty.Other], + [/*start*/ 0x1193B, WordBreakProperty.Extend], + [/*start*/ 0x1193F, WordBreakProperty.ALetter], + [/*start*/ 0x11940, WordBreakProperty.Extend], + [/*start*/ 0x11941, WordBreakProperty.ALetter], + [/*start*/ 0x11942, WordBreakProperty.Extend], + [/*start*/ 0x11944, WordBreakProperty.Other], + [/*start*/ 0x11950, WordBreakProperty.Numeric], + [/*start*/ 0x1195A, WordBreakProperty.Other], + [/*start*/ 0x119A0, WordBreakProperty.ALetter], + [/*start*/ 0x119A8, WordBreakProperty.Other], + [/*start*/ 0x119AA, WordBreakProperty.ALetter], + [/*start*/ 0x119D1, WordBreakProperty.Extend], + [/*start*/ 0x119D8, WordBreakProperty.Other], + [/*start*/ 0x119DA, WordBreakProperty.Extend], + [/*start*/ 0x119E1, WordBreakProperty.ALetter], + [/*start*/ 0x119E2, WordBreakProperty.Other], + [/*start*/ 0x119E3, WordBreakProperty.ALetter], + [/*start*/ 0x119E4, WordBreakProperty.Extend], + [/*start*/ 0x119E5, WordBreakProperty.Other], + [/*start*/ 0x11A00, WordBreakProperty.ALetter], + [/*start*/ 0x11A01, WordBreakProperty.Extend], + [/*start*/ 0x11A0B, WordBreakProperty.ALetter], + [/*start*/ 0x11A33, WordBreakProperty.Extend], + [/*start*/ 0x11A3A, WordBreakProperty.ALetter], + [/*start*/ 0x11A3B, WordBreakProperty.Extend], + [/*start*/ 0x11A3F, WordBreakProperty.Other], + [/*start*/ 0x11A47, WordBreakProperty.Extend], + [/*start*/ 0x11A48, WordBreakProperty.Other], + [/*start*/ 0x11A50, WordBreakProperty.ALetter], + [/*start*/ 0x11A51, WordBreakProperty.Extend], + [/*start*/ 0x11A5C, WordBreakProperty.ALetter], + [/*start*/ 0x11A8A, WordBreakProperty.Extend], + [/*start*/ 0x11A9A, WordBreakProperty.Other], + [/*start*/ 0x11A9D, WordBreakProperty.ALetter], + [/*start*/ 0x11A9E, WordBreakProperty.Other], + [/*start*/ 0x11AC0, WordBreakProperty.ALetter], + [/*start*/ 0x11AF9, WordBreakProperty.Other], + [/*start*/ 0x11C00, WordBreakProperty.ALetter], + [/*start*/ 0x11C09, WordBreakProperty.Other], + [/*start*/ 0x11C0A, WordBreakProperty.ALetter], + [/*start*/ 0x11C2F, WordBreakProperty.Extend], + [/*start*/ 0x11C37, WordBreakProperty.Other], + [/*start*/ 0x11C38, WordBreakProperty.Extend], + [/*start*/ 0x11C40, WordBreakProperty.ALetter], + [/*start*/ 0x11C41, WordBreakProperty.Other], + [/*start*/ 0x11C50, WordBreakProperty.Numeric], + [/*start*/ 0x11C5A, WordBreakProperty.Other], + [/*start*/ 0x11C72, WordBreakProperty.ALetter], + [/*start*/ 0x11C90, WordBreakProperty.Other], + [/*start*/ 0x11C92, WordBreakProperty.Extend], + [/*start*/ 0x11CA8, WordBreakProperty.Other], + [/*start*/ 0x11CA9, WordBreakProperty.Extend], + [/*start*/ 0x11CB7, WordBreakProperty.Other], + [/*start*/ 0x11D00, WordBreakProperty.ALetter], + [/*start*/ 0x11D07, WordBreakProperty.Other], + [/*start*/ 0x11D08, WordBreakProperty.ALetter], + [/*start*/ 0x11D0A, WordBreakProperty.Other], + [/*start*/ 0x11D0B, WordBreakProperty.ALetter], + [/*start*/ 0x11D31, WordBreakProperty.Extend], + [/*start*/ 0x11D37, WordBreakProperty.Other], + [/*start*/ 0x11D3A, WordBreakProperty.Extend], + [/*start*/ 0x11D3B, WordBreakProperty.Other], + [/*start*/ 0x11D3C, WordBreakProperty.Extend], + [/*start*/ 0x11D3E, WordBreakProperty.Other], + [/*start*/ 0x11D3F, WordBreakProperty.Extend], + [/*start*/ 0x11D46, WordBreakProperty.ALetter], + [/*start*/ 0x11D47, WordBreakProperty.Extend], + [/*start*/ 0x11D48, WordBreakProperty.Other], + [/*start*/ 0x11D50, WordBreakProperty.Numeric], + [/*start*/ 0x11D5A, WordBreakProperty.Other], + [/*start*/ 0x11D60, WordBreakProperty.ALetter], + [/*start*/ 0x11D66, WordBreakProperty.Other], + [/*start*/ 0x11D67, WordBreakProperty.ALetter], + [/*start*/ 0x11D69, WordBreakProperty.Other], + [/*start*/ 0x11D6A, WordBreakProperty.ALetter], + [/*start*/ 0x11D8A, WordBreakProperty.Extend], + [/*start*/ 0x11D8F, WordBreakProperty.Other], + [/*start*/ 0x11D90, WordBreakProperty.Extend], + [/*start*/ 0x11D92, WordBreakProperty.Other], + [/*start*/ 0x11D93, WordBreakProperty.Extend], + [/*start*/ 0x11D98, WordBreakProperty.ALetter], + [/*start*/ 0x11D99, WordBreakProperty.Other], + [/*start*/ 0x11DA0, WordBreakProperty.Numeric], + [/*start*/ 0x11DAA, WordBreakProperty.Other], + [/*start*/ 0x11EE0, WordBreakProperty.ALetter], + [/*start*/ 0x11EF3, WordBreakProperty.Extend], + [/*start*/ 0x11EF7, WordBreakProperty.Other], + [/*start*/ 0x11FB0, WordBreakProperty.ALetter], + [/*start*/ 0x11FB1, WordBreakProperty.Other], + [/*start*/ 0x12000, WordBreakProperty.ALetter], + [/*start*/ 0x1239A, WordBreakProperty.Other], + [/*start*/ 0x12400, WordBreakProperty.ALetter], + [/*start*/ 0x1246F, WordBreakProperty.Other], + [/*start*/ 0x12480, WordBreakProperty.ALetter], + [/*start*/ 0x12544, WordBreakProperty.Other], + [/*start*/ 0x13000, WordBreakProperty.ALetter], + [/*start*/ 0x1342F, WordBreakProperty.Other], + [/*start*/ 0x13430, WordBreakProperty.Format], + [/*start*/ 0x13439, WordBreakProperty.Other], + [/*start*/ 0x14400, WordBreakProperty.ALetter], + [/*start*/ 0x14647, WordBreakProperty.Other], + [/*start*/ 0x16800, WordBreakProperty.ALetter], + [/*start*/ 0x16A39, WordBreakProperty.Other], + [/*start*/ 0x16A40, WordBreakProperty.ALetter], + [/*start*/ 0x16A5F, WordBreakProperty.Other], + [/*start*/ 0x16A60, WordBreakProperty.Numeric], + [/*start*/ 0x16A6A, WordBreakProperty.Other], + [/*start*/ 0x16AD0, WordBreakProperty.ALetter], + [/*start*/ 0x16AEE, WordBreakProperty.Other], + [/*start*/ 0x16AF0, WordBreakProperty.Extend], + [/*start*/ 0x16AF5, WordBreakProperty.Other], + [/*start*/ 0x16B00, WordBreakProperty.ALetter], + [/*start*/ 0x16B30, WordBreakProperty.Extend], + [/*start*/ 0x16B37, WordBreakProperty.Other], + [/*start*/ 0x16B40, WordBreakProperty.ALetter], + [/*start*/ 0x16B44, WordBreakProperty.Other], + [/*start*/ 0x16B50, WordBreakProperty.Numeric], + [/*start*/ 0x16B5A, WordBreakProperty.Other], + [/*start*/ 0x16B63, WordBreakProperty.ALetter], + [/*start*/ 0x16B78, WordBreakProperty.Other], + [/*start*/ 0x16B7D, WordBreakProperty.ALetter], + [/*start*/ 0x16B90, WordBreakProperty.Other], + [/*start*/ 0x16E40, WordBreakProperty.ALetter], + [/*start*/ 0x16E80, WordBreakProperty.Other], + [/*start*/ 0x16F00, WordBreakProperty.ALetter], + [/*start*/ 0x16F4B, WordBreakProperty.Other], + [/*start*/ 0x16F4F, WordBreakProperty.Extend], + [/*start*/ 0x16F50, WordBreakProperty.ALetter], + [/*start*/ 0x16F51, WordBreakProperty.Extend], + [/*start*/ 0x16F88, WordBreakProperty.Other], + [/*start*/ 0x16F8F, WordBreakProperty.Extend], + [/*start*/ 0x16F93, WordBreakProperty.ALetter], + [/*start*/ 0x16FA0, WordBreakProperty.Other], + [/*start*/ 0x16FE0, WordBreakProperty.ALetter], + [/*start*/ 0x16FE2, WordBreakProperty.Other], + [/*start*/ 0x16FE3, WordBreakProperty.ALetter], + [/*start*/ 0x16FE4, WordBreakProperty.Extend], + [/*start*/ 0x16FE5, WordBreakProperty.Other], + [/*start*/ 0x16FF0, WordBreakProperty.Extend], + [/*start*/ 0x16FF2, WordBreakProperty.Other], + [/*start*/ 0x1B000, WordBreakProperty.Katakana], + [/*start*/ 0x1B001, WordBreakProperty.Other], + [/*start*/ 0x1B164, WordBreakProperty.Katakana], + [/*start*/ 0x1B168, WordBreakProperty.Other], + [/*start*/ 0x1BC00, WordBreakProperty.ALetter], + [/*start*/ 0x1BC6B, WordBreakProperty.Other], + [/*start*/ 0x1BC70, WordBreakProperty.ALetter], + [/*start*/ 0x1BC7D, WordBreakProperty.Other], + [/*start*/ 0x1BC80, WordBreakProperty.ALetter], + [/*start*/ 0x1BC89, WordBreakProperty.Other], + [/*start*/ 0x1BC90, WordBreakProperty.ALetter], + [/*start*/ 0x1BC9A, WordBreakProperty.Other], + [/*start*/ 0x1BC9D, WordBreakProperty.Extend], + [/*start*/ 0x1BC9F, WordBreakProperty.Other], + [/*start*/ 0x1BCA0, WordBreakProperty.Format], + [/*start*/ 0x1BCA4, WordBreakProperty.Other], + [/*start*/ 0x1D165, WordBreakProperty.Extend], + [/*start*/ 0x1D16A, WordBreakProperty.Other], + [/*start*/ 0x1D16D, WordBreakProperty.Extend], + [/*start*/ 0x1D173, WordBreakProperty.Format], + [/*start*/ 0x1D17B, WordBreakProperty.Extend], + [/*start*/ 0x1D183, WordBreakProperty.Other], + [/*start*/ 0x1D185, WordBreakProperty.Extend], + [/*start*/ 0x1D18C, WordBreakProperty.Other], + [/*start*/ 0x1D1AA, WordBreakProperty.Extend], + [/*start*/ 0x1D1AE, WordBreakProperty.Other], + [/*start*/ 0x1D242, WordBreakProperty.Extend], + [/*start*/ 0x1D245, WordBreakProperty.Other], + [/*start*/ 0x1D400, WordBreakProperty.ALetter], + [/*start*/ 0x1D455, WordBreakProperty.Other], + [/*start*/ 0x1D456, WordBreakProperty.ALetter], + [/*start*/ 0x1D49D, WordBreakProperty.Other], + [/*start*/ 0x1D49E, WordBreakProperty.ALetter], + [/*start*/ 0x1D4A0, WordBreakProperty.Other], + [/*start*/ 0x1D4A2, WordBreakProperty.ALetter], + [/*start*/ 0x1D4A3, WordBreakProperty.Other], + [/*start*/ 0x1D4A5, WordBreakProperty.ALetter], + [/*start*/ 0x1D4A7, WordBreakProperty.Other], + [/*start*/ 0x1D4A9, WordBreakProperty.ALetter], + [/*start*/ 0x1D4AD, WordBreakProperty.Other], + [/*start*/ 0x1D4AE, WordBreakProperty.ALetter], + [/*start*/ 0x1D4BA, WordBreakProperty.Other], + [/*start*/ 0x1D4BB, WordBreakProperty.ALetter], + [/*start*/ 0x1D4BC, WordBreakProperty.Other], + [/*start*/ 0x1D4BD, WordBreakProperty.ALetter], + [/*start*/ 0x1D4C4, WordBreakProperty.Other], + [/*start*/ 0x1D4C5, WordBreakProperty.ALetter], + [/*start*/ 0x1D506, WordBreakProperty.Other], + [/*start*/ 0x1D507, WordBreakProperty.ALetter], + [/*start*/ 0x1D50B, WordBreakProperty.Other], + [/*start*/ 0x1D50D, WordBreakProperty.ALetter], + [/*start*/ 0x1D515, WordBreakProperty.Other], + [/*start*/ 0x1D516, WordBreakProperty.ALetter], + [/*start*/ 0x1D51D, WordBreakProperty.Other], + [/*start*/ 0x1D51E, WordBreakProperty.ALetter], + [/*start*/ 0x1D53A, WordBreakProperty.Other], + [/*start*/ 0x1D53B, WordBreakProperty.ALetter], + [/*start*/ 0x1D53F, WordBreakProperty.Other], + [/*start*/ 0x1D540, WordBreakProperty.ALetter], + [/*start*/ 0x1D545, WordBreakProperty.Other], + [/*start*/ 0x1D546, WordBreakProperty.ALetter], + [/*start*/ 0x1D547, WordBreakProperty.Other], + [/*start*/ 0x1D54A, WordBreakProperty.ALetter], + [/*start*/ 0x1D551, WordBreakProperty.Other], + [/*start*/ 0x1D552, WordBreakProperty.ALetter], + [/*start*/ 0x1D6A6, WordBreakProperty.Other], + [/*start*/ 0x1D6A8, WordBreakProperty.ALetter], + [/*start*/ 0x1D6C1, WordBreakProperty.Other], + [/*start*/ 0x1D6C2, WordBreakProperty.ALetter], + [/*start*/ 0x1D6DB, WordBreakProperty.Other], + [/*start*/ 0x1D6DC, WordBreakProperty.ALetter], + [/*start*/ 0x1D6FB, WordBreakProperty.Other], + [/*start*/ 0x1D6FC, WordBreakProperty.ALetter], + [/*start*/ 0x1D715, WordBreakProperty.Other], + [/*start*/ 0x1D716, WordBreakProperty.ALetter], + [/*start*/ 0x1D735, WordBreakProperty.Other], + [/*start*/ 0x1D736, WordBreakProperty.ALetter], + [/*start*/ 0x1D74F, WordBreakProperty.Other], + [/*start*/ 0x1D750, WordBreakProperty.ALetter], + [/*start*/ 0x1D76F, WordBreakProperty.Other], + [/*start*/ 0x1D770, WordBreakProperty.ALetter], + [/*start*/ 0x1D789, WordBreakProperty.Other], + [/*start*/ 0x1D78A, WordBreakProperty.ALetter], + [/*start*/ 0x1D7A9, WordBreakProperty.Other], + [/*start*/ 0x1D7AA, WordBreakProperty.ALetter], + [/*start*/ 0x1D7C3, WordBreakProperty.Other], + [/*start*/ 0x1D7C4, WordBreakProperty.ALetter], + [/*start*/ 0x1D7CC, WordBreakProperty.Other], + [/*start*/ 0x1D7CE, WordBreakProperty.Numeric], + [/*start*/ 0x1D800, WordBreakProperty.Other], + [/*start*/ 0x1DA00, WordBreakProperty.Extend], + [/*start*/ 0x1DA37, WordBreakProperty.Other], + [/*start*/ 0x1DA3B, WordBreakProperty.Extend], + [/*start*/ 0x1DA6D, WordBreakProperty.Other], + [/*start*/ 0x1DA75, WordBreakProperty.Extend], + [/*start*/ 0x1DA76, WordBreakProperty.Other], + [/*start*/ 0x1DA84, WordBreakProperty.Extend], + [/*start*/ 0x1DA85, WordBreakProperty.Other], + [/*start*/ 0x1DA9B, WordBreakProperty.Extend], + [/*start*/ 0x1DAA0, WordBreakProperty.Other], + [/*start*/ 0x1DAA1, WordBreakProperty.Extend], + [/*start*/ 0x1DAB0, WordBreakProperty.Other], + [/*start*/ 0x1E000, WordBreakProperty.Extend], + [/*start*/ 0x1E007, WordBreakProperty.Other], + [/*start*/ 0x1E008, WordBreakProperty.Extend], + [/*start*/ 0x1E019, WordBreakProperty.Other], + [/*start*/ 0x1E01B, WordBreakProperty.Extend], + [/*start*/ 0x1E022, WordBreakProperty.Other], + [/*start*/ 0x1E023, WordBreakProperty.Extend], + [/*start*/ 0x1E025, WordBreakProperty.Other], + [/*start*/ 0x1E026, WordBreakProperty.Extend], + [/*start*/ 0x1E02B, WordBreakProperty.Other], + [/*start*/ 0x1E100, WordBreakProperty.ALetter], + [/*start*/ 0x1E12D, WordBreakProperty.Other], + [/*start*/ 0x1E130, WordBreakProperty.Extend], + [/*start*/ 0x1E137, WordBreakProperty.ALetter], + [/*start*/ 0x1E13E, WordBreakProperty.Other], + [/*start*/ 0x1E140, WordBreakProperty.Numeric], + [/*start*/ 0x1E14A, WordBreakProperty.Other], + [/*start*/ 0x1E14E, WordBreakProperty.ALetter], + [/*start*/ 0x1E14F, WordBreakProperty.Other], + [/*start*/ 0x1E2C0, WordBreakProperty.ALetter], + [/*start*/ 0x1E2EC, WordBreakProperty.Extend], + [/*start*/ 0x1E2F0, WordBreakProperty.Numeric], + [/*start*/ 0x1E2FA, WordBreakProperty.Other], + [/*start*/ 0x1E800, WordBreakProperty.ALetter], + [/*start*/ 0x1E8C5, WordBreakProperty.Other], + [/*start*/ 0x1E8D0, WordBreakProperty.Extend], + [/*start*/ 0x1E8D7, WordBreakProperty.Other], + [/*start*/ 0x1E900, WordBreakProperty.ALetter], + [/*start*/ 0x1E944, WordBreakProperty.Extend], + [/*start*/ 0x1E94B, WordBreakProperty.ALetter], + [/*start*/ 0x1E94C, WordBreakProperty.Other], + [/*start*/ 0x1E950, WordBreakProperty.Numeric], + [/*start*/ 0x1E95A, WordBreakProperty.Other], + [/*start*/ 0x1EE00, WordBreakProperty.ALetter], + [/*start*/ 0x1EE04, WordBreakProperty.Other], + [/*start*/ 0x1EE05, WordBreakProperty.ALetter], + [/*start*/ 0x1EE20, WordBreakProperty.Other], + [/*start*/ 0x1EE21, WordBreakProperty.ALetter], + [/*start*/ 0x1EE23, WordBreakProperty.Other], + [/*start*/ 0x1EE24, WordBreakProperty.ALetter], + [/*start*/ 0x1EE25, WordBreakProperty.Other], + [/*start*/ 0x1EE27, WordBreakProperty.ALetter], + [/*start*/ 0x1EE28, WordBreakProperty.Other], + [/*start*/ 0x1EE29, WordBreakProperty.ALetter], + [/*start*/ 0x1EE33, WordBreakProperty.Other], + [/*start*/ 0x1EE34, WordBreakProperty.ALetter], + [/*start*/ 0x1EE38, WordBreakProperty.Other], + [/*start*/ 0x1EE39, WordBreakProperty.ALetter], + [/*start*/ 0x1EE3A, WordBreakProperty.Other], + [/*start*/ 0x1EE3B, WordBreakProperty.ALetter], + [/*start*/ 0x1EE3C, WordBreakProperty.Other], + [/*start*/ 0x1EE42, WordBreakProperty.ALetter], + [/*start*/ 0x1EE43, WordBreakProperty.Other], + [/*start*/ 0x1EE47, WordBreakProperty.ALetter], + [/*start*/ 0x1EE48, WordBreakProperty.Other], + [/*start*/ 0x1EE49, WordBreakProperty.ALetter], + [/*start*/ 0x1EE4A, WordBreakProperty.Other], + [/*start*/ 0x1EE4B, WordBreakProperty.ALetter], + [/*start*/ 0x1EE4C, WordBreakProperty.Other], + [/*start*/ 0x1EE4D, WordBreakProperty.ALetter], + [/*start*/ 0x1EE50, WordBreakProperty.Other], + [/*start*/ 0x1EE51, WordBreakProperty.ALetter], + [/*start*/ 0x1EE53, WordBreakProperty.Other], + [/*start*/ 0x1EE54, WordBreakProperty.ALetter], + [/*start*/ 0x1EE55, WordBreakProperty.Other], + [/*start*/ 0x1EE57, WordBreakProperty.ALetter], + [/*start*/ 0x1EE58, WordBreakProperty.Other], + [/*start*/ 0x1EE59, WordBreakProperty.ALetter], + [/*start*/ 0x1EE5A, WordBreakProperty.Other], + [/*start*/ 0x1EE5B, WordBreakProperty.ALetter], + [/*start*/ 0x1EE5C, WordBreakProperty.Other], + [/*start*/ 0x1EE5D, WordBreakProperty.ALetter], + [/*start*/ 0x1EE5E, WordBreakProperty.Other], + [/*start*/ 0x1EE5F, WordBreakProperty.ALetter], + [/*start*/ 0x1EE60, WordBreakProperty.Other], + [/*start*/ 0x1EE61, WordBreakProperty.ALetter], + [/*start*/ 0x1EE63, WordBreakProperty.Other], + [/*start*/ 0x1EE64, WordBreakProperty.ALetter], + [/*start*/ 0x1EE65, WordBreakProperty.Other], + [/*start*/ 0x1EE67, WordBreakProperty.ALetter], + [/*start*/ 0x1EE6B, WordBreakProperty.Other], + [/*start*/ 0x1EE6C, WordBreakProperty.ALetter], + [/*start*/ 0x1EE73, WordBreakProperty.Other], + [/*start*/ 0x1EE74, WordBreakProperty.ALetter], + [/*start*/ 0x1EE78, WordBreakProperty.Other], + [/*start*/ 0x1EE79, WordBreakProperty.ALetter], + [/*start*/ 0x1EE7D, WordBreakProperty.Other], + [/*start*/ 0x1EE7E, WordBreakProperty.ALetter], + [/*start*/ 0x1EE7F, WordBreakProperty.Other], + [/*start*/ 0x1EE80, WordBreakProperty.ALetter], + [/*start*/ 0x1EE8A, WordBreakProperty.Other], + [/*start*/ 0x1EE8B, WordBreakProperty.ALetter], + [/*start*/ 0x1EE9C, WordBreakProperty.Other], + [/*start*/ 0x1EEA1, WordBreakProperty.ALetter], + [/*start*/ 0x1EEA4, WordBreakProperty.Other], + [/*start*/ 0x1EEA5, WordBreakProperty.ALetter], + [/*start*/ 0x1EEAA, WordBreakProperty.Other], + [/*start*/ 0x1EEAB, WordBreakProperty.ALetter], + [/*start*/ 0x1EEBC, WordBreakProperty.Other], + [/*start*/ 0x1F130, WordBreakProperty.ALetter], + [/*start*/ 0x1F14A, WordBreakProperty.Other], + [/*start*/ 0x1F150, WordBreakProperty.ALetter], + [/*start*/ 0x1F16A, WordBreakProperty.Other], + [/*start*/ 0x1F170, WordBreakProperty.ALetter], + [/*start*/ 0x1F18A, WordBreakProperty.Other], + [/*start*/ 0x1F1E6, WordBreakProperty.Regional_Indicator], + [/*start*/ 0x1F200, WordBreakProperty.Other], + [/*start*/ 0x1F3FB, WordBreakProperty.Extend], + [/*start*/ 0x1F400, WordBreakProperty.Other], + [/*start*/ 0x1FBF0, WordBreakProperty.Numeric], + [/*start*/ 0x1FBFA, WordBreakProperty.Other], + [/*start*/ 0xE0001, WordBreakProperty.Format], + [/*start*/ 0xE0002, WordBreakProperty.Other], + [/*start*/ 0xE0020, WordBreakProperty.Extend], + [/*start*/ 0xE0080, WordBreakProperty.Other], + [/*start*/ 0xE0100, WordBreakProperty.Extend], + [/*start*/ 0xE01F0, WordBreakProperty.Other], +]; +} +} diff --git a/common/predictive-text/worker/word_breaking/default-word-breaking/index.ts b/common/models/wordbreakers/src/default/index.ts similarity index 98% rename from common/predictive-text/worker/word_breaking/default-word-breaking/index.ts rename to common/models/wordbreakers/src/default/index.ts index f35b22ac8058a6fce0d2a25322af32a65f87e89a..c587ca08de98858a8c89253697fee4e4467ba8af 100644 --- a/common/predictive-text/worker/word_breaking/default-word-breaking/index.ts +++ b/common/models/wordbreakers/src/default/index.ts @@ -358,14 +358,18 @@ namespace wordBreakers { let midpoint = left + ~~((right - left) / 2); let candidate = WORD_BREAK_PROPERTY[midpoint]; + + let nextRange = WORD_BREAK_PROPERTY[midpoint + 1]; + let startOfNextRange = nextRange ? nextRange[I.Start] : Infinity; + if (codePoint < candidate[I.Start]) { return searchForProperty(codePoint, left, midpoint - 1); - } else if (codePoint > candidate[I.End]) { + } else if (codePoint >= startOfNextRange) { return searchForProperty(codePoint, midpoint + 1, right); - } else { - // We found it! - return candidate[I.Value]; } + + // We found it! + return candidate[I.Value]; } } diff --git a/common/models/wordbreakers/src/index.ts b/common/models/wordbreakers/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2140ae6bf4cf0157cdb93dff26d5dabcc4cb2a46 --- /dev/null +++ b/common/models/wordbreakers/src/index.ts @@ -0,0 +1,8 @@ +/// +/// +/// + +// Let the word breakers be available both in the browser and in Node. +if (typeof module !== "undefined" && (module as any).exports) { + (module as any).exports['wordBreakers'] = wordBreakers; +} diff --git a/common/predictive-text/worker/word_breaking/placeholder-word-breaker.ts b/common/models/wordbreakers/src/placeholder.ts similarity index 100% rename from common/predictive-text/worker/word_breaking/placeholder-word-breaker.ts rename to common/models/wordbreakers/src/placeholder.ts diff --git a/common/predictive-text/unit_tests/headless/ascii-word-breaker.js b/common/models/wordbreakers/test/test-ascii-word-breaker.js similarity index 82% rename from common/predictive-text/unit_tests/headless/ascii-word-breaker.js rename to common/models/wordbreakers/test/test-ascii-word-breaker.js index 7e6d12990523a77ea6fd20366826f3fbcbcd8d02..598780ad959123550f343270f4798a7ed43f5efb 100644 --- a/common/predictive-text/unit_tests/headless/ascii-word-breaker.js +++ b/common/models/wordbreakers/test/test-ascii-word-breaker.js @@ -1,6 +1,5 @@ var assert = require('chai').assert; - -var breakASCIIWords = require('../../build/intermediate').wordBreakers['ascii']; +var breakASCIIWords = require('..').wordBreakers['ascii']; describe('The ASCII word breaker', function () { it('should break simple English sentences', function () { @@ -8,4 +7,4 @@ describe('The ASCII word breaker', function () { let words = breaks.map(span => span.text); assert.deepEqual(words, ['Look', 'The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']); }); -}); \ No newline at end of file +}); diff --git a/common/models/wordbreakers/test/test-default-word-breaker.js b/common/models/wordbreakers/test/test-default-word-breaker.js new file mode 100644 index 0000000000000000000000000000000000000000..6cf236269560f4fbeea61f0840e50d9260694b28 --- /dev/null +++ b/common/models/wordbreakers/test/test-default-word-breaker.js @@ -0,0 +1,23 @@ +/** + * Smoke-test the default + */ + +const assert = require('chai').assert; +const breakWords = require('..').wordBreakers['default']; + +const SHY = '\u00AD'; + +describe('The default word breaker', function () { + it('should break multilingual text', function () { + let breaks = breakWords( + `Добрый день! ᑕᐻ᙮ — after working on ka${SHY}wen${SHY}non:${SHY}nis, + let's eat phở! 🥣` + ); + let words = breaks.map(span => span.text); + assert.deepEqual(words, [ + 'Добрый', 'день', '!', 'ᑕᐻ', '᙮', '—', 'after', + 'working', 'on', `ka${SHY}wen${SHY}non:${SHY}nis`, ',', + "let's", 'eat', 'phở', '!', '🥣' + ]); + }); +}); diff --git a/common/models/wordbreakers/test/test-placeholder-word-breaker.js b/common/models/wordbreakers/test/test-placeholder-word-breaker.js new file mode 100644 index 0000000000000000000000000000000000000000..b23fd5d6bb80c2423746772d84c65e070cd44c69 --- /dev/null +++ b/common/models/wordbreakers/test/test-placeholder-word-breaker.js @@ -0,0 +1,11 @@ +const assert = require('chai').assert; +const breakWords = require('..').wordBreakers['placeholder']; + + +describe('The placeholder word breaker', function () { + it('should break simple English sentences', function () { + let breaks = breakWords('Look! -- The quick brown fox jumps... over the lazy dog!'); + let words = breaks.map(span => span.text); + assert.deepEqual(words, ['Look!', '--', 'The', 'quick', 'brown', 'fox', 'jumps...', 'over', 'the', 'lazy', 'dog!']); + }); +}); diff --git a/common/models/wordbreakers/tsconfig.json b/common/models/wordbreakers/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..5d9b97a291bbf88013ffffd6a6c708bf86f08727 --- /dev/null +++ b/common/models/wordbreakers/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "none", + "lib": ["es6"], + "target": "es5", + "declaration": true, + "sourceMap": true, + "outFile": "index.js", + "strict": true, + "allowJs": false, + "typeRoots": [ + "node_modules/@types", + "node_modules/@keymanapp" + ] + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules", + "test/**/*.ts" + ] +} diff --git a/common/predictive-text/build.sh b/common/predictive-text/build.sh index cef65e16a53879eac46b9c36185ae79d5c2b4dab..50b15af4dd3a2374316f78002e95825e526b095f 100755 --- a/common/predictive-text/build.sh +++ b/common/predictive-text/build.sh @@ -28,7 +28,6 @@ WORKER_OUTPUT=build/intermediate INCLUDES_OUTPUT=build/includes NAKED_WORKER=$WORKER_OUTPUT/index.js EMBEDDED_WORKER=$WORKER_OUTPUT/embedded_worker.js -LEXICAL_MODELS_TYPES=../lexical-model-types # Builds the top-level JavaScript file for use in browsers (the second stage of compilation) build-browser () { @@ -85,13 +84,14 @@ clean ( ) { } display_usage ( ) { - echo "Usage: $0 [-clean] [-test | -tdd]" + echo "Usage: $0 [-clean] [-skip-package-install | -S] [-test | -tdd]" echo " $0 -help" echo - echo " -clean to erase pre-existing build products before a re-build" - echo " -help displays this screen and exits" - echo " -tdd skips dependency updates, builds, then runs unit tests only" - echo " -test runs unit and integration tests after building" + echo " -clean to erase pre-existing build products before a re-build" + echo " -help displays this screen and exits" + echo " -skip-package-install (or -S) skips dependency updates" + echo " -tdd skips dependency updates, builds, then runs unit tests only" + echo " -test runs unit and integration tests after building" } # Creates embedded_worker.js. Must be run after the worker is built for the @@ -135,7 +135,7 @@ wrap-worker-code ( ) { ################################ Main script ################################ run_tests=0 -fetch_deps=1 +fetch_deps=true unit_tests_only=0 # Process command-line arguments @@ -149,12 +149,15 @@ while [[ $# -gt 0 ]] ; do display_usage exit ;; + -skip-package-install|-S) + fetch_deps=false + ;; -test) run_tests=1 ;; -tdd) run_tests=1 - fetch_deps=0 + fetch_deps=false unit_tests_only=1 ;; *) @@ -166,17 +169,7 @@ while [[ $# -gt 0 ]] ; do done # Check if Node.JS/npm is installed. -type npm >/dev/null ||\ - fail "Build environment setup error detected! Please ensure Node.js is installed!" - -if (( fetch_deps )); then - # Before installing, ensure that the local npm package we need can be require()'d. - (cd $LEXICAL_MODELS_TYPES && npm link .) || fail "Could not link lexical-model-types" - - echo "Dependencies check" - npm install --no-optional -fi - +verify_npm_setup $fetch_deps # Ensure that the build-product destination for any generated include .d.ts files exists. if ! [ -d $INCLUDES_OUTPUT ]; then diff --git a/common/predictive-text/message.d.ts b/common/predictive-text/message.d.ts index df48220761e03c838f9025724f26ad3d37ae1452..1cf4ce1fcddb42edea5b6a61abea96c851637d19 100644 --- a/common/predictive-text/message.d.ts +++ b/common/predictive-text/message.d.ts @@ -20,7 +20,7 @@ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/// +/// /** * Tokens are signed 31-bit integers! diff --git a/common/predictive-text/package-lock.json b/common/predictive-text/package-lock.json index 73153a4b1822ab392932bee984e4ec79923f9106..213468410976de71742b821c741d71f6426862f2 100644 --- a/common/predictive-text/package-lock.json +++ b/common/predictive-text/package-lock.json @@ -1,6 +1,6 @@ { - "name": "keyman-lmlayer-prototype", - "version": "0.0.0", + "name": "@keymanapp/lexical-model-layer", + "version": "14.0.144", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -46,9 +46,9 @@ "dev": true }, "@types/node": { - "version": "10.12.11", - "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.11.tgz", - "integrity": "sha512-3iIOhNiPGTdcUNVCv9e5G7GotfvJJe2pc9w2UgDXlUwnxSZ3RgcUocIU+xYm+rTU54jIKih998QE4dMOyMN1NQ==", + "version": "10.17.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.17.21.tgz", + "integrity": "sha512-PQKsydPxYxF1DsAFWmunaxd3sOi3iMt6Zmx/tgaagHYmwJ/9cRH91hQkeJZaUGWbvn0K5HlSVEXkn5U/llWPpQ==", "dev": true }, "accepts": { @@ -2000,12 +2000,6 @@ "mime-types": "~2.1.24" } }, - "typescript": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.2.1.tgz", - "integrity": "sha512-jw7P2z/h6aPT4AENXDGjcfHTu5CSqzsbZc6YlUIebTyBAq8XaKp78x7VcSh30xwSCcsu5irZkYZUSFP1MrAMbg==", - "dev": true - }, "ultron": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ultron/-/ultron-1.1.1.tgz", diff --git a/common/predictive-text/package.json b/common/predictive-text/package.json index 5ab729027f504285df8743d6a766f5e072dbbadc..fa2003de5cd3483b2c92ec6d42adec37e7192630 100644 --- a/common/predictive-text/package.json +++ b/common/predictive-text/package.json @@ -1,27 +1,29 @@ { - "name": "keyman-lmlayer-prototype", - "version": "0.0.0", + "name": "@keymanapp/lexical-model-layer", + "version": "14.0.144", "description": "Keyman/Predictive Text integration layer", "main": "build/index.js", "scripts": { "karma": "karma", + "lerna": "cd ../.. && npm run lerna --", "mocha": "mocha", - "test": "bash ./unit_tests/test.sh", - "tsc": "tsc", - "install": "npm link @keymanapp/lexical-model-types" + "test": "gosh ./unit_tests/test.sh", + "tsc": "tsc" }, "repository": { "type": "git", - "url": "git+https://github.com/eddieantonio/keyman-lmlayer-prototype.git" + "url": "git+https://github.com/keymanapp/keyman.git" }, - "author": "Eddie Antonio Santos (http://eddieantonio.ca/)", + "author": "Eddie Antonio Santos ", "license": "MIT", "bugs": { - "url": "https://github.com/eddieantonio/keyman-lmlayer-prototype/issues" + "url": "https://github.com/keymanapp/keyman/issues" }, - "homepage": "https://github.com/eddieantonio/keyman-lmlayer-prototype#readme", + "homepage": "https://github.com/keymanapp/keyman#readme", "devDependencies": { - "@types/node": "^10.12.11", + "@keymanapp/models-types": "^14.0.144", + "@keymanapp/resources-gosh": "^14.0.144", + "@types/node": "^10.17.21", "chai": "^4.2.0", "karma": "^4.2.0", "karma-browserstack-launcher": "^1.5.1", @@ -41,9 +43,13 @@ "mocha-teamcity-reporter": "^2.5.1", "sinon": "^7.1.1", "ts-node": "^7.0.1", - "typescript": "^3.2.1" + "typescript": "^3.8.3" }, "dependencies": { + "@keymanapp/models-templates": "^14.0.144", + "@keymanapp/models-wordbreakers": "^14.0.144", + "@keymanapp/web-environment": "^14.0.144", + "@keymanapp/web-utils": "^14.0.144", "es6-shim": "^0.35.5", "string.prototype.codepointat": "^0.2.1", "string.prototype.startswith": "^0.2.0" diff --git a/common/predictive-text/unit_tests/headless/default-word-breaker.js b/common/predictive-text/unit_tests/headless/default-word-breaker.js index bcf08efd83cf8b268ab313ebdb0a2e20c3182d12..613336458e76dc8c45eeb855d9e2a40544c1f922 100644 --- a/common/predictive-text/unit_tests/headless/default-word-breaker.js +++ b/common/predictive-text/unit_tests/headless/default-word-breaker.js @@ -1,5 +1,5 @@ /** - * Smoke-test the default + * Smoke-test the default word breaker. */ var assert = require('chai').assert; var TrieModel = require('../../build/intermediate').models.TrieModel; @@ -7,29 +7,19 @@ var TrieModel = require('../../build/intermediate').models.TrieModel; var breakWords = require('../../build/intermediate').wordBreakers['default']; const SHY = '\u00AD'; +// The following are **integration tests** testing the interaction between the +// Trie model "template" and the default word breaker. +// +// They exercise whether the default word breaker produces the correct word +// breaks, and whether the Trie model can consume the word breaks properly. describe('The default word breaker', function () { - it('should break multilingual text', function () { - let breaks = breakWords( - `Добрый день! ᑕᐻ᙮ — after working on ka${SHY}wen${SHY}non:${SHY}nis, - let's eat phở! 🥣` - ); - let words = breaks.map(span => span.text); - assert.deepEqual(words, [ - 'Добрый', 'день', '!', 'ᑕᐻ', '᙮', '—', 'after', - 'working', 'on', `ka${SHY}wen${SHY}non:${SHY}nis`, ',', - "let's", 'eat', 'phở', '!', '🥣' - ]); - }); - - // The following tests are performed with model integration as an internal - // test for the wordbreaking API. it('recognizes a word at end of complete lefthand context', function () { var model = new TrieModel(jsonFixture('tries/english-1000'), { wordBreaker: breakWords // wordBreakers['default'] when fully integrated. }); // Standard case - wordbreaking at the end of a word. - var context = { + var context = { left: 'The quick brown fox jumped', startOfBuffer: true, right: ' over the lazy dog.', endOfBuffer: true }; @@ -47,7 +37,7 @@ describe('The default word breaker', function () { }); // Standard case - wordbreaking at the end of a word. - var context = { + var context = { left: 'The quick brown fox jumped', startOfBuffer: false, right: ' over the lazy dog.', endOfBuffer: false }; @@ -63,7 +53,7 @@ describe('The default word breaker', function () { }); // Standard case - midword (xylophone) call - var context = { + var context = { left: 'xyl', startOfBuffer: true, right: '', endOfBuffer: true }; @@ -72,14 +62,14 @@ describe('The default word breaker', function () { assert.strictEqual(broken, 'xyl'); }); - + it('returns empty string when called without word text', function() { var model = new TrieModel(jsonFixture('tries/english-1000'), { wordBreaker: breakWords }); // Wordbreaking on a empty space => no word. - context = { + context = { left: 'The quick brown fox jumped ', startOfBuffer: true, right: 'over the lazy dog.', endOfBuffer: true }; @@ -95,7 +85,7 @@ describe('The default word breaker', function () { }); // Wordbreaking on a empty space => no word. - context = { + context = { left: '', startOfBuffer: true, right: '', endOfBuffer: true }; @@ -111,7 +101,7 @@ describe('The default word breaker', function () { }); // Wordbreaking on a empty space => no word. - context = { + context = { left: '', startOfBuffer: false, right: '', endOfBuffer: false }; @@ -128,13 +118,13 @@ describe('The default word breaker', function () { // A limitation of the current implementation; we should fix this before release. // Then again, when typing this is probably fine; just not when not typing. - context = { + context = { left: 'The quick brown fox jum', startOfBuffer: true, right: 'ped over the lazy dog.', endOfBuffer: true }; broken = model.wordbreak(context); - assert.strictEqual(broken, 'jumped'); // Current result: 'jum'. + assert.strictEqual(broken, 'jumped'); // Current result: 'jum'. }); }); diff --git a/common/predictive-text/unit_tests/headless/edit-distance/classical-calculation.js b/common/predictive-text/unit_tests/headless/edit-distance/classical-calculation.js new file mode 100644 index 0000000000000000000000000000000000000000..2356704d577106e64208158b0527a09e32712b32 --- /dev/null +++ b/common/predictive-text/unit_tests/headless/edit-distance/classical-calculation.js @@ -0,0 +1,532 @@ +var assert = require('chai').assert; +var ClassicalDistanceCalculation = require('../../../build/intermediate').correction.ClassicalDistanceCalculation; + +function prettyPrintMatrix(matrix) { + for(let r = 0; r < matrix.length; r++) { + console.log(JSON.stringify(matrix[r], function(key, value) { + if(value == Number.MAX_VALUE) { + return "MAX"; + } else if(value === undefined) { + return -1; + } else { + return value; + } + })); + } +} + +function compute(input, match, mode, bandSize) { + let buffer = new ClassicalDistanceCalculation(); + + /* SUPPORTED MODES: + * "InputThenMatch" // adds all input chars, then all match chars. + * "MatchThenInput" // adds all match chars, then all input chars. + */ + + // TEMP: once diagonal expansion is implemented, do this LATER, AFTER adding the chars. + bandSize = bandSize || 1; + buffer.diagonalWidth = bandSize; + + switch(mode || "InputThenMatch") { + case "InputThenMatch": + for(let i = 0; i < input.length; i++) { + buffer = buffer.addInputChar({ + key: input.charAt(i) + }); + } + + for(let j = 0; j < match.length; j++) { + buffer = buffer.addMatchChar({ + key: match.charAt(j) + }); + } + break; + case "MatchThenInput": + for(let j = 0; j < match.length; j++) { + buffer = buffer.addMatchChar({ + key: match.charAt(j) + }); + } + + for(let i = 0; i < input.length; i++) { + buffer = buffer.addInputChar({ + key: input.charAt(i) + }); + } + break; + default: + throw "Invalid test mode specified!" + } + + return buffer; +} + +describe('Classical Damerau-Levenshtein edit-distance calculation', function() { + describe('unweighted', function() { + it("'abc' -> 'abc' = 0", function() { + assert.equal(compute("abc", "abc", "InputThenMatch").getFinalCost(), 0); + assert.equal(compute("abc", "abc", "MatchThenInput").getFinalCost(), 0); + }); + + it("'abc' -> 'cab' = 2", function() { + assert.equal(compute("abc", "cab", "InputThenMatch").getFinalCost(), 2); + assert.equal(compute("abc", "cab", "MatchThenInput").getFinalCost(), 2); + }); + + it("'abc' -> 'cdb' = 3", function() { + assert.equal(compute("abc", "cdb", "InputThenMatch").getFinalCost(), 3); + assert.equal(compute("abc", "cdb", "MatchThenInput").getFinalCost(), 3); + }); + + it("'cab' -> 'bac' = 2", function() { + assert.equal(compute("cab", "bac", "InputThenMatch").getFinalCost(), 2); + assert.equal(compute("cab", "bac", "MatchThenInput").getFinalCost(), 2); + }); + + it("'cab' -> 'bdc' = 2", function() { + assert.equal(compute("cab", "bdc", "InputThenMatch").getFinalCost(), 3); + assert.equal(compute("cab", "bdc", "MatchThenInput").getFinalCost(), 3); + }); + + it("'access' -> 'assess' = 2", function() { + assert.equal(compute("access", "assess", "InputThenMatch").getFinalCost(), 2); + assert.equal(compute("access", "assess", "MatchThenInput").getFinalCost(), 2); + }) + + it("'foo' -> 'foo' = 0", function() { + assert.equal(compute("foo", "foo", "InputThenMatch").getFinalCost(), 0); + assert.equal(compute("foo", "foo", "MatchThenInput").getFinalCost(), 0); + }) + + it("'help' -> 'yelp' = 1", function() { + assert.equal(compute("help", "yelp", "InputThenMatch").getFinalCost(), 1); + assert.equal(compute("help", "yelp", "MatchThenInput").getFinalCost(), 1); + }) + + it("'teh' -> 'the' = 1", function() { + assert.equal(compute("teh", "the", "InputThenMatch").getFinalCost(), 1); + assert.equal(compute("teh", "the", "MatchThenInput").getFinalCost(), 1); + }); + + // 'aa' considered to be inserted within the transposition. + it("'teaah' -> 'the' = 3", function() { + assert.equal(compute("teaah", "the", "InputThenMatch").getFinalCost(), 3); // Note: requires diagonal of width 2, not 1. + assert.equal(compute("teaah", "the", "MatchThenInput").getFinalCost(), 3); + }); + + // d & b transposed, then 'c' inserted. + it("'adb' -> 'abcd' = 2", function() { + assert.equal(compute("adb", "abcd", "InputThenMatch").getFinalCost(), 2); + assert.equal(compute("adb", "abcd", "MatchThenInput").getFinalCost(), 2); + }); + + it("'the' -> '' = 3", function() { + // Oh yeah, gotta do the null-string match case. + assert.equal(compute("the", "", "InputThenMatch").getFinalCost(), 3); + assert.equal(compute("the", "", "MatchThenInput").getFinalCost(), 3); + }); + + it("'' -> 'the' = 3", function() { + // Oh yeah, gotta do the null-string match case. + assert.equal(compute("", "the", "InputThenMatch").getFinalCost(), 3); + assert.equal(compute("", "the", "MatchThenInput").getFinalCost(), 3); + }); + + it("'accomodate' -> 'accommodate' = 1", function() { + assert.equal(compute("accomodate", "accommodate", "InputThenMatch").getFinalCost(), 1); + assert.equal(compute("accomodate", "accommodate", "MatchThenInput").getFinalCost(), 1); + }); + + it("'belitttle' -> 'belittle' = 1", function() { + assert.equal(compute("belitttle", "belittle", "InputThenMatch").getFinalCost(), 1); + assert.equal(compute("belitttle", "belittle", "MatchThenInput").getFinalCost(), 1); + }); + + it("'harras' -> 'harass' = 2", function() { + assert.equal(compute("harras", "harass", "InputThenMatch").getFinalCost(), 2); + assert.equal(compute("harras", "harass", "MatchThenInput").getFinalCost(), 2); + }); + + it("'hiegth' -> 'height' = 2", function() { + assert.equal(compute("hiegth", "height", "InputThenMatch").getFinalCost(), 2); + assert.equal(compute("hiegth", "height", "MatchThenInput").getFinalCost(), 2); + }); + + it("'jellyifhs' -> 'jellyfish' = 2", function() { + assert.equal(compute("jellyifhs", "jellyfish", "InputThenMatch").getFinalCost(), 2); + assert.equal(compute("jellyifhs", "jellyfish", "MatchThenInput").getFinalCost(), 2); + }); + + it("'aadddres' -> 'address' = 3", function() { + // If diagonal set to '1', cost is reported as 4. + assert.equal(compute("aadddres", "address", "InputThenMatch").getFinalCost(), 3); // Error - is returning 5, not 4 (which would be correct for current implementation state) + assert.equal(compute("aadddres", "address", "MatchThenInput").getFinalCost(), 3); + }); + + describe("Intermediate cost tests", function() { + it("'abc' -> 'cab' (width 1) = 2", function() { + // Technically a heuristic here, but it gets the right value b/c all changes are on the diagonal. + assert.equal(compute("abc", "cab", "InputThenMatch").getHeuristicFinalCost(), 2); + assert.equal(compute("abc", "cab", "MatchThenInput").getHeuristicFinalCost(), 2); + }); + + it("'aadddres' -> 'address' (width 1) = 4", function() { + // If diagonal set to '1', cost is reported as 4. + assert.equal(compute("aadddres", "address", "InputThenMatch").getHeuristicFinalCost(), 4); + assert.equal(compute("aadddres", "address", "MatchThenInput").getHeuristicFinalCost(), 4); + }); + + it("'aadddres' -> 'address' (width 2) = 3", function() { + // If diagonal set to '1', cost is reported as 4. + assert.equal(compute("aadddres", "address", "InputThenMatch", 2).getHeuristicFinalCost(), 3); + assert.equal(compute("aadddres", "address", "MatchThenInput", 2).getHeuristicFinalCost(), 3); + }); + + it("'jellyifhs' -> 'jellyfish' (width 1) = 2", function() { + // Technically a heuristic here, but it gets the right value b/c all changes are on the diagonal. + assert.equal(compute("jellyifhs", "jellyfish", "InputThenMatch").getHeuristicFinalCost(), 2); + assert.equal(compute("jellyifhs", "jellyfish", "MatchThenInput").getHeuristicFinalCost(), 2); + }); + + // Two transpositions: abc -> ca, ig <- ghi. Also, one deletion: 'd'. + it("'abcdefig' -> 'caefghi' (width 1) = 7", function() { + let buffer = compute("abcdefig", "caefghi", "InputThenMatch"); + // This test case was constructed with the tranposition parts outside of the center diagonal. + assert.equal(buffer.getHeuristicFinalCost(), 7); + }); + + // Two transpositions: abc -> ca, ig <- ghi. Also, one deletion: 'd'. + it("'abcdefig' -> 'caefghi' (width 2) = 5", function() { + let buffer = compute("abcdefig", "caefghi", "InputThenMatch", 2); + assert.equal(buffer.getHeuristicFinalCost(), 5); + }); + + // Two transpositions: abc -> ca, ig <- ghi. Also, one deletion: 'd'. + it("'abcdefigj' -> 'caefghij' (width 1) = 7", function() { + let buffer = compute("abcdefigj", "caefghij", "InputThenMatch", 1); + assert.equal(buffer.getHeuristicFinalCost(), 7); + }); + + // Two transpositions: abc -> ca, ig <- ghi. Also, one deletion: 'd'. + it("'abcdefigj' -> 'caefghij' (width 2) = 5", function() { + let buffer = compute("abcdefigj", "caefghij", "InputThenMatch", 2); + assert.equal(buffer.getHeuristicFinalCost(), 5); + }); + + // Two transpositions: abcd -> da, zx <- xyz and one deletion ('g') + // The intermediate 'ef[g]hi' ensures that the two transpositions are kept separate. + it("'abcdefghizx' -> 'daefhixyz' (width 2) = 8", function() { + let buffer = compute("abcdefghizx", "daefhixyz", "InputThenMatch", 2); + assert.equal(buffer.getHeuristicFinalCost(), 8); + }); + + // Two transpositions: abcd -> da, zx <- xyz and one deletion ('g') + // The intermediate 'ef[g]hi' ensures that the two transpositions are kept separate. + it("'abcdefghizx' -> 'daefhixyz' (width 3) = 6", function() { + let buffer = compute("abcdefghizx", "daefhixyz", "InputThenMatch", 3); + assert.equal(buffer.getHeuristicFinalCost(), 6); + }); + + // Two transpositions: abcd -> da, zw <- wxyz and two deletions ('gh') + // The intermediate deletions help to ensure that the two transpositions are kept separate. + it("'abcdefijzw' -> 'daefghijwxyz' (width 2) = 8", function() { + let buffer = compute("abcdefijzw", "daefghijwxyz", "InputThenMatch", 2); + assert.equal(buffer.getHeuristicFinalCost(), 8); + }); + + // One transposition: da <- abcd, one insertion ('g'), and two deletions ('yz'). + it("'daefhiwxyz' -> 'abcdefghiyz' (width 1) = 9", function() { + let buffer = compute("daefhiwxyz", "abcdefghiyz", "InputThenMatch", 1); + assert.equal(buffer.getHeuristicFinalCost(), 9); + }); + + // One transposition: da <- abcd, one insertion ('g'), and two deletions ('yz'). + it("'daefhiwxyz' -> 'abcdefghiyz' (width 2) = 7", function() { + let buffer = compute("daefhiwxyz", "abcdefghiyz", "InputThenMatch", 2); + assert.equal(buffer.getHeuristicFinalCost(), 7); + }); + + // One transposition: da <- abcd, one insertion ('g'), and two deletions ('yz'). + it("'daefhiwxyz' -> 'abcdefghiyz' (width 3) = 6", function() { + let buffer = compute("daefhiwxyz", "abcdefghiyz", "InputThenMatch", 3); + assert.equal(buffer.getHeuristicFinalCost(), 6); + }); + + // Two transpositions: da <- abcd, wxyz -> zw and one deletion ('g') + it("'daefghiwxyz' -> 'abcdefhizw' (width 1) = 9", function() { + let buffer = compute("daefghiwxyz", "abcdefhizw", "InputThenMatch", 1); + assert.equal(buffer.getHeuristicFinalCost(), 9); + }); + + // Two transpositions: da <- abcd, wxyz -> zw and one deletion ('g') + it("'daefghiwxyz' -> 'abcdefhizw' (width 2) = 7", function() { + buffer = compute("daefghiwxyz", "abcdefhizw", "InputThenMatch", 2); + assert.equal(buffer.getHeuristicFinalCost(), 7); + }); + }); + + describe("Diagonal extension tests", function() { + it("'aadddres' -> 'address' (width 1->2) = 3", function() { + // If diagonal set to '1', cost is reported as 4. + let buffer = compute("aadddres", "address", "InputThenMatch", 1); + assert.equal(buffer.getHeuristicFinalCost(), 4); + + // 1 -> 2 + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 3); + }); + + // Two transpositions: abc -> ca, ig <- ghi. Also, one deletion: 'd'. + it("'abcdefig' -> 'caefghi' (width 1->2) = 5", function() { + let buffer = compute("abcdefig", "caefghi", "InputThenMatch", 1); + // This test case was constructed with the tranposition parts outside of the center diagonal. + assert.equal(buffer.getHeuristicFinalCost(), 7); + + // 1 -> 2 + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 5); + }); + + // Two transpositions: abc -> ca, ig <- ghi. Also, one deletion: 'd'. + it("'abcdefigj' -> 'caefghij' (width 1->2) = 5", function() { + let buffer = compute("abcdefigj", "caefghij", "InputThenMatch", 1); + // This test case was constructed with the tranposition parts outside of the center diagonal. + assert.equal(buffer.getHeuristicFinalCost(), 7); + + // 1 -> 2 + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 5); + }); + + // Two transpositions: abcd -> da, zx <- xyz and one deletion ('g') + // The intermediate 'ef[g]hi' ensures that the two transpositions are kept separate. + it("'abcdefghizx' -> 'daefhixyz' (width 1->2) = 8", function() { + let buffer = compute("abcdefghizx", "daefhixyz", "InputThenMatch", 1); + assert.equal(buffer.getHeuristicFinalCost(), Number.MAX_VALUE); + + // 1 -> 2 + // Will become too small during expansion if not properly checking + // transpositions for the diagonal's left cell. + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 8); + }); + + // Two transpositions: abcd -> da, zx <- xyz and one deletion ('g') + // The intermediate 'ef[g]hi' ensures that the two transpositions are kept separate. + it("'abcdefghizx' -> 'daefhixyz' (width 2->3) = 6", function() { + let buffer = compute("abcdefghizx", "daefhixyz", "InputThenMatch", 2); + assert.equal(buffer.getHeuristicFinalCost(), 8); + + // 2 -> 3 + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 6); + }); + + // Two transpositions: abcd -> da, zw <- wxyz and two deletions ('gh') + // The intermediate deletions help to ensure that the two transpositions are kept separate. + it("'abcdefijzw' -> 'daefghijwxyz' (width 1->2) = 8", function() { + // Relies on a propagated insertion. + let buffer = compute("abcdefijzw", "daefghijwxyz", "InputThenMatch", 1); + assert.equal(buffer.getHeuristicFinalCost(), Number.MAX_VALUE); + + // 1 -> 2 + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 8); + }); + + // Two transpositions: da <- abcd, wxyz -> zw and one deletion ('g') + it("'daefghiwxyz' -> 'abcdefhizw' (width 1->2) = 7", function() { + // Relies on a propagated transposition and multiple propagated substitutions. + // Inspection of the diagonal-expansion update shows it involves a LOT of propagations! + let buffer = compute("daefghiwxyz", "abcdefhizw", "InputThenMatch", 1); + assert.equal(buffer.getHeuristicFinalCost(), 9); + + // 1 -> 2 + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 7); + }); + + // One transposition: da <- abcd, one insertion ('g'), and two deletions ('yz'). + it("'daefhiwxyz' -> 'abcdefghiyz' (width 1->2) = 6", function() { + let buffer = compute("daefhiwxyz", "abcdefghiyz", "InputThenMatch", 1); + assert.equal(buffer.getHeuristicFinalCost(), 9); + + // 1 -> 2 + // Will become too small during expansion if not properly checking + // transpositions for the diagonal's right cell. + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 7); + }); + + // One transposition: da <- abcd, one insertion ('g'), and two deletions ('yz'). + it("'daefhiwxyz' -> 'abcdefghiyz' (width 2->3) = 6", function() { + let buffer = compute("daefhiwxyz", "abcdefghiyz", "InputThenMatch", 2); + assert.equal(buffer.getHeuristicFinalCost(), 7); + + // 2 -> 3 + // relies on a propagated deletion! + buffer = buffer.increaseMaxDistance(); + assert.equal(buffer.getHeuristicFinalCost(), 6); + }); + }); + + + describe("Bounded final cost tests", function() { + it("'adddress' -> 'address' has final cost within 4", function() { + let buffer = compute("aadddres", "address", "InputThenMatch"); + assert.isTrue(buffer.hasFinalCostWithin(4)); + }) + + it("'adddress' -> 'address' has final cost within 3", function() { + let buffer = compute("aadddres", "address", "InputThenMatch"); + assert.isTrue(buffer.hasFinalCostWithin(3)); + }) + + it("'adddress' -> 'address' does not have final cost within 2", function() { + let buffer = compute("aadddres", "address", "InputThenMatch"); + assert.isFalse(buffer.hasFinalCostWithin(2)); + }) + }); + }); + + describe("subset operations", function() { + it("properly truncates tracked input & match sequences", function() { + let buffer = compute("tear", "there", "InputThenMatch"); + assert.equal(buffer.getFinalCost(), 3); + + let trimmedBuffer = buffer.getSubset(3, 3); + assert.equal(trimmedBuffer.inputSequence.length, 3); + assert.equal(trimmedBuffer.matchSequence.length, 3); + + let expectedInput = ['t', 'e', 'a']; + for(let i=0; i < expectedInput.length; i++) { + assert.equal(trimmedBuffer.inputSequence[i].key, expectedInput[i]); + } + + let expectedMatch = ['t', 'h', 'e']; + for(let i=0; i < expectedMatch.length; i++) { + assert.equal(trimmedBuffer.matchSequence[i].key, expectedMatch[i]); + } + }); + + it("['tear' => 'there'] trimmed to ['tea' => 'the']", function() { + let buffer = compute("tear", "there", "InputThenMatch"); + assert.equal(buffer.getFinalCost(), 3); + + let trimmedBuffer = buffer.getSubset(3, 3); + assert.equal(trimmedBuffer.getFinalCost(), 2); + }); + + it("['tear' => 'there'] trimmed to ['te' => 'the']", function() { + let buffer = compute("tear", "there", "InputThenMatch"); + assert.equal(buffer.getFinalCost(), 3); + + let trimmedBuffer = buffer.getSubset(2, 3); + assert.equal(trimmedBuffer.getFinalCost(), 1); + }); + + it("['tear' => 'there'] trimmed to ['tear' => '']", function() { + let buffer = compute("tear", "there", "InputThenMatch"); + assert.equal(buffer.getFinalCost(), 3); + + let trimmedBuffer = buffer.getSubset(4, 0); + assert.equal(trimmedBuffer.getFinalCost(), 4); + }); + + it("['tear' => 'there'] trimmed to ['' => 'there']", function() { + let buffer = compute("tear", "there", "InputThenMatch"); + assert.equal(buffer.getFinalCost(), 3); + + let trimmedBuffer = buffer.getSubset(0, 5); + assert.equal(trimmedBuffer.getFinalCost(), 5); + }); + + it("['jellyifhs' -> 'jellyfish'] trimmed to ['jelly' => 'jelly']", function() { + let buffer = compute("jellyifhs", "jellyfish"); + + let trimmedBuffer = buffer.getSubset(5, 5); + assert.equal(trimmedBuffer.getFinalCost(), 0) + }); + + it("['jellyifhs' -> 'jellyfish'] trimmed to ['jellyifh' => 'jellyfis']", function() { + let buffer = compute("jellyifhs", "jellyfish"); + + let trimmedBuffer = buffer.getSubset(8, 8); + assert.equal(trimmedBuffer.getFinalCost(), 2) + }); + }); + + describe("edit path construction", function() { + let op = { + s: 'substitute', + m: 'match', + i: 'insert', + d: 'delete', + ts: 'transpose-start', + te: 'transpose-end', + ti: 'transpose-insert', + td: 'transpose-delete' + } + + it("'accomodate' -> 'accommodate'", function() { + let buffer = compute("accomodate", "accommodate", "InputThenMatch"); + + let editSequence = [ + // a c c o m + op.m, op.m, op.m, op.m, op.m, + // +m o d a t e + op.i, op.m, op.m, op.m, op.m, op.m + ]; + + assert.deepEqual(buffer.editPath(), editSequence); + }); + + it("'harras' -> 'harass'", function() { + let buffer = compute("harras", "harass", "InputThenMatch"); + + let editSequence = [ + // h a r -r a s +s + op.m, op.m, op.m, op.d, op.m, op.m, op.i + ]; + + assert.deepEqual(buffer.editPath(), editSequence); + }); + + it("'access' -> 'assess'", function() { + let buffer = compute("access", "assess", "InputThenMatch"); + + let editSequence = [ + // a c/s c/s e s s + op.m, op.s, op.s, op.m, op.m, op.m + ]; + + assert.deepEqual(buffer.editPath(), editSequence); + }); + + it("'ifhs' -> 'fish'", function() { + let buffer = compute("ifhs", "fish"); + + let editSequence = [ + op.ts, op.te, op.ts, op.te + ]; + + assert.deepEqual(buffer.editPath(), editSequence); + }); + + // Two transpositions: abc -> ca, ig <- ghi. Also, one deletion: 'd'. + it("'abczdefig' -> 'cazefghi'", function() { + let buffer = compute("abczdefig", "cazefghi", "InputThenMatch", 2); + + let editSequence = [ + // --- abc -> ca ---- + // a/c b/_ c/a z -d e f + op.ts, op.td, op.te, op.m, op.d, op.m, op.m, + // --- ig -> ghi ---- + // i/g _/h g/i + op.ts, op.ti, op.te + ]; + + assert.deepEqual(buffer.editPath(), editSequence); + }); + }) +}); diff --git a/common/predictive-text/unit_tests/headless/edit-distance/distance-modeler.js b/common/predictive-text/unit_tests/headless/edit-distance/distance-modeler.js new file mode 100644 index 0000000000000000000000000000000000000000..c69f1b21b6e821a94d9f8f33ebc98ccfd5853abd --- /dev/null +++ b/common/predictive-text/unit_tests/headless/edit-distance/distance-modeler.js @@ -0,0 +1,370 @@ +var assert = require('chai').assert; +let models = require('../../../build/intermediate').models; +let correction = require('../../../build/intermediate').correction; + +function assertEdgeChars(edge, input, match) { + assert.isTrue(edgeHasChars(edge, input, match)); +} + +function edgeHasChars(edge, input, match) { + if(edge.optimalInput[edge.optimalInput.length - 1].sample.insert != input) { + return false; + } + + return edge.calculation.lastMatchEntry.key == match; +} + +function findEdgeWithChars(edgeArray, input, match) { + let results = edgeArray.filter(function(value) { + return value.calculation.lastMatchEntry.key == match && value.optimalInput[value.optimalInput.length - 1].sample.insert == input; + }); + + assert.equal(results.length, 1); + return results[0]; +} + +describe('Correction Distance Modeler', function() { + describe('SearchNode + SearchEdge', function() { + var testModel; + + before(function() { + testModel = new models.TrieModel(jsonFixture('tries/english-1000')); + }); + + it('SearchNode.buildInsertionEdges() - from root', function() { + let rootTraversal = testModel.traverseFromRoot(); + assert.isNotEmpty(rootTraversal); + + let rootNode = new correction.SearchNode(rootTraversal); + assert.equal(rootNode.calculation.getHeuristicFinalCost(), 0); + + let edges = rootNode.buildInsertionEdges(); + assert.isAbove(edges.length, 0); + + let expectedChildCount = 0; + for(let child of rootTraversal.children()) { + expectedChildCount++; + + let childEdge = edges.filter(value => value.calculation.lastMatchEntry.key == child.char)[0]; + assert.isOk(childEdge); + assert.isEmpty(childEdge.optimalInput); + assert.isEmpty(childEdge.calculation.inputSequence); + assert.equal(childEdge.currentCost, 1); + } + + assert.equal(edges.length, expectedChildCount); + }); + + it('SearchNode.buildDeletionEdges() - from root', function() { + let rootTraversal = testModel.traverseFromRoot(); + assert.isNotEmpty(rootTraversal); + + let rootNode = new correction.SearchNode(rootTraversal); + assert.equal(rootNode.calculation.getHeuristicFinalCost(), 0); + + let synthDistribution = [ + {sample: {insert: 't', deleteLeft: 0}, p: 0.75}, // Transform, probability + {sample: {insert: 'h', deleteLeft: 0}, p: 0.25} + ]; + + let edges = rootNode.buildDeletionEdges(synthDistribution); + assert.equal(edges.length, 2); + + for(let edge of edges) { + assert.isNotEmpty(edge.optimalInput); + assert.isEmpty(edge.calculation.matchSequence); + + if(edge.optimalInput[0].p == 0.75) { + // 't'. + // 1.25: assumes p = .75 ==> transform to input string cost of .25. + assert.equal(edge.currentCost, 1.25); + } else if(edge.optimalInput[0].p == 0.25) { + // 'h' + } else { + assert.fail(); + assert.equal(edge.currentCost, 1.75); + } + } + }); + + it('SearchNode.buildSubstitutionEdges() - from root', function() { + // The combinatorial effect here is a bit much to fully test. + let rootTraversal = testModel.traverseFromRoot(); + assert.isNotEmpty(rootTraversal); + + let rootNode = new correction.SearchNode(rootTraversal); + assert.equal(rootNode.calculation.getHeuristicFinalCost(), 0); + + let synthDistribution = [ + {sample: {insert: 't', deleteLeft: 0}, p: 0.75}, // Transform, probability + {sample: {insert: 'h', deleteLeft: 0}, p: 0.25} + ]; + + let edges = rootNode.buildSubstitutionEdges(synthDistribution); + assert.isAbove(edges.length, 0); + + let expectedChildCount = 0; + for(let child of rootTraversal.children()) { + for(let mass of synthDistribution) { + expectedChildCount++; + + let matchingEdge = findEdgeWithChars(edges, mass.sample.insert, child.char); + + // Substitution - matching char + if(mass.sample.insert == matchingEdge.calculation.lastMatchEntry.key) { + assert.equal(matchingEdge.currentCost, 1 - mass.p); + } else { + // not matching char. + assert.equal(matchingEdge.currentCost, 2 - mass.p); + } + } + } + + assert.equal(edges.length, expectedChildCount); + + // One final bit, which is a bit of integration - we know the top two nodes that should result. + let queue = new models.PriorityQueue(correction.QUEUE_EDGE_COMPARATOR, edges); + + let firstEdge = queue.dequeue(); + assert.equal(firstEdge.optimalInput[0].sample.insert, 't'); + assert.equal(firstEdge.calculation.lastMatchEntry.key, 't'); + assert.equal(firstEdge.currentCost, 0.25); + + let secondEdge = queue.dequeue(); + assert.equal(secondEdge.optimalInput[0].sample.insert, 'h'); + assert.equal(secondEdge.calculation.lastMatchEntry.key, 'h'); + assert.equal(secondEdge.currentCost, 0.75); + + // After this, a 't' input without a matching char. + let nextEdge = queue.dequeue(); + assert.equal(nextEdge.optimalInput[0].sample.insert, 't'); + assert.notEqual(nextEdge.calculation.lastMatchEntry.key, 't'); + assert.equal(nextEdge.currentCost, 1.25); + }); + + it('Small integration test: "teh" => "ten", "the"', function() { + // The combinatorial effect here is a bit much to fully test. + let rootTraversal = testModel.traverseFromRoot(); + assert.isNotEmpty(rootTraversal); + + let rootNode = new correction.SearchNode(rootTraversal); + assert.equal(rootNode.calculation.getHeuristicFinalCost(), 0); + + // VERY artificial distributions. + let synthDistribution1 = [ + {sample: {insert: 't', deleteLeft: 0}, p: 1} // Transform, probability + ]; + + let synthDistribution2 = [ + {sample: {insert: 'e', deleteLeft: 0}, p: 0.75}, // Transform, probability + {sample: {insert: 'h', deleteLeft: 0}, p: 0.25} + ]; + + let synthDistribution3 = [ + {sample: {insert: 'h', deleteLeft: 0}, p: 0.75}, // Transform, probability + {sample: {insert: 'n', deleteLeft: 0}, p: 0.25} + ]; + + let layer1Edges = rootNode.buildSubstitutionEdges(synthDistribution1); + let layer1Queue = new models.PriorityQueue(correction.QUEUE_EDGE_COMPARATOR, layer1Edges); + + let tEdge = layer1Queue.dequeue(); + assertEdgeChars(tEdge, 't', 't'); + + let layer2Edges = new correction.SearchNode(rootTraversal, tEdge).buildSubstitutionEdges(synthDistribution2); + let layer2Queue = new models.PriorityQueue(correction.QUEUE_EDGE_COMPARATOR, layer2Edges); + + let eEdge = layer2Queue.dequeue(); + assertEdgeChars(eEdge, 'e', 'e'); + + let hEdge = layer2Queue.dequeue(); + assertEdgeChars(hEdge, 'h', 'h'); + + // Needed for a proper e <-> h transposition. + let ehEdge = findEdgeWithChars(layer2Edges, 'e', 'h'); + + assert.isOk(ehEdge); + + // Final round: we'll use three nodes and throw all of their results into the same priority queue. + let layer3eEdges = new correction.SearchNode(rootTraversal, eEdge).buildSubstitutionEdges(synthDistribution3); + let layer3hEdges = new correction.SearchNode(rootTraversal, hEdge).buildSubstitutionEdges(synthDistribution3); + let layer3ehEdges = new correction.SearchNode(rootTraversal, ehEdge).buildSubstitutionEdges(synthDistribution3); + let layer3Queue = new models.PriorityQueue(correction.QUEUE_EDGE_COMPARATOR, layer3eEdges.concat(layer3hEdges).concat(layer3ehEdges)); + + // Find the first result with an actual word directly represented. + do { + edge = layer3Queue.dequeue(); + } while(edge.calculation.lastMatchEntry.traversal.entries.length == 0); + + assertEdgeChars(edge, 'n', 'n'); // 'ten' - perfect edit distance of 0, though less-likely input sequence. + assert(edge.currentCost, 1); + + var edge; + do { + edge = layer3Queue.dequeue(); + } while(edge.calculation.lastMatchEntry.traversal.entries.length == 0); + + // Both have a raw edit distance of 1 while using the same input-sequence root. ('th') + let tenFlag = edgeHasChars(edge, 'h', 'n'); // subs out the 'h' entirely. Could also occur with 'a', but is too unlikely. + let theFlag = edgeHasChars(edge, 'h', 'e'); // looks for transposed 'h' and 'e'. + + assert.isTrue(tenFlag || theFlag); + assert.equal(edge.currentCost, 1.5); + + do { + edge = layer3Queue.dequeue(); + } while(edge.calculation.lastMatchEntry.traversal.entries.length == 0); + + tenFlag = tenFlag || edgeHasChars(edge, 'h', 'n'); + theFlag = theFlag || edgeHasChars(edge, 'h', 'e'); + + assert.isTrue(tenFlag && theFlag); + assert.equal(edge.currentCost, 1.5); + }); + }); + + describe('SearchSpaceTier + SearchSpace', function() { + var testModel; + + before(function() { + testModel = new models.TrieModel(jsonFixture('tries/english-1000')); + }); + + let checkResults_teh = function(iter) { + let firstSet = iter.next(); // {value: , done: } + assert.isFalse(firstSet.done); + + firstSet = firstSet.value; // Retrieves + assert.equal(firstSet[1], 1); + assert.equal(firstSet[0].length, 1); // A single sequence ("ten") should be the best match. + + let chars = firstSet[0][0].map(value => value.key); + assert.equal(chars.join(''), "ten"); + + let secondBatch = [ + 'beh', 'te', 'tec', + 'tech', 'tel', 'tem', + 'ter', 'tes', 'th', + 'the' + ]; + + let secondSet = iter.next(); // {value: , done: } + assert.isFalse(secondSet.done); + + secondSet = secondSet.value; // Retrieves + assert.equal(secondSet[1], 1.5); + assert.equal(secondSet[0].length, secondBatch.length); + + let entries = secondSet[0].map(function(sequence) { + return sequence.map(value => value.key).join(''); + }).sort(); + assert.deepEqual(entries, secondBatch); + + let thirdBatch = [ + 'cen', 'en', 'gen', + 'ken', 'len', 'men', + 'sen', 'tha', 'then', + 'thi', 'tho', 'thr', + 'thu', 'wen' + ]; + + let thirdSet = iter.next(); // {value: , done: } + assert.isFalse(thirdSet.done); + + thirdSet = thirdSet.value; // Retrieves + assert.equal(thirdSet[1], 2); + assert.equal(thirdSet[0].length, thirdBatch.length); + + entries = thirdSet[0].map(function(sequence) { + return sequence.map(value => value.key).join(''); + }).sort(); + assert.deepEqual(entries, thirdBatch); + } + + it('Simple search (paralleling "Small integration test")', function() { + // The combinatorial effect here is a bit much to fully test. + let rootTraversal = testModel.traverseFromRoot(); + assert.isNotEmpty(rootTraversal); + + let searchSpace = new correction.SearchSpace(rootTraversal); + + // VERY artificial distributions. + let synthDistribution1 = [ + {sample: {insert: 't', deleteLeft: 0}, p: 1} // Transform, probability + ]; + + let synthDistribution2 = [ + {sample: {insert: 'e', deleteLeft: 0}, p: 0.75}, // Transform, probability + {sample: {insert: 'h', deleteLeft: 0}, p: 0.25} + ]; + + let synthDistribution3 = [ + {sample: {insert: 'h', deleteLeft: 0}, p: 0.75}, // Transform, probability + {sample: {insert: 'n', deleteLeft: 0}, p: 0.25} + ]; + + searchSpace.addInput(synthDistribution1); + searchSpace.addInput(synthDistribution2); + searchSpace.addInput(synthDistribution3); + + let iter = searchSpace.getBestMatches(); + checkResults_teh(iter); + + // Debugging method: a simple loop for printing out the generated sets, in succession. + // + // for(let i = 1; i <= 8; i++) { // After 8 tiers, we run out of entries for this particular case. + // console.log(); + // console.log("Batch " + i); + + // let set = iter.next(); + // assert.isFalse(set.done); + + // set = set.value; + + // let entries = set[0].map(function(sequence) { + // return sequence.map(value => value.key).join(''); + // }); + + // console.log("Entry count: " + set[0].length); + // entries.sort(); + // console.log(entries); + // console.log(set[1]); + // } + }); + + it('Allows reiteration (sequentially)', function() { + // The combinatorial effect here is a bit much to fully test. + let rootTraversal = testModel.traverseFromRoot(); + assert.isNotEmpty(rootTraversal); + + let searchSpace = new correction.SearchSpace(rootTraversal); + + // VERY artificial distributions. + let synthDistribution1 = [ + {sample: {insert: 't', deleteLeft: 0}, p: 1} // Transform, probability + ]; + + let synthDistribution2 = [ + {sample: {insert: 'e', deleteLeft: 0}, p: 0.75}, // Transform, probability + {sample: {insert: 'h', deleteLeft: 0}, p: 0.25} + ]; + + let synthDistribution3 = [ + {sample: {insert: 'h', deleteLeft: 0}, p: 0.75}, // Transform, probability + {sample: {insert: 'n', deleteLeft: 0}, p: 0.25} + ]; + + searchSpace.addInput(synthDistribution1); + searchSpace.addInput(synthDistribution2); + searchSpace.addInput(synthDistribution3); + + let iter = searchSpace.getBestMatches(); + checkResults_teh(iter); + + // The key: do we get the same results the second time? + // Reset the iterator first... + let iter2 = searchSpace.getBestMatches(); + checkResults_teh(iter2); + }); + }); +}); diff --git a/common/predictive-text/unit_tests/test.sh b/common/predictive-text/unit_tests/test.sh index b794cbe8f8d035db937fd144d2d89669f250a36c..ac1d1df9bd05b7c078ce841e24ebc723ef24c114 100755 --- a/common/predictive-text/unit_tests/test.sh +++ b/common/predictive-text/unit_tests/test.sh @@ -1,27 +1,30 @@ #! /bin/bash # We should work within the script's directory, not the one we were called in. -cd $(dirname "$BASH_SOURCE") +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../../resources/build/build-utils.sh" +## END STANDARD BUILD SCRIPT INCLUDE -# Include useful testing resource functions -. ../../../resources/shellHelperFunctions.sh +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +SCRIPT_ROOT="$(dirname "$THIS_SCRIPT")" # A simple utility script to facilitate unit-testing for the LM Layer. # It's rigged to be callable by NPM to facilitate testing during development when in other folders. display_usage ( ) { echo "test.sh [ -? | -h | -help]" - echo " -CI to perform continuous-integration friendly tests and reporting" - echo " -headless to disable the in-browser tests" - echo " -integrated to disable the 'headless' test suite" - echo " -? | -h | -help to display this help information" + echo " -CI to perform continuous-integration friendly tests and reporting" + echo " -headless to disable the in-browser tests" + echo " -integrated to disable the 'headless' test suite" + echo " -skip-package-install (or -S) skips dependency updates" + echo " -? | -h | -help to display this help information" echo "" exit 0 } init_dependencies ( ) { # Ensure all testing dependencies are in place. - npm install + verify_npm_setup $fetch_deps } test-headless ( ) { @@ -30,7 +33,7 @@ test-headless ( ) { _FLAGS="$_FLAGS --reporter mocha-teamcity-reporter" fi - npm run mocha -- --recursive $_FLAGS ./unit_tests/headless/*.js + npm run mocha -- --recursive $_FLAGS ./unit_tests/headless/*.js ./unit_tests/headless/**/*.js } test-browsers ( ) { @@ -39,7 +42,7 @@ test-browsers ( ) { _FLAGS="$_FLAGS -CI -reporter teamcity" fi - in_browser/browser-test.sh $os_id $_FLAGS + $SCRIPT_ROOT/in_browser/browser-test.sh $os_id $_FLAGS } # Defaults @@ -49,11 +52,13 @@ FLAGS="--require ./unit_tests/helpers" CI_REPORTING=0 RUN_HEADLESS=1 RUN_BROWSERS=1 +fetch_deps=true + # Parse args while [[ $# -gt 0 ]] ; do key="$1" case $key in - -h|-help|-?) + -h|-help) display_usage exit ;; @@ -66,6 +71,9 @@ while [[ $# -gt 0 ]] ; do -integrated) RUN_HEADLESS=0 ;; + -skip-package-install|-S) + fetch_deps=false + ;; esac shift # past argument done diff --git a/common/predictive-text/worker/correction/classical-calculation.ts b/common/predictive-text/worker/correction/classical-calculation.ts new file mode 100644 index 0000000000000000000000000000000000000000..df2748836e5823063a042e7a3c2ae20cf5d87bb9 --- /dev/null +++ b/common/predictive-text/worker/correction/classical-calculation.ts @@ -0,0 +1,551 @@ +namespace correction { + type EditOperation = 'insert' | 'delete' | 'match' | 'substitute' | 'transpose-start' | 'transpose-end' | 'transpose-insert' | 'transpose-delete'; + + /** + * Represents the lowest-level unit for comparison during edit-distance calculations. + */ + export interface EditToken { + key: TUnit; + } + + // A semi-optimized 'online'/iterative Damerau-Levenshtein calculator with the following features: + // - may add new character to the 'input' string or to the 'match' string, reusing all old calculations efficiently. + // - allows a 'focused' evaluation that seeks if the edit distance is within a specific range. Designed for use in match-searching, + // where we want to find the 'closest' matching strings in a lexicon. + // - towards such a match-searching algorithm/heuristic: should nothing be found within that range, all prior calculations may be reused + // to search across the lexicon with an incremented edit distance. + // - minimized memory footprint: O(m) memory footprint (where m = length of 'input' string), rather than O(mn) (where n = length of 'match' string) + // - guaranteed to use a smaller footprint than DiagonalizedIterativeDamerauLevenshteinCalculation. + // + // In short: Used to optimize calculations for low edit-distance checks, then expanded if/as necessary + // if a greater edit distance is requested. + // + // Reference: https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm#Possible_modifications + // - Motivating statement: "if we are only interested in the distance if it is smaller than a threshold..." + export class ClassicalDistanceCalculation = EditToken, TMatch extends EditToken = EditToken> { + /** + * Stores ONLY the computed diagonal elements, nothing else. + * + * Mapped as seen in the example below (with a diagonal of width 1): + * ``` + * MAX | MAX | MAX | MAX | MAX | ... + * MAX | 0 | 1 | 2 | 3 | ... > + * MAX | 1 | a | b | - | ... ====>> | - | a | b | + * MAX | 2 | c | d | e | ... > | c | d | e | + * MAX | 3 | - | f | g | ... | f | g | ... | + * ... | ... | ... | ... | ... | ... | ... | ... | ... | + * ``` + * + * Any "`-`" entries are undefined, as they lie outside of the diagonal under consideration. + * + * Things of note: + * - The entry where row index = col index will always lie at the center of the row's array. + * - For each +1 increase in row index, the row's entries are (logically) shifted by -1 in order to make this happen. + * - As all of the MAX entries and numerical entries above are fixed, known values, they are not represented here. + */ + resolvedDistances: number[][]; + /** + * Specifies how far off-diagonal calculations should be performed. A value of 0 only evaluates cells with matching + * row and column indicies. + * + * The resulting value from .getFinalCost() is only guaranteed correct if it is less than or equal to this value. + * Otherwise, this object represents a heuristic that _may_ overestimate the true edit distance. Note that it will + * never underestimate. + */ + diagonalWidth: number = 1; + + // The sequence of characters input so far. + inputSequence: TInput[] = []; + matchSequence: TMatch[] = []; + + constructor(); + constructor(other: ClassicalDistanceCalculation); + constructor(other?: ClassicalDistanceCalculation) { + if(other) { + // Clone class properties. + let rowCount = other.resolvedDistances.length; + this.resolvedDistances = Array(rowCount); + + for(let r = 0; r < rowCount; r++) { + this.resolvedDistances[r] = Array.from(other.resolvedDistances[r]); + } + + this.inputSequence = Array.from(other.inputSequence); + this.matchSequence = Array.from(other.matchSequence); + this.diagonalWidth = other.diagonalWidth; + } else { + this.resolvedDistances = []; + } + } + + private getTrueIndex(r: number, c: number, width: number): {row: number, col: number, sparse: boolean} { + let retVal = { + row: r, + col: c - r + width, + sparse: false + } + + if(retVal.col < 0 || retVal.col > 2 * width) { + retVal.sparse = true; + } + + return retVal; + } + + private getCostAt(i: number, j: number, width: number = this.diagonalWidth): number { + // Check for and handle the set of fixed-value virtualized indices. + if(i < 0 || j < 0) { + if(i == -1 && j >= -1) { + return j+1; + } else if(j == -1 && i >= -1) { + return i+1; + } + + return Number.MAX_VALUE; + } + + let index = this.getTrueIndex(i, j, width); + return index.sparse ? Number.MAX_VALUE : this.resolvedDistances[index.row][index.col]; + } + + /** + * Noting the above link's statement prefixed "By examining diagonals instead of rows, and by using lazy evaluation...", + * this function will return the actual edit distance between the strings, temporarily increasing the computed + * diagonal's size if necessary. + * + * Does not actually mutate the instance. + */ + getFinalCost(): number { + let buffer = this as ClassicalDistanceCalculation; + let val = buffer.getHeuristicFinalCost(); + + while(val > buffer.diagonalWidth) { + // A consequence of treating this class as immutable. + buffer = buffer.increaseMaxDistance(); + val = buffer.getHeuristicFinalCost(); + } + + return val; + } + + /** + * Returns this instance's computed edit distance. If greater than the diagonal's width value, note that it may be an overestimate. + */ + getHeuristicFinalCost(): number { + return this.getCostAt(this.inputSequence.length-1, this.matchSequence.length-1); + } + + /** + * Returns `true` if the represented edit distance is less than or equal to the specified threshold, minimizing the amount of calculations + * needed to meet the specified limit. + * + * Does not mutate the instance. + * @param threshold + */ + hasFinalCostWithin(threshold: number): boolean { + let buffer = this as ClassicalDistanceCalculation; + let val = buffer.getHeuristicFinalCost(); + let guaranteedBound = this.diagonalWidth; + + do { + // val will never exceed the length of the longer string, no matter how large the threshold. + if(val <= threshold) { + return true; + } else if(guaranteedBound < threshold) { + buffer = buffer.increaseMaxDistance(); + guaranteedBound++; + val = buffer.getHeuristicFinalCost(); + } else { + break; + } + } while(true); + + return false; + } + + /** + * Determines the edit path used to obtain the optimal cost, distinguishing between zero-cost + * substitutions ('match' operations) and actual substitutions. + * @param row + * @param col + */ + public editPath(row: number = this.inputSequence.length - 1, col: number = this.matchSequence.length - 1): EditOperation[] { + let currentCost = this.getCostAt(row, col); + let ops: EditOperation[] = null; + let parent: [number, number] = null; + + let insertParentCost = this.getCostAt(row, col-1); + let deleteParentCost = this.getCostAt(row-1, col); + let substitutionParentCost = this.getCostAt(row-1, col-1); + let [lastInputIndex, lastMatchIndex] = ClassicalDistanceCalculation.getTransposeParent(this, row, col); + if(lastInputIndex >= 0 && lastMatchIndex >= 0) { + // OK, a transposition source is quite possible. Still need to do more vetting, to be sure. + let expectedCost = 1; + + // This transposition includes either 'transpose-insert' or 'transpose-delete' operations. + ops = ['transpose-start']; // always needs a 'start'. + if(lastInputIndex != row-1) { + let count = row - lastInputIndex - 1; + ops = ops.concat( Array(count).fill('transpose-delete') ); + expectedCost += count; + } else { + let count = col - lastMatchIndex - 1; + ops = ops.concat( Array(count).fill('transpose-insert') ); + expectedCost += count; + } + ops.push('transpose-end'); + + // Double-check our expectations. + if(this.getCostAt(lastInputIndex-1, lastMatchIndex-1) != currentCost - expectedCost) { + ops = null; + } + parent = [lastInputIndex-1, lastMatchIndex-1]; + } + + if(ops) { + // bypass the ladder. + } else if(substitutionParentCost == currentCost - 1) { + ops = ['substitute']; + parent = [row-1, col-1]; + } else if(insertParentCost == currentCost - 1) { + ops = ['insert']; + parent = [row, col-1]; + } else if(deleteParentCost == currentCost - 1) { + ops = ['delete']; + parent = [row-1, col]; + } else { //if(substitutionParentCost == currentCost) { + ops = ['match']; + parent = [row-1, col-1]; + } + + // Recursively build the edit path. + if(parent[0] >= 0 && parent[1] >= 0) { + return this.editPath(parent[0], parent[1]).concat(ops); + } else { + if(parent[0] > -1) { + // There are initial deletions. + return Array(parent[0]+1).fill('delete').concat(ops); + } else if(parent[1] > -1) { + // There are initial insertions. + return Array(parent[1]+1).fill('insert').concat(ops); + } else { + return ops; + } + } + } + + private static getTransposeParent, TMatch extends EditToken>( + buffer: ClassicalDistanceCalculation, + r: number, + c: number + ): [number, number] { + // Block any transpositions where the tokens are identical. + // Other operations will be cheaper. + if(buffer.inputSequence[r].key == buffer.matchSequence[c].key) { + return [-1, -1]; + } + + // Transposition checks + let lastInputIndex = -1; + for(let i = r-1; i >= 0; i--) { + if(buffer.inputSequence[i].key == buffer.matchSequence[c].key) { + lastInputIndex = i; + break; + } + } + + let lastMatchIndex = -1; + for(let i = c-1; i >= 0; i--) { + if(buffer.matchSequence[i].key == buffer.inputSequence[r].key) { + lastMatchIndex = i; + break; + } + } + + return [lastInputIndex, lastMatchIndex]; + } + + private static initialCostAt, TMatch extends EditToken>( + buffer: ClassicalDistanceCalculation, + r: number, + c: number, + insertCost?: number, + deleteCost?: number) { + var baseSubstitutionCost = buffer.inputSequence[r].key == buffer.matchSequence[c].key ? 0 : 1; + var substitutionCost: number = buffer.getCostAt(r-1, c-1) + baseSubstitutionCost; + var insertionCost: number = insertCost || buffer.getCostAt(r, c-1) + 1; // If set meaningfully, will never equal zero. + var deletionCost: number = deleteCost || buffer.getCostAt(r-1, c) + 1; // If set meaningfully, will never equal zero. + var transpositionCost: number = Number.MAX_VALUE + + if(r > 0 && c > 0) { // bypass when transpositions are known to be impossible. + let [lastInputIndex, lastMatchIndex] = ClassicalDistanceCalculation.getTransposeParent(buffer, r, c); + transpositionCost = buffer.getCostAt(lastInputIndex-1, lastMatchIndex-1) + (r - lastInputIndex - 1) + 1 + (c - lastMatchIndex - 1); + } + + return Math.min(substitutionCost, deletionCost, insertionCost, transpositionCost); + } + + getSubset(inputLength: number, matchLength: number): ClassicalDistanceCalculation { + let trimmedInstance = new ClassicalDistanceCalculation(this); + + if(inputLength > this.inputSequence.length || matchLength > this.matchSequence.length) { + throw "Invalid dimensions specified for trim operation"; + } + // Trim our tracked input & match sequences. + trimmedInstance.inputSequence.splice(inputLength); + trimmedInstance.matchSequence.splice(matchLength); + + // Major index corresponds to input length. + trimmedInstance.resolvedDistances.splice(inputLength); + + // The real fun: trimming off columns. (Minor index, corresponds to match length) + let finalTrueIndex = this.getTrueIndex(inputLength-1, matchLength-1, this.diagonalWidth); + // The diagonal index increases as the row index decreases. + for(let diagonalIndex = finalTrueIndex.col; diagonalIndex <= 2 * this.diagonalWidth; diagonalIndex++) { + let row = finalTrueIndex.row - (diagonalIndex - finalTrueIndex.col); + if(row < 0) { + break; + } + + if(diagonalIndex < 0) { + trimmedInstance.resolvedDistances[row] = Array(2 * trimmedInstance.diagonalWidth + 1).fill(Number.MAX_VALUE); + } else { + let newCount = 2 * this.diagonalWidth - diagonalIndex; + let keptEntries = trimmedInstance.resolvedDistances[row].splice(0, diagonalIndex+1); + let newEntries = Array(newCount).fill(Number.MAX_VALUE); + trimmedInstance.resolvedDistances[row] = keptEntries.concat(newEntries); + } + } + + return trimmedInstance; + } + + private static forDiagonalOfAxis(diagonalWidth: number, centerIndex: number, axisCap: number, closure: (axisIndex: number, diagIndex: number) => void) { + let diagonalCap = axisCap - centerIndex < diagonalWidth ? axisCap - centerIndex + diagonalWidth : 2 * diagonalWidth; + let startOffset = centerIndex - diagonalWidth; // The axis's index for diagonal entry 0. May be negative. + let diagonalStart = startOffset < 0 ? 0 : startOffset; + + for(let diagonalIndex = diagonalStart - startOffset; diagonalIndex <= diagonalCap; diagonalIndex++) { + closure(startOffset + diagonalIndex, diagonalIndex); + } + } + + // Inputs add an extra row / first index entry. + addInputChar(token: TInput): ClassicalDistanceCalculation { + let returnBuffer = new ClassicalDistanceCalculation(this); + + let r = returnBuffer.inputSequence.length; + returnBuffer.inputSequence.push(token); + + // Insert a row, even if we don't actually do anything with it yet. + // Initialize all entries with Number.MAX_VALUE, as `undefined` use leads to JS math issues. + let row = Array(2 * returnBuffer.diagonalWidth + 1).fill(Number.MAX_VALUE); + returnBuffer.resolvedDistances[r] = row; + + // If there isn't a 'match' entry yet, there are no values to compute. Exit immediately. + if(returnBuffer.matchSequence.length == 0) { + return returnBuffer; + } + + ClassicalDistanceCalculation.forDiagonalOfAxis(returnBuffer.diagonalWidth, r, returnBuffer.matchSequence.length - 1, function(c, diagIndex) { + row[diagIndex] = ClassicalDistanceCalculation.initialCostAt(returnBuffer, r, c); + }); + + return returnBuffer; + } + + addMatchChar(token: TMatch): ClassicalDistanceCalculation { + let returnBuffer = new ClassicalDistanceCalculation(this); + + let c = returnBuffer.matchSequence.length; + returnBuffer.matchSequence.push(token); + + // If there isn't a 'match' entry yet, there are no values to compute. Exit immediately. + if(returnBuffer.inputSequence.length == 0) { + return returnBuffer; + } + + ClassicalDistanceCalculation.forDiagonalOfAxis(returnBuffer.diagonalWidth, c, returnBuffer.inputSequence.length - 1, function(r, diagIndex) { + var row = returnBuffer.resolvedDistances[r]; + // Since diagIndex is from the perspective of the row, it must be inverted to properly index the column. + row[2 * returnBuffer.diagonalWidth - diagIndex] = ClassicalDistanceCalculation.initialCostAt(returnBuffer, r, c); + }); + + return returnBuffer; + } + + public increaseMaxDistance(): ClassicalDistanceCalculation { + let returnBuffer = new ClassicalDistanceCalculation(this); + returnBuffer.diagonalWidth++; + + if(returnBuffer.inputSequence.length < 1 || returnBuffer.matchSequence.length < 1) { + return returnBuffer; + } + + // An abstraction of the common aspects of transposition handling during diagonal extensions. + function forPossibleTranspositionsInDiagonal(startPos: number, fixedChar: TUnit, lookupString: EditToken[], closure: (axisIndex: number, diagIndex: number) => void) { + let diagonalCap = 2 * (returnBuffer.diagonalWidth - 1); // The maximum diagonal index permitted + let axisCap = lookupString.length - 1; // The maximum index supported by the axis of iteration + + // Ensures that diagonal iteration only occurs within the axis's supported range + diagonalCap = diagonalCap < axisCap - startPos ? diagonalCap : axisCap - startPos; + + // Iterate within the diagonal and call our closure for any potential transpositions. + for(let diagonalIndex = 0; diagonalIndex <= diagonalCap; diagonalIndex++) { + if(fixedChar == lookupString[startPos + diagonalIndex].key) { + closure(startPos + diagonalIndex, diagonalIndex); + } + } + } + + for(let r = 0; r < returnBuffer.inputSequence.length; r++) { + let leftCell = Number.MAX_VALUE; + let c = r - returnBuffer.diagonalWidth // External index of the left-most entry, which we will now calculate. + if(c >= 0) { + // If c == 0, cell is at edge, thus a known value for insertions exists. + // Base cost: r+1, +1 for inserting. + let insertionCost = c == 0 ? r + 2 : Number.MAX_VALUE; + // compute new left cell + leftCell = ClassicalDistanceCalculation.initialCostAt(returnBuffer, r, c, insertionCost, undefined); + let addedCost = leftCell; + + // daisy-chain possible updates + + // cell (r, c+1): new insertion source + if(c < returnBuffer.matchSequence.length-1) { + // We propagate the new added cost (via insertion) to the old left-most cell, which is one to our right. + ClassicalDistanceCalculation.propagateUpdateFrom(returnBuffer, r, c+1, addedCost+1, 0); + + // Only possible if insertions are also possible AND more conditions are met. + // cells (r+2, * > c+2): new transposition source + let transposeRow = r+2; + if(r+2 < this.inputSequence.length) { // Row to check for transposes must exist. + let rowChar = returnBuffer.inputSequence[r+1].key; + // First possible match in input could be at index c + 2, which adjusts col c+2's cost. Except that entry in r+2 + // doesn't exist yet - so we start with c+3 instead. + forPossibleTranspositionsInDiagonal(c + 3, rowChar, returnBuffer.matchSequence, function(axisIndex, diagIndex) { + // Because (r+2, c+3) is root, not (r+2, c+2). Min cost of 2. + ClassicalDistanceCalculation.propagateUpdateFrom(returnBuffer, transposeRow, axisIndex, addedCost + diagIndex + 2, diagIndex); + }); + } + } + } + + let rightCell = Number.MAX_VALUE; + c = r + returnBuffer.diagonalWidth; + if(c < returnBuffer.matchSequence.length) { + // If r == 0, cell is at edge, thus a known value for insertions exists. + // Base cost: c+1, +1 for inserting. + let deletionCost = r == 0 ? c + 2 : Number.MAX_VALUE; + + // the current row wants to use adjusted diagonal width; we must specify use of the old width & its mapping instead. + var insertionCost: number = returnBuffer.getCostAt(r, c-1, this.diagonalWidth) + 1; + + // compute new right cell + rightCell = ClassicalDistanceCalculation.initialCostAt(returnBuffer, r, c, insertionCost, deletionCost); + let addedCost = rightCell; + + // daisy-chain possible updates + + // cell (r+1, c): new deletion source + if(r < returnBuffer.inputSequence.length - 1) { + // We propagate the new added cost (via deletion) to the old right-most cell, which is one to our right. + ClassicalDistanceCalculation.propagateUpdateFrom(returnBuffer, r+1, c, addedCost + 1, 2 * this.diagonalWidth); + + // Only possible if deletions are also possible AND more conditions are met. + // cells(* > r+2, c+2): new transposition source + let transposeCol = c+2; + if(c+2 < this.matchSequence.length) { // Row to check for transposes must exist. + let colChar = returnBuffer.matchSequence[r+1].key; + // First possible match in input could be at index r + 2, which adjusts row r+2's cost. Except that entry in c+2 + // doesn't exist yet - so we start with r+3 instead. + forPossibleTranspositionsInDiagonal(r+3, colChar, returnBuffer.inputSequence, function(axisIndex, diagIndex) { + let diagColIndex = 2 * (returnBuffer.diagonalWidth - 1) - diagIndex; + // Because (r+3, c+2) is root, not (r+2, c+2). Min cost of 2. + ClassicalDistanceCalculation.propagateUpdateFrom(returnBuffer, axisIndex, transposeCol, addedCost + diagIndex + 2, diagColIndex); + }); + } + } + } + + // Constructs the final expanded diagonal for the row. + returnBuffer.resolvedDistances[r] = [leftCell].concat(returnBuffer.resolvedDistances[r], rightCell); + } + + return returnBuffer; + } + + private static propagateUpdateFrom, TMatch extends EditToken>( + buffer: ClassicalDistanceCalculation, + r: number, + c: number, + value: number, + diagonalIndex: number) { + // Note: this function does not actually need the `c` parameter! + // That said, it's very useful when tracing stack traces & debugging. + if(value < buffer.resolvedDistances[r][diagonalIndex]) { + buffer.resolvedDistances[r][diagonalIndex] = value; + } else { + return + } + + let internalRow = r < buffer.inputSequence.length - 1; + let internalCol = c < buffer.matchSequence.length - 1; + + // We have to compensate for the current & following rows not having been expanded yet. + if(diagonalIndex < 2 * (buffer.diagonalWidth - 1) && internalCol) { + // We've inserted to the left of an existing calculation - check for propagation via insertion. + let updateCost = value + 1; + this.propagateUpdateFrom(buffer, r, c+1, updateCost, diagonalIndex+1); + } + + if(diagonalIndex > 0 && internalRow) { + // We've inserted above an existing calculation - check for propagation via deletion + let updateCost = value + 1 + this.propagateUpdateFrom(buffer, r+1, c, updateCost, diagonalIndex-1); + } + + // If both, check for propagation via substitution and possible transpositions + if(internalRow && internalCol) { + let updateCost = value + (buffer.inputSequence[r+1].key == buffer.matchSequence[c+1].key ? 0 : 1); + this.propagateUpdateFrom(buffer, r+1, c+1, updateCost, diagonalIndex); + + // Propagating transpositions (only possible if 'internal'.) + let nextInputIndex = -1; + for(let i = r+2; i < buffer.inputSequence.length; i++) { + if(buffer.inputSequence[i].key == buffer.matchSequence[c+1].key) { + nextInputIndex = i; + break; + } + } + + let nextMatchIndex = -1; + for(let i = c+2; i < buffer.matchSequence.length; i++) { + if(buffer.matchSequence[i].key == buffer.inputSequence[r+1].key) { + nextMatchIndex = i; + break; + } + } + + if(nextInputIndex > 0 && nextMatchIndex > 0) { + let transpositionCost = value + (nextInputIndex - r - 2) + 1 + (nextMatchIndex - c - 2); + this.propagateUpdateFrom(buffer, nextInputIndex, nextMatchIndex, transpositionCost, (buffer.diagonalWidth - 1) + nextMatchIndex - nextInputIndex); + } + } + } + + get mapKey(): string { + let inputString = this.inputSequence.map((value) => value.key).join(''); + let matchString = this.matchSequence.map((value) => value.key).join(''); + return inputString + models.SENTINEL_CODE_UNIT + matchString + models.SENTINEL_CODE_UNIT + this.diagonalWidth; + } + + get lastInputEntry(): TInput { + return this.inputSequence[this.inputSequence.length-1]; + } + + get lastMatchEntry(): TMatch { + return this.matchSequence[this.matchSequence.length-1]; + } + } +} diff --git a/common/predictive-text/worker/correction/distance-modeler.ts b/common/predictive-text/worker/correction/distance-modeler.ts new file mode 100644 index 0000000000000000000000000000000000000000..a15caf85c097dc5148b29d2b06cf3d9b41ffaf32 --- /dev/null +++ b/common/predictive-text/worker/correction/distance-modeler.ts @@ -0,0 +1,481 @@ +/// + +namespace correction { + type RealizedInput = ProbabilityMass[]; // NOT Distribution - they're masses from separate distributions. + + type TraversableToken = { + key: TUnit, + traversal: LexiconTraversal + } + + export const QUEUE_EDGE_COMPARATOR: models.Comparator = function(arg1, arg2) { + return arg1.currentCost - arg2.currentCost; + } + + export const QUEUE_NODE_COMPARATOR: models.Comparator = function(arg1, arg2) { + return arg1.currentCost - arg2.currentCost; + } + + export const QUEUE_SPACE_COMPARATOR: models.Comparator = function(space1, space2) { + let node1 = space1.correctionQueue.peek(); + let node2 = space2.correctionQueue.peek(); + + // Guards, just in case one of the search spaces ever has an empty node. + if(node1 && node2) { + return node1.currentCost - node2.currentCost; + } else if(node2) { + return 1; + } else { + return -1; + } + } + + // Represents an 'edge' to a potential 'node' on the (conceptual) graph used to search for best-fitting + // corrections by the correction-search algorithm. Stores the cost leading to the new node, though it may be + // an overestimate when the edit distance is greater than the current search threshold. + // + // For nodes with raw edit-distance cost within the current threshold for correction searches, we do have admissibility. + // If not enough nodes are available within that threshold, however, admissibility may be lost, leaving our search as a + // heuristic. + class SearchEdge { + // Existing calculation from prior rounds to use as source. + calculation: ClassicalDistanceCalculation, TraversableToken>; + + // The sequence of input 'samples' taken from specified input distributions. + optimalInput: RealizedInput; + + // Returns the new input character + probabilty component to add in the current search space's + // calculation layer. + get currentInput(): ProbabilityMass { + if(!Array.isArray(this.optimalInput)) { + return undefined; + } + + let length = this.optimalInput.length; + return this.optimalInput[length-1]; + } + + get knownCost(): number { + return this.calculation.getHeuristicFinalCost(); + } + + get inputSamplingCost(): number { + // TODO: Optimize so that we're not frequently recomputing this? + // TODO: We might should generalize this so that the probability-to-cost function isn't directly hard-coded. + // Seems like a decent first conversion function though, at least. + return this.optimalInput.map(mass => mass.p).reduce((previous, current) => previous + (1 - current), 0); + } + + // The part used to prioritize our search. + get currentCost(): number { + return this.knownCost + this.inputSamplingCost; + } + + get mapKey(): string { + // TODO: correct, as Transforms don't convert nicely to strings. + let inputString = this.optimalInput.map((value) => '+' + value.sample.insert + '-' + value.sample.deleteLeft).join(''); + let matchString = this.calculation.matchSequence.map((value) => value.key).join(''); + // TODO: might should also track diagonalWidth. + return inputString + models.SENTINEL_CODE_UNIT + matchString; + } + } + + // Represents a processed node for the correction-search's search-space's tree-like graph. May represent + // internal and 'leaf' nodes on said graph, as well as the overall root of the search. + // + // Provides functions usable to enumerate across the node's outward edges to new nodes for continued search. + // Most of the actual calculations occur as part of this process. + // + export class SearchNode { + calculation: ClassicalDistanceCalculation, TraversableToken>; + + currentTraversal: LexiconTraversal; + priorInput: RealizedInput; + + constructor(rootTraversal: LexiconTraversal, edge?: SearchEdge) { + if(edge) { + this.calculation = edge.calculation; + + if(edge.calculation.lastMatchEntry) { + this.currentTraversal = edge.calculation.lastMatchEntry.traversal; + } else { + this.currentTraversal = rootTraversal; + } + this.priorInput = edge.optimalInput; + } else { + this.calculation = new ClassicalDistanceCalculation(); + this.currentTraversal = rootTraversal; + this.priorInput = []; + } + } + + get knownCost(): number { + return this.calculation.getHeuristicFinalCost(); + } + + get inputSamplingCost(): number { + // TODO: Optimize so that we're not frequently recomputing this? + // TODO: We might should generalize this so that the probability-to-cost function isn't directly hard-coded. + // Seems like a decent first conversion function though, at least. + return this.priorInput.map(mass => mass.p).reduce((previous, current) => previous + (1 - current), 0); + } + + // The part used to prioritize our search. + get currentCost(): number { + return this.knownCost + this.inputSamplingCost; + } + + buildInsertionEdges(): SearchEdge[] { + let edges: SearchEdge[] = []; + + for(let lexicalChild of this.currentTraversal.children()) { + let matchToken = { + key: lexicalChild.char, + traversal: lexicalChild.traversal() + } + + // TODO: Check against cache(s) & cache results. + let childCalc = this.calculation.addMatchChar(matchToken); + + let searchChild = new SearchEdge(); + searchChild.calculation = childCalc; + searchChild.optimalInput = this.priorInput; + + edges.push(searchChild); + } + + return edges; + } + + buildDeletionEdges(inputDistribution: Distribution): SearchEdge[] { + let edges: SearchEdge[] = []; + + for(let probMass of inputDistribution) { + let edgeCalc = this.calculation; + let transform = probMass.sample; + if(transform.deleteLeft) { + edgeCalc = edgeCalc.getSubset(edgeCalc.inputSequence.length - transform.deleteLeft, edgeCalc.matchSequence.length); + } + + // TODO: transform.deleteRight currently not supported. + + let inputPath = Array.from(this.priorInput); + inputPath.push(probMass); + // Tokenize and iterate over input chars, adding them into the calc. + for(let i=0; i < transform.insert.length; i++) { + let char = transform.insert[i]; + if(models.isHighSurrogate(char)) { + i++; + char = char + transform.insert[i]; + } + + // TODO: Check against cache, write results to that cache. + edgeCalc = edgeCalc.addInputChar({key: char}); + } + + let childEdge = new SearchEdge(); + childEdge.calculation = edgeCalc; + childEdge.optimalInput = inputPath; + + edges.push(childEdge); + } + + return edges; + } + + // While this may SEEM to be unnecessary, note that sometimes substitutions (which are computed + // via insert + delete) may be lower cost than both just-insert and just-delete. + buildSubstitutionEdges(inputDistribution: Distribution): SearchEdge[] { + // Handles the 'input' component. + let intermediateEdges = this.buildDeletionEdges(inputDistribution); + let edges: SearchEdge[] = []; + + for(let lexicalChild of this.currentTraversal.children()) { + for(let edge of intermediateEdges) { + let matchToken = { + key: lexicalChild.char, + traversal: lexicalChild.traversal() + } + + // TODO: Check against cache(s), cache results. + let childCalc = edge.calculation.addMatchChar(matchToken); + + let searchChild = new SearchEdge(); + searchChild.calculation = childCalc; + searchChild.optimalInput = edge.optimalInput; + + edges.push(searchChild); + } + } + + return edges; + } + } + + class SearchSpaceTier { + correctionQueue: models.PriorityQueue; + processed: SearchNode[] = []; + index: number; + + constructor(index: number, initialEdges?: SearchEdge[]) { + this.index = index; + this.correctionQueue = new models.PriorityQueue(QUEUE_EDGE_COMPARATOR, initialEdges); + } + + increaseMaxEditDistance() { + // By extracting the entries from the priority queue and increasing distance outside of it as a batch job, + // we get an O(N) implementation, rather than the O(N log N) that would result from maintaining the original queue. + let entries = this.correctionQueue.toArray(); + + entries.forEach(function(edge) { edge.calculation = edge.calculation.increaseMaxDistance(); }); + + // Since we just modified the stored instances, and the costs may have shifted, we need to re-heapify. + this.correctionQueue = new models.PriorityQueue(QUEUE_EDGE_COMPARATOR, entries); + } + } + + // The set of search spaces corresponding to the same 'context' for search. + // Whenever a wordbreak boundary is crossed, a new instance should be made. + export class SearchSpace { + private tierOrdering: SearchSpaceTier[] = []; + private selectionQueue: models.PriorityQueue; + private inputSequence: Distribution[] = []; + private rootNode: SearchNode; + + // We use an array and not a PriorityQueue b/c batch-heapifying at a single point in time + // is cheaper than iteratively building a priority queue. + private completedPaths: SearchNode[]; + private returnedValues: {[mapKey: string]: SearchNode} = {}; + + // Lingering question - can we get away with storing a single bit instead? + // For now, it's best to wait for the full implementation... just in case we do + // find a secondary use for this. + private processedEdgeSet: {[mapKey: string]: SearchEdge} = {}; + + constructor(traversalRoot: LexiconTraversal) { + this.selectionQueue = new models.PriorityQueue(QUEUE_SPACE_COMPARATOR); + this.rootNode = new SearchNode(traversalRoot); + + this.completedPaths = [this.rootNode]; + } + + increaseMaxEditDistance() { + this.tierOrdering.forEach(function(tier) { tier.increaseMaxEditDistance() }); + } + + addInput(inputDistribution: Distribution) { + this.inputSequence.push(inputDistribution); + + // With a newly-available input, we can extend new input-dependent paths from + // our previously-reached 'extractedResults' nodes. + let newlyAvailableEdges: SearchEdge[] = []; + let batches = this.completedPaths.map(function(node) { + let deletions = node.buildDeletionEdges(inputDistribution); + let substitutions = node.buildSubstitutionEdges(inputDistribution); + + return deletions.concat(substitutions); + }); + + // Don't forget to reset the array; the contained nodes no longer reach the search's end. + this.completedPaths = []; + this.returnedValues = {}; + + batches.forEach(function(batch) { + newlyAvailableEdges = newlyAvailableEdges.concat(batch); + }); + + // Now that we've built the new edges, we can efficiently construct the new search tier. + let tier = new SearchSpaceTier(this.tierOrdering.length, newlyAvailableEdges); + this.tierOrdering.push(tier); + this.selectionQueue.enqueue(tier); + } + + // TODO: will want eventually for reversions and/or backspaces + removeLastInput() { + // 1. truncate all entries from that search tier; we need to 'restore' extractedResults to match + // the state that would have existed without the last search tier. + // 2. remove the last search tier. Which may necessitate reconstructing the tier queue, but oh well. + } + + private hasNextMatchEntry(): boolean { + return this.selectionQueue.peek().correctionQueue.count > 0; + } + + findNextMatch(): SearchNode { + while(this.hasNextMatchEntry()) { + let bestTier = this.selectionQueue.dequeue(); + + let incomingEdge = bestTier.correctionQueue.dequeue(); + + // Have we already processed a matching edge? If so, skip it. + // We already know the previous edge is of lower cost. + if(this.processedEdgeSet[incomingEdge.mapKey]) { + this.selectionQueue.enqueue(bestTier); + continue; + } else { + this.processedEdgeSet[incomingEdge.mapKey] = incomingEdge; + } + + let currentNode = new SearchNode(this.rootNode.currentTraversal, incomingEdge); + + // Always possible, as this does not require any new input. + let insertionEdges = currentNode.buildInsertionEdges(); + bestTier.correctionQueue.enqueueAll(insertionEdges); + + if(bestTier.index == this.tierOrdering.length - 1) { + // It was the final tier - store the node for future reference. + this.completedPaths.push(currentNode); + + // Since we don't modify any other tier, we may simply reinsert the removed tier. + this.selectionQueue.enqueue(bestTier); + + return currentNode; + } else { + // Time to construct new edges for the next tier! + let nextTier = this.tierOrdering[bestTier.index+1]; + // TODO: make sure we get this part right. + let inputIndex = nextTier.index; + + let deletionEdges = currentNode.buildDeletionEdges(this.inputSequence[inputIndex]); + let substitutionEdges = currentNode.buildSubstitutionEdges(this.inputSequence[inputIndex]); + + // Note: we're live-modifying the tier's cost here! The priority queue loses its guarantees as a result. + nextTier.correctionQueue.enqueueAll(deletionEdges.concat(substitutionEdges)); + + // So, we simply rebuild the selection queue. + this.selectionQueue = new models.PriorityQueue(QUEUE_SPACE_COMPARATOR, this.tierOrdering); + + // We didn't reach an end-node, so we just end the iteration and continue the search. + } + } + + // If we've somehow fully exhausted all search options, indicate that none remain. + return null; + } + + // Current best guesstimate of how compositor will retrieve ideal corrections. + *getBestMatches(): Generator<[TraversableToken[][], number]> { + // might should also include a 'base cost' parameter of sorts? + let searchSpace = this; + let currentReturns: {[mapKey: string]: SearchNode} = {}; + + class BatchingAssistant { + currentCost = Number.MIN_SAFE_INTEGER; + entries: TraversableToken[][] = []; + + checkAndAdd(entry: SearchNode): [TraversableToken[][], number] | null { + var result: [TraversableToken[][], number] = null; + + if(entry.currentCost > this.currentCost) { + result = this.tryFinalize(); + + this.currentCost = entry.currentCost; + } + + // Filter out any duplicated match sequences. The same match sequence may be reached via + // different input sequences, after all. + let outputMapKey = entry.calculation.matchSequence.map(value => value.key).join(''); + + // First, ensure the edge has an existing 'shared' cache entry. + if(!searchSpace.returnedValues[outputMapKey]) { + searchSpace.returnedValues[outputMapKey] = entry; + } + + // Check the generator's local returned-value cache - this determines whether or not we + // need to add a new 'return' to the batch. + if(!currentReturns[outputMapKey]) { + this.entries.push(entry.calculation.matchSequence); + currentReturns[outputMapKey] = entry; + } + + return result; + } + + tryFinalize(): [TraversableToken[][], number] | null { + var result: [TraversableToken[][], number] = null; + if(this.entries.length > 0) { + result = [this.entries, this.currentCost]; + this.entries = []; + } + + return result; + } + } + + let batcher = new BatchingAssistant(); + let batch: [TraversableToken[][], number]; + + // Stage 1 - if we already have extracted results, build a queue just for them and iterate over it first. + let returnedValues = Object.values(this.returnedValues); + if(returnedValues.length > 0) { + let preprocessedQueue = new models.PriorityQueue(QUEUE_NODE_COMPARATOR, returnedValues); + + // Build batches of same-cost entries. + while(preprocessedQueue.count > 0) { + let entry = preprocessedQueue.dequeue(); + batch = batcher.checkAndAdd(entry); + + if(batch) { + yield batch; + } + } + + // As we only return a batch once all entries of the same cost have been processed, we can safely + // finalize the last preprocessed group without issue. + batch = batcher.tryFinalize(); + if(batch) { + yield batch; + } + } + + // Stage 2: the fun part; actually searching! + do { + let newResult = this.findNextMatch(); + if(!newResult) { + break; + } + batch = batcher.checkAndAdd(newResult); + + if(batch) { + yield batch; + } + } while(this.hasNextMatchEntry()); + + batch = batcher.tryFinalize(); + if(batch) { + yield batch; + } + + return null; + } + } + + // -- Code after this point is skeletal at best. -- + + export class DistanceModelerOptions { + minimumPredictions: number; + } + + export class DistanceModeler { + private options: DistanceModelerOptions; + public static readonly DEFAULT_OPTIONS: DistanceModelerOptions = { + minimumPredictions: 3 + } + + // Keep as a 'rotating cache'. Includes search spaces corresponding to 'revert' commands. + private searchSpaces: SearchSpace[] = []; + + private inputs: Distribution[] = []; + private lexiconRoot: LexiconTraversal; + + constructor(lexiconRoot: LexiconTraversal, options: DistanceModelerOptions = DistanceModeler.DEFAULT_OPTIONS) { + this.lexiconRoot = lexiconRoot; + this.options = options; + } + + addInput(input: Distribution) { + // TODO: add 'addInput' operation + // do search space things + } + } +} \ No newline at end of file diff --git a/common/predictive-text/worker/index.ts b/common/predictive-text/worker/index.ts index 8c61a51a5a47ea43d89ed214c110058dd76563f8..ffa1df429b764da3a62e551e533dea506683ebfb 100644 --- a/common/predictive-text/worker/index.ts +++ b/common/predictive-text/worker/index.ts @@ -30,9 +30,8 @@ */ /// -/// /// -/// +/// /// /** @@ -274,14 +273,13 @@ class LMLayerWorker { * @param model The loaded language model. */ private transitionToReadyState(model: LexicalModel) { + let compositor = new ModelCompositor(model); this.state = { name: 'ready', handleMessage: (payload) => { switch(payload.message) { case 'predict': let {transform, context} = payload; - let compositor = new ModelCompositor(model); // Yeah, should probably use a persistent one eventually. - let suggestions = compositor.predict(transform, context); // Now that the suggestions are ready, send them out! @@ -304,7 +302,8 @@ class LMLayerWorker { default: throw new Error(`invalid message; expected one of {'predict', 'unload'} but got ${payload.message}`); } - } + }, + compositor: compositor }; } @@ -334,6 +333,7 @@ class LMLayerWorker { // Assists unit-testing. scope['LMLayerWorker'] = worker; scope['models'] = models; + scope['correction'] = correction; scope['wordBreakers'] = wordBreakers; return worker; @@ -343,6 +343,7 @@ class LMLayerWorker { // Let LMLayerWorker be available both in the browser and in Node. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports = LMLayerWorker; + module.exports['correction'] = correction; module.exports['models'] = models; module.exports['wordBreakers'] = wordBreakers; /// XXX: export the ModelCompositor for testing. diff --git a/common/predictive-text/worker/model-compositor.ts b/common/predictive-text/worker/model-compositor.ts index eb9a2f42ef7b0f3f26a31cc2f630b855030fbcf0..8c8122d22f2cc5828e9807944c70aa7240c7b0d4 100644 --- a/common/predictive-text/worker/model-compositor.ts +++ b/common/predictive-text/worker/model-compositor.ts @@ -1,3 +1,6 @@ +/// +/// + class ModelCompositor { private lexicalModel: LexicalModel; private static readonly MAX_SUGGESTIONS = 12; diff --git a/common/predictive-text/worker/tsconfig.json b/common/predictive-text/worker/tsconfig.json index 53abdb642f5907cf280561f534c0cf2bdb50d796..19a134778f58b656040a2a340cbde475b20c413d 100644 --- a/common/predictive-text/worker/tsconfig.json +++ b/common/predictive-text/worker/tsconfig.json @@ -6,6 +6,12 @@ "outFile": "../build/intermediate/index.js", "sourceMap": true, "lib": ["webworker", "es6"], - "target": "es5" - } + "target": "es5", + "downlevelIteration": true + }, + "include": [ + "../node_modules/@keymanapp/web-environment/environment.inc.ts", + "../node_modules/@keymanapp/web-utils/src/index.ts", + "./**/*.ts", + ] } diff --git a/common/predictive-text/worker/word_breaking/default-word-breaking/data.ts b/common/predictive-text/worker/word_breaking/default-word-breaking/data.ts deleted file mode 100644 index a0bb37c5562deb6ce49bc17751f5a86f778f27a2..0000000000000000000000000000000000000000 --- a/common/predictive-text/worker/word_breaking/default-word-breaking/data.ts +++ /dev/null @@ -1,1296 +0,0 @@ -namespace wordBreakers { -export namespace data { -// Automatically generated file. DO NOT MODIFY. -/** - * Valid values for a word break property. - */ -export const enum WordBreakProperty { - Other, - LF, - Newline, - CR, - WSegSpace, - Double_Quote, - Single_Quote, - MidNum, - MidNumLet, - Numeric, - MidLetter, - ALetter, - ExtendNumLet, - Format, - Extend, - Hebrew_Letter, - ZWJ, - Katakana, - Regional_Indicator, - sot, - eot -}; - -/** - * Constants for indexing values in WORD_BREAK_PROPERTY. - */ -export const enum I { - Start = 0, - End = 1, - Value = 2 -} - -export const WORD_BREAK_PROPERTY: [number, number, WordBreakProperty][] = [ - [/*start*/ 0xA, /*end*/ 0xA, WordBreakProperty.LF], - [/*start*/ 0xB, /*end*/ 0xC, WordBreakProperty.Newline], - [/*start*/ 0xD, /*end*/ 0xD, WordBreakProperty.CR], - [/*start*/ 0x20, /*end*/ 0x20, WordBreakProperty.WSegSpace], - [/*start*/ 0x22, /*end*/ 0x22, WordBreakProperty.Double_Quote], - [/*start*/ 0x27, /*end*/ 0x27, WordBreakProperty.Single_Quote], - [/*start*/ 0x2C, /*end*/ 0x2C, WordBreakProperty.MidNum], - [/*start*/ 0x2E, /*end*/ 0x2E, WordBreakProperty.MidNumLet], - [/*start*/ 0x30, /*end*/ 0x39, WordBreakProperty.Numeric], - [/*start*/ 0x3A, /*end*/ 0x3A, WordBreakProperty.MidLetter], - [/*start*/ 0x3B, /*end*/ 0x3B, WordBreakProperty.MidNum], - [/*start*/ 0x41, /*end*/ 0x5A, WordBreakProperty.ALetter], - [/*start*/ 0x5F, /*end*/ 0x5F, WordBreakProperty.ExtendNumLet], - [/*start*/ 0x61, /*end*/ 0x7A, WordBreakProperty.ALetter], - [/*start*/ 0x85, /*end*/ 0x85, WordBreakProperty.Newline], - [/*start*/ 0xAA, /*end*/ 0xAA, WordBreakProperty.ALetter], - [/*start*/ 0xAD, /*end*/ 0xAD, WordBreakProperty.Format], - [/*start*/ 0xB5, /*end*/ 0xB5, WordBreakProperty.ALetter], - [/*start*/ 0xB7, /*end*/ 0xB7, WordBreakProperty.MidLetter], - [/*start*/ 0xBA, /*end*/ 0xBA, WordBreakProperty.ALetter], - [/*start*/ 0xC0, /*end*/ 0xD6, WordBreakProperty.ALetter], - [/*start*/ 0xD8, /*end*/ 0xF6, WordBreakProperty.ALetter], - [/*start*/ 0xF8, /*end*/ 0x1BA, WordBreakProperty.ALetter], - [/*start*/ 0x1BB, /*end*/ 0x1BB, WordBreakProperty.ALetter], - [/*start*/ 0x1BC, /*end*/ 0x1BF, WordBreakProperty.ALetter], - [/*start*/ 0x1C0, /*end*/ 0x1C3, WordBreakProperty.ALetter], - [/*start*/ 0x1C4, /*end*/ 0x293, WordBreakProperty.ALetter], - [/*start*/ 0x294, /*end*/ 0x294, WordBreakProperty.ALetter], - [/*start*/ 0x295, /*end*/ 0x2AF, WordBreakProperty.ALetter], - [/*start*/ 0x2B0, /*end*/ 0x2C1, WordBreakProperty.ALetter], - [/*start*/ 0x2C2, /*end*/ 0x2C5, WordBreakProperty.ALetter], - [/*start*/ 0x2C6, /*end*/ 0x2D1, WordBreakProperty.ALetter], - [/*start*/ 0x2D2, /*end*/ 0x2D7, WordBreakProperty.ALetter], - [/*start*/ 0x2DE, /*end*/ 0x2DF, WordBreakProperty.ALetter], - [/*start*/ 0x2E0, /*end*/ 0x2E4, WordBreakProperty.ALetter], - [/*start*/ 0x2EC, /*end*/ 0x2EC, WordBreakProperty.ALetter], - [/*start*/ 0x2ED, /*end*/ 0x2ED, WordBreakProperty.ALetter], - [/*start*/ 0x2EE, /*end*/ 0x2EE, WordBreakProperty.ALetter], - [/*start*/ 0x2EF, /*end*/ 0x2FF, WordBreakProperty.ALetter], - [/*start*/ 0x300, /*end*/ 0x36F, WordBreakProperty.Extend], - [/*start*/ 0x370, /*end*/ 0x373, WordBreakProperty.ALetter], - [/*start*/ 0x374, /*end*/ 0x374, WordBreakProperty.ALetter], - [/*start*/ 0x376, /*end*/ 0x377, WordBreakProperty.ALetter], - [/*start*/ 0x37A, /*end*/ 0x37A, WordBreakProperty.ALetter], - [/*start*/ 0x37B, /*end*/ 0x37D, WordBreakProperty.ALetter], - [/*start*/ 0x37E, /*end*/ 0x37E, WordBreakProperty.MidNum], - [/*start*/ 0x37F, /*end*/ 0x37F, WordBreakProperty.ALetter], - [/*start*/ 0x386, /*end*/ 0x386, WordBreakProperty.ALetter], - [/*start*/ 0x387, /*end*/ 0x387, WordBreakProperty.MidLetter], - [/*start*/ 0x388, /*end*/ 0x38A, WordBreakProperty.ALetter], - [/*start*/ 0x38C, /*end*/ 0x38C, WordBreakProperty.ALetter], - [/*start*/ 0x38E, /*end*/ 0x3A1, WordBreakProperty.ALetter], - [/*start*/ 0x3A3, /*end*/ 0x3F5, WordBreakProperty.ALetter], - [/*start*/ 0x3F7, /*end*/ 0x481, WordBreakProperty.ALetter], - [/*start*/ 0x483, /*end*/ 0x487, WordBreakProperty.Extend], - [/*start*/ 0x488, /*end*/ 0x489, WordBreakProperty.Extend], - [/*start*/ 0x48A, /*end*/ 0x52F, WordBreakProperty.ALetter], - [/*start*/ 0x531, /*end*/ 0x556, WordBreakProperty.ALetter], - [/*start*/ 0x559, /*end*/ 0x559, WordBreakProperty.ALetter], - [/*start*/ 0x55B, /*end*/ 0x55C, WordBreakProperty.ALetter], - [/*start*/ 0x55E, /*end*/ 0x55E, WordBreakProperty.ALetter], - [/*start*/ 0x560, /*end*/ 0x588, WordBreakProperty.ALetter], - [/*start*/ 0x589, /*end*/ 0x589, WordBreakProperty.MidNum], - [/*start*/ 0x591, /*end*/ 0x5BD, WordBreakProperty.Extend], - [/*start*/ 0x5BF, /*end*/ 0x5BF, WordBreakProperty.Extend], - [/*start*/ 0x5C1, /*end*/ 0x5C2, WordBreakProperty.Extend], - [/*start*/ 0x5C4, /*end*/ 0x5C5, WordBreakProperty.Extend], - [/*start*/ 0x5C7, /*end*/ 0x5C7, WordBreakProperty.Extend], - [/*start*/ 0x5D0, /*end*/ 0x5EA, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0x5EF, /*end*/ 0x5F2, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0x5F3, /*end*/ 0x5F3, WordBreakProperty.ALetter], - [/*start*/ 0x5F4, /*end*/ 0x5F4, WordBreakProperty.MidLetter], - [/*start*/ 0x600, /*end*/ 0x605, WordBreakProperty.Format], - [/*start*/ 0x60C, /*end*/ 0x60D, WordBreakProperty.MidNum], - [/*start*/ 0x610, /*end*/ 0x61A, WordBreakProperty.Extend], - [/*start*/ 0x61C, /*end*/ 0x61C, WordBreakProperty.Format], - [/*start*/ 0x620, /*end*/ 0x63F, WordBreakProperty.ALetter], - [/*start*/ 0x640, /*end*/ 0x640, WordBreakProperty.ALetter], - [/*start*/ 0x641, /*end*/ 0x64A, WordBreakProperty.ALetter], - [/*start*/ 0x64B, /*end*/ 0x65F, WordBreakProperty.Extend], - [/*start*/ 0x660, /*end*/ 0x669, WordBreakProperty.Numeric], - [/*start*/ 0x66B, /*end*/ 0x66B, WordBreakProperty.Numeric], - [/*start*/ 0x66C, /*end*/ 0x66C, WordBreakProperty.MidNum], - [/*start*/ 0x66E, /*end*/ 0x66F, WordBreakProperty.ALetter], - [/*start*/ 0x670, /*end*/ 0x670, WordBreakProperty.Extend], - [/*start*/ 0x671, /*end*/ 0x6D3, WordBreakProperty.ALetter], - [/*start*/ 0x6D5, /*end*/ 0x6D5, WordBreakProperty.ALetter], - [/*start*/ 0x6D6, /*end*/ 0x6DC, WordBreakProperty.Extend], - [/*start*/ 0x6DD, /*end*/ 0x6DD, WordBreakProperty.Format], - [/*start*/ 0x6DF, /*end*/ 0x6E4, WordBreakProperty.Extend], - [/*start*/ 0x6E5, /*end*/ 0x6E6, WordBreakProperty.ALetter], - [/*start*/ 0x6E7, /*end*/ 0x6E8, WordBreakProperty.Extend], - [/*start*/ 0x6EA, /*end*/ 0x6ED, WordBreakProperty.Extend], - [/*start*/ 0x6EE, /*end*/ 0x6EF, WordBreakProperty.ALetter], - [/*start*/ 0x6F0, /*end*/ 0x6F9, WordBreakProperty.Numeric], - [/*start*/ 0x6FA, /*end*/ 0x6FC, WordBreakProperty.ALetter], - [/*start*/ 0x6FF, /*end*/ 0x6FF, WordBreakProperty.ALetter], - [/*start*/ 0x70F, /*end*/ 0x70F, WordBreakProperty.Format], - [/*start*/ 0x710, /*end*/ 0x710, WordBreakProperty.ALetter], - [/*start*/ 0x711, /*end*/ 0x711, WordBreakProperty.Extend], - [/*start*/ 0x712, /*end*/ 0x72F, WordBreakProperty.ALetter], - [/*start*/ 0x730, /*end*/ 0x74A, WordBreakProperty.Extend], - [/*start*/ 0x74D, /*end*/ 0x7A5, WordBreakProperty.ALetter], - [/*start*/ 0x7A6, /*end*/ 0x7B0, WordBreakProperty.Extend], - [/*start*/ 0x7B1, /*end*/ 0x7B1, WordBreakProperty.ALetter], - [/*start*/ 0x7C0, /*end*/ 0x7C9, WordBreakProperty.Numeric], - [/*start*/ 0x7CA, /*end*/ 0x7EA, WordBreakProperty.ALetter], - [/*start*/ 0x7EB, /*end*/ 0x7F3, WordBreakProperty.Extend], - [/*start*/ 0x7F4, /*end*/ 0x7F5, WordBreakProperty.ALetter], - [/*start*/ 0x7F8, /*end*/ 0x7F8, WordBreakProperty.MidNum], - [/*start*/ 0x7FA, /*end*/ 0x7FA, WordBreakProperty.ALetter], - [/*start*/ 0x7FD, /*end*/ 0x7FD, WordBreakProperty.Extend], - [/*start*/ 0x800, /*end*/ 0x815, WordBreakProperty.ALetter], - [/*start*/ 0x816, /*end*/ 0x819, WordBreakProperty.Extend], - [/*start*/ 0x81A, /*end*/ 0x81A, WordBreakProperty.ALetter], - [/*start*/ 0x81B, /*end*/ 0x823, WordBreakProperty.Extend], - [/*start*/ 0x824, /*end*/ 0x824, WordBreakProperty.ALetter], - [/*start*/ 0x825, /*end*/ 0x827, WordBreakProperty.Extend], - [/*start*/ 0x828, /*end*/ 0x828, WordBreakProperty.ALetter], - [/*start*/ 0x829, /*end*/ 0x82D, WordBreakProperty.Extend], - [/*start*/ 0x840, /*end*/ 0x858, WordBreakProperty.ALetter], - [/*start*/ 0x859, /*end*/ 0x85B, WordBreakProperty.Extend], - [/*start*/ 0x860, /*end*/ 0x86A, WordBreakProperty.ALetter], - [/*start*/ 0x8A0, /*end*/ 0x8B4, WordBreakProperty.ALetter], - [/*start*/ 0x8B6, /*end*/ 0x8BD, WordBreakProperty.ALetter], - [/*start*/ 0x8D3, /*end*/ 0x8E1, WordBreakProperty.Extend], - [/*start*/ 0x8E2, /*end*/ 0x8E2, WordBreakProperty.Format], - [/*start*/ 0x8E3, /*end*/ 0x902, WordBreakProperty.Extend], - [/*start*/ 0x903, /*end*/ 0x903, WordBreakProperty.Extend], - [/*start*/ 0x904, /*end*/ 0x939, WordBreakProperty.ALetter], - [/*start*/ 0x93A, /*end*/ 0x93A, WordBreakProperty.Extend], - [/*start*/ 0x93B, /*end*/ 0x93B, WordBreakProperty.Extend], - [/*start*/ 0x93C, /*end*/ 0x93C, WordBreakProperty.Extend], - [/*start*/ 0x93D, /*end*/ 0x93D, WordBreakProperty.ALetter], - [/*start*/ 0x93E, /*end*/ 0x940, WordBreakProperty.Extend], - [/*start*/ 0x941, /*end*/ 0x948, WordBreakProperty.Extend], - [/*start*/ 0x949, /*end*/ 0x94C, WordBreakProperty.Extend], - [/*start*/ 0x94D, /*end*/ 0x94D, WordBreakProperty.Extend], - [/*start*/ 0x94E, /*end*/ 0x94F, WordBreakProperty.Extend], - [/*start*/ 0x950, /*end*/ 0x950, WordBreakProperty.ALetter], - [/*start*/ 0x951, /*end*/ 0x957, WordBreakProperty.Extend], - [/*start*/ 0x958, /*end*/ 0x961, WordBreakProperty.ALetter], - [/*start*/ 0x962, /*end*/ 0x963, WordBreakProperty.Extend], - [/*start*/ 0x966, /*end*/ 0x96F, WordBreakProperty.Numeric], - [/*start*/ 0x971, /*end*/ 0x971, WordBreakProperty.ALetter], - [/*start*/ 0x972, /*end*/ 0x980, WordBreakProperty.ALetter], - [/*start*/ 0x981, /*end*/ 0x981, WordBreakProperty.Extend], - [/*start*/ 0x982, /*end*/ 0x983, WordBreakProperty.Extend], - [/*start*/ 0x985, /*end*/ 0x98C, WordBreakProperty.ALetter], - [/*start*/ 0x98F, /*end*/ 0x990, WordBreakProperty.ALetter], - [/*start*/ 0x993, /*end*/ 0x9A8, WordBreakProperty.ALetter], - [/*start*/ 0x9AA, /*end*/ 0x9B0, WordBreakProperty.ALetter], - [/*start*/ 0x9B2, /*end*/ 0x9B2, WordBreakProperty.ALetter], - [/*start*/ 0x9B6, /*end*/ 0x9B9, WordBreakProperty.ALetter], - [/*start*/ 0x9BC, /*end*/ 0x9BC, WordBreakProperty.Extend], - [/*start*/ 0x9BD, /*end*/ 0x9BD, WordBreakProperty.ALetter], - [/*start*/ 0x9BE, /*end*/ 0x9C0, WordBreakProperty.Extend], - [/*start*/ 0x9C1, /*end*/ 0x9C4, WordBreakProperty.Extend], - [/*start*/ 0x9C7, /*end*/ 0x9C8, WordBreakProperty.Extend], - [/*start*/ 0x9CB, /*end*/ 0x9CC, WordBreakProperty.Extend], - [/*start*/ 0x9CD, /*end*/ 0x9CD, WordBreakProperty.Extend], - [/*start*/ 0x9CE, /*end*/ 0x9CE, WordBreakProperty.ALetter], - [/*start*/ 0x9D7, /*end*/ 0x9D7, WordBreakProperty.Extend], - [/*start*/ 0x9DC, /*end*/ 0x9DD, WordBreakProperty.ALetter], - [/*start*/ 0x9DF, /*end*/ 0x9E1, WordBreakProperty.ALetter], - [/*start*/ 0x9E2, /*end*/ 0x9E3, WordBreakProperty.Extend], - [/*start*/ 0x9E6, /*end*/ 0x9EF, WordBreakProperty.Numeric], - [/*start*/ 0x9F0, /*end*/ 0x9F1, WordBreakProperty.ALetter], - [/*start*/ 0x9FC, /*end*/ 0x9FC, WordBreakProperty.ALetter], - [/*start*/ 0x9FE, /*end*/ 0x9FE, WordBreakProperty.Extend], - [/*start*/ 0xA01, /*end*/ 0xA02, WordBreakProperty.Extend], - [/*start*/ 0xA03, /*end*/ 0xA03, WordBreakProperty.Extend], - [/*start*/ 0xA05, /*end*/ 0xA0A, WordBreakProperty.ALetter], - [/*start*/ 0xA0F, /*end*/ 0xA10, WordBreakProperty.ALetter], - [/*start*/ 0xA13, /*end*/ 0xA28, WordBreakProperty.ALetter], - [/*start*/ 0xA2A, /*end*/ 0xA30, WordBreakProperty.ALetter], - [/*start*/ 0xA32, /*end*/ 0xA33, WordBreakProperty.ALetter], - [/*start*/ 0xA35, /*end*/ 0xA36, WordBreakProperty.ALetter], - [/*start*/ 0xA38, /*end*/ 0xA39, WordBreakProperty.ALetter], - [/*start*/ 0xA3C, /*end*/ 0xA3C, WordBreakProperty.Extend], - [/*start*/ 0xA3E, /*end*/ 0xA40, WordBreakProperty.Extend], - [/*start*/ 0xA41, /*end*/ 0xA42, WordBreakProperty.Extend], - [/*start*/ 0xA47, /*end*/ 0xA48, WordBreakProperty.Extend], - [/*start*/ 0xA4B, /*end*/ 0xA4D, WordBreakProperty.Extend], - [/*start*/ 0xA51, /*end*/ 0xA51, WordBreakProperty.Extend], - [/*start*/ 0xA59, /*end*/ 0xA5C, WordBreakProperty.ALetter], - [/*start*/ 0xA5E, /*end*/ 0xA5E, WordBreakProperty.ALetter], - [/*start*/ 0xA66, /*end*/ 0xA6F, WordBreakProperty.Numeric], - [/*start*/ 0xA70, /*end*/ 0xA71, WordBreakProperty.Extend], - [/*start*/ 0xA72, /*end*/ 0xA74, WordBreakProperty.ALetter], - [/*start*/ 0xA75, /*end*/ 0xA75, WordBreakProperty.Extend], - [/*start*/ 0xA81, /*end*/ 0xA82, WordBreakProperty.Extend], - [/*start*/ 0xA83, /*end*/ 0xA83, WordBreakProperty.Extend], - [/*start*/ 0xA85, /*end*/ 0xA8D, WordBreakProperty.ALetter], - [/*start*/ 0xA8F, /*end*/ 0xA91, WordBreakProperty.ALetter], - [/*start*/ 0xA93, /*end*/ 0xAA8, WordBreakProperty.ALetter], - [/*start*/ 0xAAA, /*end*/ 0xAB0, WordBreakProperty.ALetter], - [/*start*/ 0xAB2, /*end*/ 0xAB3, WordBreakProperty.ALetter], - [/*start*/ 0xAB5, /*end*/ 0xAB9, WordBreakProperty.ALetter], - [/*start*/ 0xABC, /*end*/ 0xABC, WordBreakProperty.Extend], - [/*start*/ 0xABD, /*end*/ 0xABD, WordBreakProperty.ALetter], - [/*start*/ 0xABE, /*end*/ 0xAC0, WordBreakProperty.Extend], - [/*start*/ 0xAC1, /*end*/ 0xAC5, WordBreakProperty.Extend], - [/*start*/ 0xAC7, /*end*/ 0xAC8, WordBreakProperty.Extend], - [/*start*/ 0xAC9, /*end*/ 0xAC9, WordBreakProperty.Extend], - [/*start*/ 0xACB, /*end*/ 0xACC, WordBreakProperty.Extend], - [/*start*/ 0xACD, /*end*/ 0xACD, WordBreakProperty.Extend], - [/*start*/ 0xAD0, /*end*/ 0xAD0, WordBreakProperty.ALetter], - [/*start*/ 0xAE0, /*end*/ 0xAE1, WordBreakProperty.ALetter], - [/*start*/ 0xAE2, /*end*/ 0xAE3, WordBreakProperty.Extend], - [/*start*/ 0xAE6, /*end*/ 0xAEF, WordBreakProperty.Numeric], - [/*start*/ 0xAF9, /*end*/ 0xAF9, WordBreakProperty.ALetter], - [/*start*/ 0xAFA, /*end*/ 0xAFF, WordBreakProperty.Extend], - [/*start*/ 0xB01, /*end*/ 0xB01, WordBreakProperty.Extend], - [/*start*/ 0xB02, /*end*/ 0xB03, WordBreakProperty.Extend], - [/*start*/ 0xB05, /*end*/ 0xB0C, WordBreakProperty.ALetter], - [/*start*/ 0xB0F, /*end*/ 0xB10, WordBreakProperty.ALetter], - [/*start*/ 0xB13, /*end*/ 0xB28, WordBreakProperty.ALetter], - [/*start*/ 0xB2A, /*end*/ 0xB30, WordBreakProperty.ALetter], - [/*start*/ 0xB32, /*end*/ 0xB33, WordBreakProperty.ALetter], - [/*start*/ 0xB35, /*end*/ 0xB39, WordBreakProperty.ALetter], - [/*start*/ 0xB3C, /*end*/ 0xB3C, WordBreakProperty.Extend], - [/*start*/ 0xB3D, /*end*/ 0xB3D, WordBreakProperty.ALetter], - [/*start*/ 0xB3E, /*end*/ 0xB3E, WordBreakProperty.Extend], - [/*start*/ 0xB3F, /*end*/ 0xB3F, WordBreakProperty.Extend], - [/*start*/ 0xB40, /*end*/ 0xB40, WordBreakProperty.Extend], - [/*start*/ 0xB41, /*end*/ 0xB44, WordBreakProperty.Extend], - [/*start*/ 0xB47, /*end*/ 0xB48, WordBreakProperty.Extend], - [/*start*/ 0xB4B, /*end*/ 0xB4C, WordBreakProperty.Extend], - [/*start*/ 0xB4D, /*end*/ 0xB4D, WordBreakProperty.Extend], - [/*start*/ 0xB56, /*end*/ 0xB56, WordBreakProperty.Extend], - [/*start*/ 0xB57, /*end*/ 0xB57, WordBreakProperty.Extend], - [/*start*/ 0xB5C, /*end*/ 0xB5D, WordBreakProperty.ALetter], - [/*start*/ 0xB5F, /*end*/ 0xB61, WordBreakProperty.ALetter], - [/*start*/ 0xB62, /*end*/ 0xB63, WordBreakProperty.Extend], - [/*start*/ 0xB66, /*end*/ 0xB6F, WordBreakProperty.Numeric], - [/*start*/ 0xB71, /*end*/ 0xB71, WordBreakProperty.ALetter], - [/*start*/ 0xB82, /*end*/ 0xB82, WordBreakProperty.Extend], - [/*start*/ 0xB83, /*end*/ 0xB83, WordBreakProperty.ALetter], - [/*start*/ 0xB85, /*end*/ 0xB8A, WordBreakProperty.ALetter], - [/*start*/ 0xB8E, /*end*/ 0xB90, WordBreakProperty.ALetter], - [/*start*/ 0xB92, /*end*/ 0xB95, WordBreakProperty.ALetter], - [/*start*/ 0xB99, /*end*/ 0xB9A, WordBreakProperty.ALetter], - [/*start*/ 0xB9C, /*end*/ 0xB9C, WordBreakProperty.ALetter], - [/*start*/ 0xB9E, /*end*/ 0xB9F, WordBreakProperty.ALetter], - [/*start*/ 0xBA3, /*end*/ 0xBA4, WordBreakProperty.ALetter], - [/*start*/ 0xBA8, /*end*/ 0xBAA, WordBreakProperty.ALetter], - [/*start*/ 0xBAE, /*end*/ 0xBB9, WordBreakProperty.ALetter], - [/*start*/ 0xBBE, /*end*/ 0xBBF, WordBreakProperty.Extend], - [/*start*/ 0xBC0, /*end*/ 0xBC0, WordBreakProperty.Extend], - [/*start*/ 0xBC1, /*end*/ 0xBC2, WordBreakProperty.Extend], - [/*start*/ 0xBC6, /*end*/ 0xBC8, WordBreakProperty.Extend], - [/*start*/ 0xBCA, /*end*/ 0xBCC, WordBreakProperty.Extend], - [/*start*/ 0xBCD, /*end*/ 0xBCD, WordBreakProperty.Extend], - [/*start*/ 0xBD0, /*end*/ 0xBD0, WordBreakProperty.ALetter], - [/*start*/ 0xBD7, /*end*/ 0xBD7, WordBreakProperty.Extend], - [/*start*/ 0xBE6, /*end*/ 0xBEF, WordBreakProperty.Numeric], - [/*start*/ 0xC00, /*end*/ 0xC00, WordBreakProperty.Extend], - [/*start*/ 0xC01, /*end*/ 0xC03, WordBreakProperty.Extend], - [/*start*/ 0xC04, /*end*/ 0xC04, WordBreakProperty.Extend], - [/*start*/ 0xC05, /*end*/ 0xC0C, WordBreakProperty.ALetter], - [/*start*/ 0xC0E, /*end*/ 0xC10, WordBreakProperty.ALetter], - [/*start*/ 0xC12, /*end*/ 0xC28, WordBreakProperty.ALetter], - [/*start*/ 0xC2A, /*end*/ 0xC39, WordBreakProperty.ALetter], - [/*start*/ 0xC3D, /*end*/ 0xC3D, WordBreakProperty.ALetter], - [/*start*/ 0xC3E, /*end*/ 0xC40, WordBreakProperty.Extend], - [/*start*/ 0xC41, /*end*/ 0xC44, WordBreakProperty.Extend], - [/*start*/ 0xC46, /*end*/ 0xC48, WordBreakProperty.Extend], - [/*start*/ 0xC4A, /*end*/ 0xC4D, WordBreakProperty.Extend], - [/*start*/ 0xC55, /*end*/ 0xC56, WordBreakProperty.Extend], - [/*start*/ 0xC58, /*end*/ 0xC5A, WordBreakProperty.ALetter], - [/*start*/ 0xC60, /*end*/ 0xC61, WordBreakProperty.ALetter], - [/*start*/ 0xC62, /*end*/ 0xC63, WordBreakProperty.Extend], - [/*start*/ 0xC66, /*end*/ 0xC6F, WordBreakProperty.Numeric], - [/*start*/ 0xC80, /*end*/ 0xC80, WordBreakProperty.ALetter], - [/*start*/ 0xC81, /*end*/ 0xC81, WordBreakProperty.Extend], - [/*start*/ 0xC82, /*end*/ 0xC83, WordBreakProperty.Extend], - [/*start*/ 0xC85, /*end*/ 0xC8C, WordBreakProperty.ALetter], - [/*start*/ 0xC8E, /*end*/ 0xC90, WordBreakProperty.ALetter], - [/*start*/ 0xC92, /*end*/ 0xCA8, WordBreakProperty.ALetter], - [/*start*/ 0xCAA, /*end*/ 0xCB3, WordBreakProperty.ALetter], - [/*start*/ 0xCB5, /*end*/ 0xCB9, WordBreakProperty.ALetter], - [/*start*/ 0xCBC, /*end*/ 0xCBC, WordBreakProperty.Extend], - [/*start*/ 0xCBD, /*end*/ 0xCBD, WordBreakProperty.ALetter], - [/*start*/ 0xCBE, /*end*/ 0xCBE, WordBreakProperty.Extend], - [/*start*/ 0xCBF, /*end*/ 0xCBF, WordBreakProperty.Extend], - [/*start*/ 0xCC0, /*end*/ 0xCC4, WordBreakProperty.Extend], - [/*start*/ 0xCC6, /*end*/ 0xCC6, WordBreakProperty.Extend], - [/*start*/ 0xCC7, /*end*/ 0xCC8, WordBreakProperty.Extend], - [/*start*/ 0xCCA, /*end*/ 0xCCB, WordBreakProperty.Extend], - [/*start*/ 0xCCC, /*end*/ 0xCCD, WordBreakProperty.Extend], - [/*start*/ 0xCD5, /*end*/ 0xCD6, WordBreakProperty.Extend], - [/*start*/ 0xCDE, /*end*/ 0xCDE, WordBreakProperty.ALetter], - [/*start*/ 0xCE0, /*end*/ 0xCE1, WordBreakProperty.ALetter], - [/*start*/ 0xCE2, /*end*/ 0xCE3, WordBreakProperty.Extend], - [/*start*/ 0xCE6, /*end*/ 0xCEF, WordBreakProperty.Numeric], - [/*start*/ 0xCF1, /*end*/ 0xCF2, WordBreakProperty.ALetter], - [/*start*/ 0xD00, /*end*/ 0xD01, WordBreakProperty.Extend], - [/*start*/ 0xD02, /*end*/ 0xD03, WordBreakProperty.Extend], - [/*start*/ 0xD05, /*end*/ 0xD0C, WordBreakProperty.ALetter], - [/*start*/ 0xD0E, /*end*/ 0xD10, WordBreakProperty.ALetter], - [/*start*/ 0xD12, /*end*/ 0xD3A, WordBreakProperty.ALetter], - [/*start*/ 0xD3B, /*end*/ 0xD3C, WordBreakProperty.Extend], - [/*start*/ 0xD3D, /*end*/ 0xD3D, WordBreakProperty.ALetter], - [/*start*/ 0xD3E, /*end*/ 0xD40, WordBreakProperty.Extend], - [/*start*/ 0xD41, /*end*/ 0xD44, WordBreakProperty.Extend], - [/*start*/ 0xD46, /*end*/ 0xD48, WordBreakProperty.Extend], - [/*start*/ 0xD4A, /*end*/ 0xD4C, WordBreakProperty.Extend], - [/*start*/ 0xD4D, /*end*/ 0xD4D, WordBreakProperty.Extend], - [/*start*/ 0xD4E, /*end*/ 0xD4E, WordBreakProperty.ALetter], - [/*start*/ 0xD54, /*end*/ 0xD56, WordBreakProperty.ALetter], - [/*start*/ 0xD57, /*end*/ 0xD57, WordBreakProperty.Extend], - [/*start*/ 0xD5F, /*end*/ 0xD61, WordBreakProperty.ALetter], - [/*start*/ 0xD62, /*end*/ 0xD63, WordBreakProperty.Extend], - [/*start*/ 0xD66, /*end*/ 0xD6F, WordBreakProperty.Numeric], - [/*start*/ 0xD7A, /*end*/ 0xD7F, WordBreakProperty.ALetter], - [/*start*/ 0xD82, /*end*/ 0xD83, WordBreakProperty.Extend], - [/*start*/ 0xD85, /*end*/ 0xD96, WordBreakProperty.ALetter], - [/*start*/ 0xD9A, /*end*/ 0xDB1, WordBreakProperty.ALetter], - [/*start*/ 0xDB3, /*end*/ 0xDBB, WordBreakProperty.ALetter], - [/*start*/ 0xDBD, /*end*/ 0xDBD, WordBreakProperty.ALetter], - [/*start*/ 0xDC0, /*end*/ 0xDC6, WordBreakProperty.ALetter], - [/*start*/ 0xDCA, /*end*/ 0xDCA, WordBreakProperty.Extend], - [/*start*/ 0xDCF, /*end*/ 0xDD1, WordBreakProperty.Extend], - [/*start*/ 0xDD2, /*end*/ 0xDD4, WordBreakProperty.Extend], - [/*start*/ 0xDD6, /*end*/ 0xDD6, WordBreakProperty.Extend], - [/*start*/ 0xDD8, /*end*/ 0xDDF, WordBreakProperty.Extend], - [/*start*/ 0xDE6, /*end*/ 0xDEF, WordBreakProperty.Numeric], - [/*start*/ 0xDF2, /*end*/ 0xDF3, WordBreakProperty.Extend], - [/*start*/ 0xE31, /*end*/ 0xE31, WordBreakProperty.Extend], - [/*start*/ 0xE34, /*end*/ 0xE3A, WordBreakProperty.Extend], - [/*start*/ 0xE47, /*end*/ 0xE4E, WordBreakProperty.Extend], - [/*start*/ 0xE50, /*end*/ 0xE59, WordBreakProperty.Numeric], - [/*start*/ 0xEB1, /*end*/ 0xEB1, WordBreakProperty.Extend], - [/*start*/ 0xEB4, /*end*/ 0xEBC, WordBreakProperty.Extend], - [/*start*/ 0xEC8, /*end*/ 0xECD, WordBreakProperty.Extend], - [/*start*/ 0xED0, /*end*/ 0xED9, WordBreakProperty.Numeric], - [/*start*/ 0xF00, /*end*/ 0xF00, WordBreakProperty.ALetter], - [/*start*/ 0xF18, /*end*/ 0xF19, WordBreakProperty.Extend], - [/*start*/ 0xF20, /*end*/ 0xF29, WordBreakProperty.Numeric], - [/*start*/ 0xF35, /*end*/ 0xF35, WordBreakProperty.Extend], - [/*start*/ 0xF37, /*end*/ 0xF37, WordBreakProperty.Extend], - [/*start*/ 0xF39, /*end*/ 0xF39, WordBreakProperty.Extend], - [/*start*/ 0xF3E, /*end*/ 0xF3F, WordBreakProperty.Extend], - [/*start*/ 0xF40, /*end*/ 0xF47, WordBreakProperty.ALetter], - [/*start*/ 0xF49, /*end*/ 0xF6C, WordBreakProperty.ALetter], - [/*start*/ 0xF71, /*end*/ 0xF7E, WordBreakProperty.Extend], - [/*start*/ 0xF7F, /*end*/ 0xF7F, WordBreakProperty.Extend], - [/*start*/ 0xF80, /*end*/ 0xF84, WordBreakProperty.Extend], - [/*start*/ 0xF86, /*end*/ 0xF87, WordBreakProperty.Extend], - [/*start*/ 0xF88, /*end*/ 0xF8C, WordBreakProperty.ALetter], - [/*start*/ 0xF8D, /*end*/ 0xF97, WordBreakProperty.Extend], - [/*start*/ 0xF99, /*end*/ 0xFBC, WordBreakProperty.Extend], - [/*start*/ 0xFC6, /*end*/ 0xFC6, WordBreakProperty.Extend], - [/*start*/ 0x102B, /*end*/ 0x102C, WordBreakProperty.Extend], - [/*start*/ 0x102D, /*end*/ 0x1030, WordBreakProperty.Extend], - [/*start*/ 0x1031, /*end*/ 0x1031, WordBreakProperty.Extend], - [/*start*/ 0x1032, /*end*/ 0x1037, WordBreakProperty.Extend], - [/*start*/ 0x1038, /*end*/ 0x1038, WordBreakProperty.Extend], - [/*start*/ 0x1039, /*end*/ 0x103A, WordBreakProperty.Extend], - [/*start*/ 0x103B, /*end*/ 0x103C, WordBreakProperty.Extend], - [/*start*/ 0x103D, /*end*/ 0x103E, WordBreakProperty.Extend], - [/*start*/ 0x1040, /*end*/ 0x1049, WordBreakProperty.Numeric], - [/*start*/ 0x1056, /*end*/ 0x1057, WordBreakProperty.Extend], - [/*start*/ 0x1058, /*end*/ 0x1059, WordBreakProperty.Extend], - [/*start*/ 0x105E, /*end*/ 0x1060, WordBreakProperty.Extend], - [/*start*/ 0x1062, /*end*/ 0x1064, WordBreakProperty.Extend], - [/*start*/ 0x1067, /*end*/ 0x106D, WordBreakProperty.Extend], - [/*start*/ 0x1071, /*end*/ 0x1074, WordBreakProperty.Extend], - [/*start*/ 0x1082, /*end*/ 0x1082, WordBreakProperty.Extend], - [/*start*/ 0x1083, /*end*/ 0x1084, WordBreakProperty.Extend], - [/*start*/ 0x1085, /*end*/ 0x1086, WordBreakProperty.Extend], - [/*start*/ 0x1087, /*end*/ 0x108C, WordBreakProperty.Extend], - [/*start*/ 0x108D, /*end*/ 0x108D, WordBreakProperty.Extend], - [/*start*/ 0x108F, /*end*/ 0x108F, WordBreakProperty.Extend], - [/*start*/ 0x1090, /*end*/ 0x1099, WordBreakProperty.Numeric], - [/*start*/ 0x109A, /*end*/ 0x109C, WordBreakProperty.Extend], - [/*start*/ 0x109D, /*end*/ 0x109D, WordBreakProperty.Extend], - [/*start*/ 0x10A0, /*end*/ 0x10C5, WordBreakProperty.ALetter], - [/*start*/ 0x10C7, /*end*/ 0x10C7, WordBreakProperty.ALetter], - [/*start*/ 0x10CD, /*end*/ 0x10CD, WordBreakProperty.ALetter], - [/*start*/ 0x10D0, /*end*/ 0x10FA, WordBreakProperty.ALetter], - [/*start*/ 0x10FC, /*end*/ 0x10FC, WordBreakProperty.ALetter], - [/*start*/ 0x10FD, /*end*/ 0x10FF, WordBreakProperty.ALetter], - [/*start*/ 0x1100, /*end*/ 0x1248, WordBreakProperty.ALetter], - [/*start*/ 0x124A, /*end*/ 0x124D, WordBreakProperty.ALetter], - [/*start*/ 0x1250, /*end*/ 0x1256, WordBreakProperty.ALetter], - [/*start*/ 0x1258, /*end*/ 0x1258, WordBreakProperty.ALetter], - [/*start*/ 0x125A, /*end*/ 0x125D, WordBreakProperty.ALetter], - [/*start*/ 0x1260, /*end*/ 0x1288, WordBreakProperty.ALetter], - [/*start*/ 0x128A, /*end*/ 0x128D, WordBreakProperty.ALetter], - [/*start*/ 0x1290, /*end*/ 0x12B0, WordBreakProperty.ALetter], - [/*start*/ 0x12B2, /*end*/ 0x12B5, WordBreakProperty.ALetter], - [/*start*/ 0x12B8, /*end*/ 0x12BE, WordBreakProperty.ALetter], - [/*start*/ 0x12C0, /*end*/ 0x12C0, WordBreakProperty.ALetter], - [/*start*/ 0x12C2, /*end*/ 0x12C5, WordBreakProperty.ALetter], - [/*start*/ 0x12C8, /*end*/ 0x12D6, WordBreakProperty.ALetter], - [/*start*/ 0x12D8, /*end*/ 0x1310, WordBreakProperty.ALetter], - [/*start*/ 0x1312, /*end*/ 0x1315, WordBreakProperty.ALetter], - [/*start*/ 0x1318, /*end*/ 0x135A, WordBreakProperty.ALetter], - [/*start*/ 0x135D, /*end*/ 0x135F, WordBreakProperty.Extend], - [/*start*/ 0x1380, /*end*/ 0x138F, WordBreakProperty.ALetter], - [/*start*/ 0x13A0, /*end*/ 0x13F5, WordBreakProperty.ALetter], - [/*start*/ 0x13F8, /*end*/ 0x13FD, WordBreakProperty.ALetter], - [/*start*/ 0x1401, /*end*/ 0x166C, WordBreakProperty.ALetter], - [/*start*/ 0x166F, /*end*/ 0x167F, WordBreakProperty.ALetter], - [/*start*/ 0x1680, /*end*/ 0x1680, WordBreakProperty.WSegSpace], - [/*start*/ 0x1681, /*end*/ 0x169A, WordBreakProperty.ALetter], - [/*start*/ 0x16A0, /*end*/ 0x16EA, WordBreakProperty.ALetter], - [/*start*/ 0x16EE, /*end*/ 0x16F0, WordBreakProperty.ALetter], - [/*start*/ 0x16F1, /*end*/ 0x16F8, WordBreakProperty.ALetter], - [/*start*/ 0x1700, /*end*/ 0x170C, WordBreakProperty.ALetter], - [/*start*/ 0x170E, /*end*/ 0x1711, WordBreakProperty.ALetter], - [/*start*/ 0x1712, /*end*/ 0x1714, WordBreakProperty.Extend], - [/*start*/ 0x1720, /*end*/ 0x1731, WordBreakProperty.ALetter], - [/*start*/ 0x1732, /*end*/ 0x1734, WordBreakProperty.Extend], - [/*start*/ 0x1740, /*end*/ 0x1751, WordBreakProperty.ALetter], - [/*start*/ 0x1752, /*end*/ 0x1753, WordBreakProperty.Extend], - [/*start*/ 0x1760, /*end*/ 0x176C, WordBreakProperty.ALetter], - [/*start*/ 0x176E, /*end*/ 0x1770, WordBreakProperty.ALetter], - [/*start*/ 0x1772, /*end*/ 0x1773, WordBreakProperty.Extend], - [/*start*/ 0x17B4, /*end*/ 0x17B5, WordBreakProperty.Extend], - [/*start*/ 0x17B6, /*end*/ 0x17B6, WordBreakProperty.Extend], - [/*start*/ 0x17B7, /*end*/ 0x17BD, WordBreakProperty.Extend], - [/*start*/ 0x17BE, /*end*/ 0x17C5, WordBreakProperty.Extend], - [/*start*/ 0x17C6, /*end*/ 0x17C6, WordBreakProperty.Extend], - [/*start*/ 0x17C7, /*end*/ 0x17C8, WordBreakProperty.Extend], - [/*start*/ 0x17C9, /*end*/ 0x17D3, WordBreakProperty.Extend], - [/*start*/ 0x17DD, /*end*/ 0x17DD, WordBreakProperty.Extend], - [/*start*/ 0x17E0, /*end*/ 0x17E9, WordBreakProperty.Numeric], - [/*start*/ 0x180B, /*end*/ 0x180D, WordBreakProperty.Extend], - [/*start*/ 0x180E, /*end*/ 0x180E, WordBreakProperty.Format], - [/*start*/ 0x1810, /*end*/ 0x1819, WordBreakProperty.Numeric], - [/*start*/ 0x1820, /*end*/ 0x1842, WordBreakProperty.ALetter], - [/*start*/ 0x1843, /*end*/ 0x1843, WordBreakProperty.ALetter], - [/*start*/ 0x1844, /*end*/ 0x1878, WordBreakProperty.ALetter], - [/*start*/ 0x1880, /*end*/ 0x1884, WordBreakProperty.ALetter], - [/*start*/ 0x1885, /*end*/ 0x1886, WordBreakProperty.Extend], - [/*start*/ 0x1887, /*end*/ 0x18A8, WordBreakProperty.ALetter], - [/*start*/ 0x18A9, /*end*/ 0x18A9, WordBreakProperty.Extend], - [/*start*/ 0x18AA, /*end*/ 0x18AA, WordBreakProperty.ALetter], - [/*start*/ 0x18B0, /*end*/ 0x18F5, WordBreakProperty.ALetter], - [/*start*/ 0x1900, /*end*/ 0x191E, WordBreakProperty.ALetter], - [/*start*/ 0x1920, /*end*/ 0x1922, WordBreakProperty.Extend], - [/*start*/ 0x1923, /*end*/ 0x1926, WordBreakProperty.Extend], - [/*start*/ 0x1927, /*end*/ 0x1928, WordBreakProperty.Extend], - [/*start*/ 0x1929, /*end*/ 0x192B, WordBreakProperty.Extend], - [/*start*/ 0x1930, /*end*/ 0x1931, WordBreakProperty.Extend], - [/*start*/ 0x1932, /*end*/ 0x1932, WordBreakProperty.Extend], - [/*start*/ 0x1933, /*end*/ 0x1938, WordBreakProperty.Extend], - [/*start*/ 0x1939, /*end*/ 0x193B, WordBreakProperty.Extend], - [/*start*/ 0x1946, /*end*/ 0x194F, WordBreakProperty.Numeric], - [/*start*/ 0x19D0, /*end*/ 0x19D9, WordBreakProperty.Numeric], - [/*start*/ 0x1A00, /*end*/ 0x1A16, WordBreakProperty.ALetter], - [/*start*/ 0x1A17, /*end*/ 0x1A18, WordBreakProperty.Extend], - [/*start*/ 0x1A19, /*end*/ 0x1A1A, WordBreakProperty.Extend], - [/*start*/ 0x1A1B, /*end*/ 0x1A1B, WordBreakProperty.Extend], - [/*start*/ 0x1A55, /*end*/ 0x1A55, WordBreakProperty.Extend], - [/*start*/ 0x1A56, /*end*/ 0x1A56, WordBreakProperty.Extend], - [/*start*/ 0x1A57, /*end*/ 0x1A57, WordBreakProperty.Extend], - [/*start*/ 0x1A58, /*end*/ 0x1A5E, WordBreakProperty.Extend], - [/*start*/ 0x1A60, /*end*/ 0x1A60, WordBreakProperty.Extend], - [/*start*/ 0x1A61, /*end*/ 0x1A61, WordBreakProperty.Extend], - [/*start*/ 0x1A62, /*end*/ 0x1A62, WordBreakProperty.Extend], - [/*start*/ 0x1A63, /*end*/ 0x1A64, WordBreakProperty.Extend], - [/*start*/ 0x1A65, /*end*/ 0x1A6C, WordBreakProperty.Extend], - [/*start*/ 0x1A6D, /*end*/ 0x1A72, WordBreakProperty.Extend], - [/*start*/ 0x1A73, /*end*/ 0x1A7C, WordBreakProperty.Extend], - [/*start*/ 0x1A7F, /*end*/ 0x1A7F, WordBreakProperty.Extend], - [/*start*/ 0x1A80, /*end*/ 0x1A89, WordBreakProperty.Numeric], - [/*start*/ 0x1A90, /*end*/ 0x1A99, WordBreakProperty.Numeric], - [/*start*/ 0x1AB0, /*end*/ 0x1ABD, WordBreakProperty.Extend], - [/*start*/ 0x1ABE, /*end*/ 0x1ABE, WordBreakProperty.Extend], - [/*start*/ 0x1B00, /*end*/ 0x1B03, WordBreakProperty.Extend], - [/*start*/ 0x1B04, /*end*/ 0x1B04, WordBreakProperty.Extend], - [/*start*/ 0x1B05, /*end*/ 0x1B33, WordBreakProperty.ALetter], - [/*start*/ 0x1B34, /*end*/ 0x1B34, WordBreakProperty.Extend], - [/*start*/ 0x1B35, /*end*/ 0x1B35, WordBreakProperty.Extend], - [/*start*/ 0x1B36, /*end*/ 0x1B3A, WordBreakProperty.Extend], - [/*start*/ 0x1B3B, /*end*/ 0x1B3B, WordBreakProperty.Extend], - [/*start*/ 0x1B3C, /*end*/ 0x1B3C, WordBreakProperty.Extend], - [/*start*/ 0x1B3D, /*end*/ 0x1B41, WordBreakProperty.Extend], - [/*start*/ 0x1B42, /*end*/ 0x1B42, WordBreakProperty.Extend], - [/*start*/ 0x1B43, /*end*/ 0x1B44, WordBreakProperty.Extend], - [/*start*/ 0x1B45, /*end*/ 0x1B4B, WordBreakProperty.ALetter], - [/*start*/ 0x1B50, /*end*/ 0x1B59, WordBreakProperty.Numeric], - [/*start*/ 0x1B6B, /*end*/ 0x1B73, WordBreakProperty.Extend], - [/*start*/ 0x1B80, /*end*/ 0x1B81, WordBreakProperty.Extend], - [/*start*/ 0x1B82, /*end*/ 0x1B82, WordBreakProperty.Extend], - [/*start*/ 0x1B83, /*end*/ 0x1BA0, WordBreakProperty.ALetter], - [/*start*/ 0x1BA1, /*end*/ 0x1BA1, WordBreakProperty.Extend], - [/*start*/ 0x1BA2, /*end*/ 0x1BA5, WordBreakProperty.Extend], - [/*start*/ 0x1BA6, /*end*/ 0x1BA7, WordBreakProperty.Extend], - [/*start*/ 0x1BA8, /*end*/ 0x1BA9, WordBreakProperty.Extend], - [/*start*/ 0x1BAA, /*end*/ 0x1BAA, WordBreakProperty.Extend], - [/*start*/ 0x1BAB, /*end*/ 0x1BAD, WordBreakProperty.Extend], - [/*start*/ 0x1BAE, /*end*/ 0x1BAF, WordBreakProperty.ALetter], - [/*start*/ 0x1BB0, /*end*/ 0x1BB9, WordBreakProperty.Numeric], - [/*start*/ 0x1BBA, /*end*/ 0x1BE5, WordBreakProperty.ALetter], - [/*start*/ 0x1BE6, /*end*/ 0x1BE6, WordBreakProperty.Extend], - [/*start*/ 0x1BE7, /*end*/ 0x1BE7, WordBreakProperty.Extend], - [/*start*/ 0x1BE8, /*end*/ 0x1BE9, WordBreakProperty.Extend], - [/*start*/ 0x1BEA, /*end*/ 0x1BEC, WordBreakProperty.Extend], - [/*start*/ 0x1BED, /*end*/ 0x1BED, WordBreakProperty.Extend], - [/*start*/ 0x1BEE, /*end*/ 0x1BEE, WordBreakProperty.Extend], - [/*start*/ 0x1BEF, /*end*/ 0x1BF1, WordBreakProperty.Extend], - [/*start*/ 0x1BF2, /*end*/ 0x1BF3, WordBreakProperty.Extend], - [/*start*/ 0x1C00, /*end*/ 0x1C23, WordBreakProperty.ALetter], - [/*start*/ 0x1C24, /*end*/ 0x1C2B, WordBreakProperty.Extend], - [/*start*/ 0x1C2C, /*end*/ 0x1C33, WordBreakProperty.Extend], - [/*start*/ 0x1C34, /*end*/ 0x1C35, WordBreakProperty.Extend], - [/*start*/ 0x1C36, /*end*/ 0x1C37, WordBreakProperty.Extend], - [/*start*/ 0x1C40, /*end*/ 0x1C49, WordBreakProperty.Numeric], - [/*start*/ 0x1C4D, /*end*/ 0x1C4F, WordBreakProperty.ALetter], - [/*start*/ 0x1C50, /*end*/ 0x1C59, WordBreakProperty.Numeric], - [/*start*/ 0x1C5A, /*end*/ 0x1C77, WordBreakProperty.ALetter], - [/*start*/ 0x1C78, /*end*/ 0x1C7D, WordBreakProperty.ALetter], - [/*start*/ 0x1C80, /*end*/ 0x1C88, WordBreakProperty.ALetter], - [/*start*/ 0x1C90, /*end*/ 0x1CBA, WordBreakProperty.ALetter], - [/*start*/ 0x1CBD, /*end*/ 0x1CBF, WordBreakProperty.ALetter], - [/*start*/ 0x1CD0, /*end*/ 0x1CD2, WordBreakProperty.Extend], - [/*start*/ 0x1CD4, /*end*/ 0x1CE0, WordBreakProperty.Extend], - [/*start*/ 0x1CE1, /*end*/ 0x1CE1, WordBreakProperty.Extend], - [/*start*/ 0x1CE2, /*end*/ 0x1CE8, WordBreakProperty.Extend], - [/*start*/ 0x1CE9, /*end*/ 0x1CEC, WordBreakProperty.ALetter], - [/*start*/ 0x1CED, /*end*/ 0x1CED, WordBreakProperty.Extend], - [/*start*/ 0x1CEE, /*end*/ 0x1CF3, WordBreakProperty.ALetter], - [/*start*/ 0x1CF4, /*end*/ 0x1CF4, WordBreakProperty.Extend], - [/*start*/ 0x1CF5, /*end*/ 0x1CF6, WordBreakProperty.ALetter], - [/*start*/ 0x1CF7, /*end*/ 0x1CF7, WordBreakProperty.Extend], - [/*start*/ 0x1CF8, /*end*/ 0x1CF9, WordBreakProperty.Extend], - [/*start*/ 0x1CFA, /*end*/ 0x1CFA, WordBreakProperty.ALetter], - [/*start*/ 0x1D00, /*end*/ 0x1D2B, WordBreakProperty.ALetter], - [/*start*/ 0x1D2C, /*end*/ 0x1D6A, WordBreakProperty.ALetter], - [/*start*/ 0x1D6B, /*end*/ 0x1D77, WordBreakProperty.ALetter], - [/*start*/ 0x1D78, /*end*/ 0x1D78, WordBreakProperty.ALetter], - [/*start*/ 0x1D79, /*end*/ 0x1D9A, WordBreakProperty.ALetter], - [/*start*/ 0x1D9B, /*end*/ 0x1DBF, WordBreakProperty.ALetter], - [/*start*/ 0x1DC0, /*end*/ 0x1DF9, WordBreakProperty.Extend], - [/*start*/ 0x1DFB, /*end*/ 0x1DFF, WordBreakProperty.Extend], - [/*start*/ 0x1E00, /*end*/ 0x1F15, WordBreakProperty.ALetter], - [/*start*/ 0x1F18, /*end*/ 0x1F1D, WordBreakProperty.ALetter], - [/*start*/ 0x1F20, /*end*/ 0x1F45, WordBreakProperty.ALetter], - [/*start*/ 0x1F48, /*end*/ 0x1F4D, WordBreakProperty.ALetter], - [/*start*/ 0x1F50, /*end*/ 0x1F57, WordBreakProperty.ALetter], - [/*start*/ 0x1F59, /*end*/ 0x1F59, WordBreakProperty.ALetter], - [/*start*/ 0x1F5B, /*end*/ 0x1F5B, WordBreakProperty.ALetter], - [/*start*/ 0x1F5D, /*end*/ 0x1F5D, WordBreakProperty.ALetter], - [/*start*/ 0x1F5F, /*end*/ 0x1F7D, WordBreakProperty.ALetter], - [/*start*/ 0x1F80, /*end*/ 0x1FB4, WordBreakProperty.ALetter], - [/*start*/ 0x1FB6, /*end*/ 0x1FBC, WordBreakProperty.ALetter], - [/*start*/ 0x1FBE, /*end*/ 0x1FBE, WordBreakProperty.ALetter], - [/*start*/ 0x1FC2, /*end*/ 0x1FC4, WordBreakProperty.ALetter], - [/*start*/ 0x1FC6, /*end*/ 0x1FCC, WordBreakProperty.ALetter], - [/*start*/ 0x1FD0, /*end*/ 0x1FD3, WordBreakProperty.ALetter], - [/*start*/ 0x1FD6, /*end*/ 0x1FDB, WordBreakProperty.ALetter], - [/*start*/ 0x1FE0, /*end*/ 0x1FEC, WordBreakProperty.ALetter], - [/*start*/ 0x1FF2, /*end*/ 0x1FF4, WordBreakProperty.ALetter], - [/*start*/ 0x1FF6, /*end*/ 0x1FFC, WordBreakProperty.ALetter], - [/*start*/ 0x2000, /*end*/ 0x2006, WordBreakProperty.WSegSpace], - [/*start*/ 0x2008, /*end*/ 0x200A, WordBreakProperty.WSegSpace], - [/*start*/ 0x200C, /*end*/ 0x200C, WordBreakProperty.Extend], - [/*start*/ 0x200D, /*end*/ 0x200D, WordBreakProperty.ZWJ], - [/*start*/ 0x200E, /*end*/ 0x200F, WordBreakProperty.Format], - [/*start*/ 0x2018, /*end*/ 0x2018, WordBreakProperty.MidNumLet], - [/*start*/ 0x2019, /*end*/ 0x2019, WordBreakProperty.MidNumLet], - [/*start*/ 0x2024, /*end*/ 0x2024, WordBreakProperty.MidNumLet], - [/*start*/ 0x2027, /*end*/ 0x2027, WordBreakProperty.MidLetter], - [/*start*/ 0x2028, /*end*/ 0x2028, WordBreakProperty.Newline], - [/*start*/ 0x2029, /*end*/ 0x2029, WordBreakProperty.Newline], - [/*start*/ 0x202A, /*end*/ 0x202E, WordBreakProperty.Format], - [/*start*/ 0x202F, /*end*/ 0x202F, WordBreakProperty.ExtendNumLet], - [/*start*/ 0x203F, /*end*/ 0x2040, WordBreakProperty.ExtendNumLet], - [/*start*/ 0x2044, /*end*/ 0x2044, WordBreakProperty.MidNum], - [/*start*/ 0x2054, /*end*/ 0x2054, WordBreakProperty.ExtendNumLet], - [/*start*/ 0x205F, /*end*/ 0x205F, WordBreakProperty.WSegSpace], - [/*start*/ 0x2060, /*end*/ 0x2064, WordBreakProperty.Format], - [/*start*/ 0x2066, /*end*/ 0x206F, WordBreakProperty.Format], - [/*start*/ 0x2071, /*end*/ 0x2071, WordBreakProperty.ALetter], - [/*start*/ 0x207F, /*end*/ 0x207F, WordBreakProperty.ALetter], - [/*start*/ 0x2090, /*end*/ 0x209C, WordBreakProperty.ALetter], - [/*start*/ 0x20D0, /*end*/ 0x20DC, WordBreakProperty.Extend], - [/*start*/ 0x20DD, /*end*/ 0x20E0, WordBreakProperty.Extend], - [/*start*/ 0x20E1, /*end*/ 0x20E1, WordBreakProperty.Extend], - [/*start*/ 0x20E2, /*end*/ 0x20E4, WordBreakProperty.Extend], - [/*start*/ 0x20E5, /*end*/ 0x20F0, WordBreakProperty.Extend], - [/*start*/ 0x2102, /*end*/ 0x2102, WordBreakProperty.ALetter], - [/*start*/ 0x2107, /*end*/ 0x2107, WordBreakProperty.ALetter], - [/*start*/ 0x210A, /*end*/ 0x2113, WordBreakProperty.ALetter], - [/*start*/ 0x2115, /*end*/ 0x2115, WordBreakProperty.ALetter], - [/*start*/ 0x2119, /*end*/ 0x211D, WordBreakProperty.ALetter], - [/*start*/ 0x2124, /*end*/ 0x2124, WordBreakProperty.ALetter], - [/*start*/ 0x2126, /*end*/ 0x2126, WordBreakProperty.ALetter], - [/*start*/ 0x2128, /*end*/ 0x2128, WordBreakProperty.ALetter], - [/*start*/ 0x212A, /*end*/ 0x212D, WordBreakProperty.ALetter], - [/*start*/ 0x212F, /*end*/ 0x2134, WordBreakProperty.ALetter], - [/*start*/ 0x2135, /*end*/ 0x2138, WordBreakProperty.ALetter], - [/*start*/ 0x2139, /*end*/ 0x2139, WordBreakProperty.ALetter], - [/*start*/ 0x213C, /*end*/ 0x213F, WordBreakProperty.ALetter], - [/*start*/ 0x2145, /*end*/ 0x2149, WordBreakProperty.ALetter], - [/*start*/ 0x214E, /*end*/ 0x214E, WordBreakProperty.ALetter], - [/*start*/ 0x2160, /*end*/ 0x2182, WordBreakProperty.ALetter], - [/*start*/ 0x2183, /*end*/ 0x2184, WordBreakProperty.ALetter], - [/*start*/ 0x2185, /*end*/ 0x2188, WordBreakProperty.ALetter], - [/*start*/ 0x24B6, /*end*/ 0x24E9, WordBreakProperty.ALetter], - [/*start*/ 0x2C00, /*end*/ 0x2C2E, WordBreakProperty.ALetter], - [/*start*/ 0x2C30, /*end*/ 0x2C5E, WordBreakProperty.ALetter], - [/*start*/ 0x2C60, /*end*/ 0x2C7B, WordBreakProperty.ALetter], - [/*start*/ 0x2C7C, /*end*/ 0x2C7D, WordBreakProperty.ALetter], - [/*start*/ 0x2C7E, /*end*/ 0x2CE4, WordBreakProperty.ALetter], - [/*start*/ 0x2CEB, /*end*/ 0x2CEE, WordBreakProperty.ALetter], - [/*start*/ 0x2CEF, /*end*/ 0x2CF1, WordBreakProperty.Extend], - [/*start*/ 0x2CF2, /*end*/ 0x2CF3, WordBreakProperty.ALetter], - [/*start*/ 0x2D00, /*end*/ 0x2D25, WordBreakProperty.ALetter], - [/*start*/ 0x2D27, /*end*/ 0x2D27, WordBreakProperty.ALetter], - [/*start*/ 0x2D2D, /*end*/ 0x2D2D, WordBreakProperty.ALetter], - [/*start*/ 0x2D30, /*end*/ 0x2D67, WordBreakProperty.ALetter], - [/*start*/ 0x2D6F, /*end*/ 0x2D6F, WordBreakProperty.ALetter], - [/*start*/ 0x2D7F, /*end*/ 0x2D7F, WordBreakProperty.Extend], - [/*start*/ 0x2D80, /*end*/ 0x2D96, WordBreakProperty.ALetter], - [/*start*/ 0x2DA0, /*end*/ 0x2DA6, WordBreakProperty.ALetter], - [/*start*/ 0x2DA8, /*end*/ 0x2DAE, WordBreakProperty.ALetter], - [/*start*/ 0x2DB0, /*end*/ 0x2DB6, WordBreakProperty.ALetter], - [/*start*/ 0x2DB8, /*end*/ 0x2DBE, WordBreakProperty.ALetter], - [/*start*/ 0x2DC0, /*end*/ 0x2DC6, WordBreakProperty.ALetter], - [/*start*/ 0x2DC8, /*end*/ 0x2DCE, WordBreakProperty.ALetter], - [/*start*/ 0x2DD0, /*end*/ 0x2DD6, WordBreakProperty.ALetter], - [/*start*/ 0x2DD8, /*end*/ 0x2DDE, WordBreakProperty.ALetter], - [/*start*/ 0x2DE0, /*end*/ 0x2DFF, WordBreakProperty.Extend], - [/*start*/ 0x2E2F, /*end*/ 0x2E2F, WordBreakProperty.ALetter], - [/*start*/ 0x3000, /*end*/ 0x3000, WordBreakProperty.WSegSpace], - [/*start*/ 0x3005, /*end*/ 0x3005, WordBreakProperty.ALetter], - [/*start*/ 0x302A, /*end*/ 0x302D, WordBreakProperty.Extend], - [/*start*/ 0x302E, /*end*/ 0x302F, WordBreakProperty.Extend], - [/*start*/ 0x3031, /*end*/ 0x3035, WordBreakProperty.Katakana], - [/*start*/ 0x303B, /*end*/ 0x303B, WordBreakProperty.ALetter], - [/*start*/ 0x303C, /*end*/ 0x303C, WordBreakProperty.ALetter], - [/*start*/ 0x3099, /*end*/ 0x309A, WordBreakProperty.Extend], - [/*start*/ 0x309B, /*end*/ 0x309C, WordBreakProperty.Katakana], - [/*start*/ 0x30A0, /*end*/ 0x30A0, WordBreakProperty.Katakana], - [/*start*/ 0x30A1, /*end*/ 0x30FA, WordBreakProperty.Katakana], - [/*start*/ 0x30FC, /*end*/ 0x30FE, WordBreakProperty.Katakana], - [/*start*/ 0x30FF, /*end*/ 0x30FF, WordBreakProperty.Katakana], - [/*start*/ 0x3105, /*end*/ 0x312F, WordBreakProperty.ALetter], - [/*start*/ 0x3131, /*end*/ 0x318E, WordBreakProperty.ALetter], - [/*start*/ 0x31A0, /*end*/ 0x31BA, WordBreakProperty.ALetter], - [/*start*/ 0x31F0, /*end*/ 0x31FF, WordBreakProperty.Katakana], - [/*start*/ 0x32D0, /*end*/ 0x32FE, WordBreakProperty.Katakana], - [/*start*/ 0x3300, /*end*/ 0x3357, WordBreakProperty.Katakana], - [/*start*/ 0xA000, /*end*/ 0xA014, WordBreakProperty.ALetter], - [/*start*/ 0xA015, /*end*/ 0xA015, WordBreakProperty.ALetter], - [/*start*/ 0xA016, /*end*/ 0xA48C, WordBreakProperty.ALetter], - [/*start*/ 0xA4D0, /*end*/ 0xA4F7, WordBreakProperty.ALetter], - [/*start*/ 0xA4F8, /*end*/ 0xA4FD, WordBreakProperty.ALetter], - [/*start*/ 0xA500, /*end*/ 0xA60B, WordBreakProperty.ALetter], - [/*start*/ 0xA60C, /*end*/ 0xA60C, WordBreakProperty.ALetter], - [/*start*/ 0xA610, /*end*/ 0xA61F, WordBreakProperty.ALetter], - [/*start*/ 0xA620, /*end*/ 0xA629, WordBreakProperty.Numeric], - [/*start*/ 0xA62A, /*end*/ 0xA62B, WordBreakProperty.ALetter], - [/*start*/ 0xA640, /*end*/ 0xA66D, WordBreakProperty.ALetter], - [/*start*/ 0xA66E, /*end*/ 0xA66E, WordBreakProperty.ALetter], - [/*start*/ 0xA66F, /*end*/ 0xA66F, WordBreakProperty.Extend], - [/*start*/ 0xA670, /*end*/ 0xA672, WordBreakProperty.Extend], - [/*start*/ 0xA674, /*end*/ 0xA67D, WordBreakProperty.Extend], - [/*start*/ 0xA67F, /*end*/ 0xA67F, WordBreakProperty.ALetter], - [/*start*/ 0xA680, /*end*/ 0xA69B, WordBreakProperty.ALetter], - [/*start*/ 0xA69C, /*end*/ 0xA69D, WordBreakProperty.ALetter], - [/*start*/ 0xA69E, /*end*/ 0xA69F, WordBreakProperty.Extend], - [/*start*/ 0xA6A0, /*end*/ 0xA6E5, WordBreakProperty.ALetter], - [/*start*/ 0xA6E6, /*end*/ 0xA6EF, WordBreakProperty.ALetter], - [/*start*/ 0xA6F0, /*end*/ 0xA6F1, WordBreakProperty.Extend], - [/*start*/ 0xA717, /*end*/ 0xA71F, WordBreakProperty.ALetter], - [/*start*/ 0xA720, /*end*/ 0xA721, WordBreakProperty.ALetter], - [/*start*/ 0xA722, /*end*/ 0xA76F, WordBreakProperty.ALetter], - [/*start*/ 0xA770, /*end*/ 0xA770, WordBreakProperty.ALetter], - [/*start*/ 0xA771, /*end*/ 0xA787, WordBreakProperty.ALetter], - [/*start*/ 0xA788, /*end*/ 0xA788, WordBreakProperty.ALetter], - [/*start*/ 0xA789, /*end*/ 0xA78A, WordBreakProperty.ALetter], - [/*start*/ 0xA78B, /*end*/ 0xA78E, WordBreakProperty.ALetter], - [/*start*/ 0xA78F, /*end*/ 0xA78F, WordBreakProperty.ALetter], - [/*start*/ 0xA790, /*end*/ 0xA7BF, WordBreakProperty.ALetter], - [/*start*/ 0xA7C2, /*end*/ 0xA7C6, WordBreakProperty.ALetter], - [/*start*/ 0xA7F7, /*end*/ 0xA7F7, WordBreakProperty.ALetter], - [/*start*/ 0xA7F8, /*end*/ 0xA7F9, WordBreakProperty.ALetter], - [/*start*/ 0xA7FA, /*end*/ 0xA7FA, WordBreakProperty.ALetter], - [/*start*/ 0xA7FB, /*end*/ 0xA801, WordBreakProperty.ALetter], - [/*start*/ 0xA802, /*end*/ 0xA802, WordBreakProperty.Extend], - [/*start*/ 0xA803, /*end*/ 0xA805, WordBreakProperty.ALetter], - [/*start*/ 0xA806, /*end*/ 0xA806, WordBreakProperty.Extend], - [/*start*/ 0xA807, /*end*/ 0xA80A, WordBreakProperty.ALetter], - [/*start*/ 0xA80B, /*end*/ 0xA80B, WordBreakProperty.Extend], - [/*start*/ 0xA80C, /*end*/ 0xA822, WordBreakProperty.ALetter], - [/*start*/ 0xA823, /*end*/ 0xA824, WordBreakProperty.Extend], - [/*start*/ 0xA825, /*end*/ 0xA826, WordBreakProperty.Extend], - [/*start*/ 0xA827, /*end*/ 0xA827, WordBreakProperty.Extend], - [/*start*/ 0xA840, /*end*/ 0xA873, WordBreakProperty.ALetter], - [/*start*/ 0xA880, /*end*/ 0xA881, WordBreakProperty.Extend], - [/*start*/ 0xA882, /*end*/ 0xA8B3, WordBreakProperty.ALetter], - [/*start*/ 0xA8B4, /*end*/ 0xA8C3, WordBreakProperty.Extend], - [/*start*/ 0xA8C4, /*end*/ 0xA8C5, WordBreakProperty.Extend], - [/*start*/ 0xA8D0, /*end*/ 0xA8D9, WordBreakProperty.Numeric], - [/*start*/ 0xA8E0, /*end*/ 0xA8F1, WordBreakProperty.Extend], - [/*start*/ 0xA8F2, /*end*/ 0xA8F7, WordBreakProperty.ALetter], - [/*start*/ 0xA8FB, /*end*/ 0xA8FB, WordBreakProperty.ALetter], - [/*start*/ 0xA8FD, /*end*/ 0xA8FE, WordBreakProperty.ALetter], - [/*start*/ 0xA8FF, /*end*/ 0xA8FF, WordBreakProperty.Extend], - [/*start*/ 0xA900, /*end*/ 0xA909, WordBreakProperty.Numeric], - [/*start*/ 0xA90A, /*end*/ 0xA925, WordBreakProperty.ALetter], - [/*start*/ 0xA926, /*end*/ 0xA92D, WordBreakProperty.Extend], - [/*start*/ 0xA930, /*end*/ 0xA946, WordBreakProperty.ALetter], - [/*start*/ 0xA947, /*end*/ 0xA951, WordBreakProperty.Extend], - [/*start*/ 0xA952, /*end*/ 0xA953, WordBreakProperty.Extend], - [/*start*/ 0xA960, /*end*/ 0xA97C, WordBreakProperty.ALetter], - [/*start*/ 0xA980, /*end*/ 0xA982, WordBreakProperty.Extend], - [/*start*/ 0xA983, /*end*/ 0xA983, WordBreakProperty.Extend], - [/*start*/ 0xA984, /*end*/ 0xA9B2, WordBreakProperty.ALetter], - [/*start*/ 0xA9B3, /*end*/ 0xA9B3, WordBreakProperty.Extend], - [/*start*/ 0xA9B4, /*end*/ 0xA9B5, WordBreakProperty.Extend], - [/*start*/ 0xA9B6, /*end*/ 0xA9B9, WordBreakProperty.Extend], - [/*start*/ 0xA9BA, /*end*/ 0xA9BB, WordBreakProperty.Extend], - [/*start*/ 0xA9BC, /*end*/ 0xA9BD, WordBreakProperty.Extend], - [/*start*/ 0xA9BE, /*end*/ 0xA9C0, WordBreakProperty.Extend], - [/*start*/ 0xA9CF, /*end*/ 0xA9CF, WordBreakProperty.ALetter], - [/*start*/ 0xA9D0, /*end*/ 0xA9D9, WordBreakProperty.Numeric], - [/*start*/ 0xA9E5, /*end*/ 0xA9E5, WordBreakProperty.Extend], - [/*start*/ 0xA9F0, /*end*/ 0xA9F9, WordBreakProperty.Numeric], - [/*start*/ 0xAA00, /*end*/ 0xAA28, WordBreakProperty.ALetter], - [/*start*/ 0xAA29, /*end*/ 0xAA2E, WordBreakProperty.Extend], - [/*start*/ 0xAA2F, /*end*/ 0xAA30, WordBreakProperty.Extend], - [/*start*/ 0xAA31, /*end*/ 0xAA32, WordBreakProperty.Extend], - [/*start*/ 0xAA33, /*end*/ 0xAA34, WordBreakProperty.Extend], - [/*start*/ 0xAA35, /*end*/ 0xAA36, WordBreakProperty.Extend], - [/*start*/ 0xAA40, /*end*/ 0xAA42, WordBreakProperty.ALetter], - [/*start*/ 0xAA43, /*end*/ 0xAA43, WordBreakProperty.Extend], - [/*start*/ 0xAA44, /*end*/ 0xAA4B, WordBreakProperty.ALetter], - [/*start*/ 0xAA4C, /*end*/ 0xAA4C, WordBreakProperty.Extend], - [/*start*/ 0xAA4D, /*end*/ 0xAA4D, WordBreakProperty.Extend], - [/*start*/ 0xAA50, /*end*/ 0xAA59, WordBreakProperty.Numeric], - [/*start*/ 0xAA7B, /*end*/ 0xAA7B, WordBreakProperty.Extend], - [/*start*/ 0xAA7C, /*end*/ 0xAA7C, WordBreakProperty.Extend], - [/*start*/ 0xAA7D, /*end*/ 0xAA7D, WordBreakProperty.Extend], - [/*start*/ 0xAAB0, /*end*/ 0xAAB0, WordBreakProperty.Extend], - [/*start*/ 0xAAB2, /*end*/ 0xAAB4, WordBreakProperty.Extend], - [/*start*/ 0xAAB7, /*end*/ 0xAAB8, WordBreakProperty.Extend], - [/*start*/ 0xAABE, /*end*/ 0xAABF, WordBreakProperty.Extend], - [/*start*/ 0xAAC1, /*end*/ 0xAAC1, WordBreakProperty.Extend], - [/*start*/ 0xAAE0, /*end*/ 0xAAEA, WordBreakProperty.ALetter], - [/*start*/ 0xAAEB, /*end*/ 0xAAEB, WordBreakProperty.Extend], - [/*start*/ 0xAAEC, /*end*/ 0xAAED, WordBreakProperty.Extend], - [/*start*/ 0xAAEE, /*end*/ 0xAAEF, WordBreakProperty.Extend], - [/*start*/ 0xAAF2, /*end*/ 0xAAF2, WordBreakProperty.ALetter], - [/*start*/ 0xAAF3, /*end*/ 0xAAF4, WordBreakProperty.ALetter], - [/*start*/ 0xAAF5, /*end*/ 0xAAF5, WordBreakProperty.Extend], - [/*start*/ 0xAAF6, /*end*/ 0xAAF6, WordBreakProperty.Extend], - [/*start*/ 0xAB01, /*end*/ 0xAB06, WordBreakProperty.ALetter], - [/*start*/ 0xAB09, /*end*/ 0xAB0E, WordBreakProperty.ALetter], - [/*start*/ 0xAB11, /*end*/ 0xAB16, WordBreakProperty.ALetter], - [/*start*/ 0xAB20, /*end*/ 0xAB26, WordBreakProperty.ALetter], - [/*start*/ 0xAB28, /*end*/ 0xAB2E, WordBreakProperty.ALetter], - [/*start*/ 0xAB30, /*end*/ 0xAB5A, WordBreakProperty.ALetter], - [/*start*/ 0xAB5B, /*end*/ 0xAB5B, WordBreakProperty.ALetter], - [/*start*/ 0xAB5C, /*end*/ 0xAB5F, WordBreakProperty.ALetter], - [/*start*/ 0xAB60, /*end*/ 0xAB67, WordBreakProperty.ALetter], - [/*start*/ 0xAB70, /*end*/ 0xABBF, WordBreakProperty.ALetter], - [/*start*/ 0xABC0, /*end*/ 0xABE2, WordBreakProperty.ALetter], - [/*start*/ 0xABE3, /*end*/ 0xABE4, WordBreakProperty.Extend], - [/*start*/ 0xABE5, /*end*/ 0xABE5, WordBreakProperty.Extend], - [/*start*/ 0xABE6, /*end*/ 0xABE7, WordBreakProperty.Extend], - [/*start*/ 0xABE8, /*end*/ 0xABE8, WordBreakProperty.Extend], - [/*start*/ 0xABE9, /*end*/ 0xABEA, WordBreakProperty.Extend], - [/*start*/ 0xABEC, /*end*/ 0xABEC, WordBreakProperty.Extend], - [/*start*/ 0xABED, /*end*/ 0xABED, WordBreakProperty.Extend], - [/*start*/ 0xABF0, /*end*/ 0xABF9, WordBreakProperty.Numeric], - [/*start*/ 0xAC00, /*end*/ 0xD7A3, WordBreakProperty.ALetter], - [/*start*/ 0xD7B0, /*end*/ 0xD7C6, WordBreakProperty.ALetter], - [/*start*/ 0xD7CB, /*end*/ 0xD7FB, WordBreakProperty.ALetter], - [/*start*/ 0xFB00, /*end*/ 0xFB06, WordBreakProperty.ALetter], - [/*start*/ 0xFB13, /*end*/ 0xFB17, WordBreakProperty.ALetter], - [/*start*/ 0xFB1D, /*end*/ 0xFB1D, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0xFB1E, /*end*/ 0xFB1E, WordBreakProperty.Extend], - [/*start*/ 0xFB1F, /*end*/ 0xFB28, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0xFB2A, /*end*/ 0xFB36, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0xFB38, /*end*/ 0xFB3C, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0xFB3E, /*end*/ 0xFB3E, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0xFB40, /*end*/ 0xFB41, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0xFB43, /*end*/ 0xFB44, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0xFB46, /*end*/ 0xFB4F, WordBreakProperty.Hebrew_Letter], - [/*start*/ 0xFB50, /*end*/ 0xFBB1, WordBreakProperty.ALetter], - [/*start*/ 0xFBD3, /*end*/ 0xFD3D, WordBreakProperty.ALetter], - [/*start*/ 0xFD50, /*end*/ 0xFD8F, WordBreakProperty.ALetter], - [/*start*/ 0xFD92, /*end*/ 0xFDC7, WordBreakProperty.ALetter], - [/*start*/ 0xFDF0, /*end*/ 0xFDFB, WordBreakProperty.ALetter], - [/*start*/ 0xFE00, /*end*/ 0xFE0F, WordBreakProperty.Extend], - [/*start*/ 0xFE10, /*end*/ 0xFE10, WordBreakProperty.MidNum], - [/*start*/ 0xFE13, /*end*/ 0xFE13, WordBreakProperty.MidLetter], - [/*start*/ 0xFE14, /*end*/ 0xFE14, WordBreakProperty.MidNum], - [/*start*/ 0xFE20, /*end*/ 0xFE2F, WordBreakProperty.Extend], - [/*start*/ 0xFE33, /*end*/ 0xFE34, WordBreakProperty.ExtendNumLet], - [/*start*/ 0xFE4D, /*end*/ 0xFE4F, WordBreakProperty.ExtendNumLet], - [/*start*/ 0xFE50, /*end*/ 0xFE50, WordBreakProperty.MidNum], - [/*start*/ 0xFE52, /*end*/ 0xFE52, WordBreakProperty.MidNumLet], - [/*start*/ 0xFE54, /*end*/ 0xFE54, WordBreakProperty.MidNum], - [/*start*/ 0xFE55, /*end*/ 0xFE55, WordBreakProperty.MidLetter], - [/*start*/ 0xFE70, /*end*/ 0xFE74, WordBreakProperty.ALetter], - [/*start*/ 0xFE76, /*end*/ 0xFEFC, WordBreakProperty.ALetter], - [/*start*/ 0xFEFF, /*end*/ 0xFEFF, WordBreakProperty.Format], - [/*start*/ 0xFF07, /*end*/ 0xFF07, WordBreakProperty.MidNumLet], - [/*start*/ 0xFF0C, /*end*/ 0xFF0C, WordBreakProperty.MidNum], - [/*start*/ 0xFF0E, /*end*/ 0xFF0E, WordBreakProperty.MidNumLet], - [/*start*/ 0xFF10, /*end*/ 0xFF19, WordBreakProperty.Numeric], - [/*start*/ 0xFF1A, /*end*/ 0xFF1A, WordBreakProperty.MidLetter], - [/*start*/ 0xFF1B, /*end*/ 0xFF1B, WordBreakProperty.MidNum], - [/*start*/ 0xFF21, /*end*/ 0xFF3A, WordBreakProperty.ALetter], - [/*start*/ 0xFF3F, /*end*/ 0xFF3F, WordBreakProperty.ExtendNumLet], - [/*start*/ 0xFF41, /*end*/ 0xFF5A, WordBreakProperty.ALetter], - [/*start*/ 0xFF66, /*end*/ 0xFF6F, WordBreakProperty.Katakana], - [/*start*/ 0xFF70, /*end*/ 0xFF70, WordBreakProperty.Katakana], - [/*start*/ 0xFF71, /*end*/ 0xFF9D, WordBreakProperty.Katakana], - [/*start*/ 0xFF9E, /*end*/ 0xFF9F, WordBreakProperty.Extend], - [/*start*/ 0xFFA0, /*end*/ 0xFFBE, WordBreakProperty.ALetter], - [/*start*/ 0xFFC2, /*end*/ 0xFFC7, WordBreakProperty.ALetter], - [/*start*/ 0xFFCA, /*end*/ 0xFFCF, WordBreakProperty.ALetter], - [/*start*/ 0xFFD2, /*end*/ 0xFFD7, WordBreakProperty.ALetter], - [/*start*/ 0xFFDA, /*end*/ 0xFFDC, WordBreakProperty.ALetter], - [/*start*/ 0xFFF9, /*end*/ 0xFFFB, WordBreakProperty.Format], - [/*start*/ 0x10000, /*end*/ 0x1000B, WordBreakProperty.ALetter], - [/*start*/ 0x1000D, /*end*/ 0x10026, WordBreakProperty.ALetter], - [/*start*/ 0x10028, /*end*/ 0x1003A, WordBreakProperty.ALetter], - [/*start*/ 0x1003C, /*end*/ 0x1003D, WordBreakProperty.ALetter], - [/*start*/ 0x1003F, /*end*/ 0x1004D, WordBreakProperty.ALetter], - [/*start*/ 0x10050, /*end*/ 0x1005D, WordBreakProperty.ALetter], - [/*start*/ 0x10080, /*end*/ 0x100FA, WordBreakProperty.ALetter], - [/*start*/ 0x10140, /*end*/ 0x10174, WordBreakProperty.ALetter], - [/*start*/ 0x101FD, /*end*/ 0x101FD, WordBreakProperty.Extend], - [/*start*/ 0x10280, /*end*/ 0x1029C, WordBreakProperty.ALetter], - [/*start*/ 0x102A0, /*end*/ 0x102D0, WordBreakProperty.ALetter], - [/*start*/ 0x102E0, /*end*/ 0x102E0, WordBreakProperty.Extend], - [/*start*/ 0x10300, /*end*/ 0x1031F, WordBreakProperty.ALetter], - [/*start*/ 0x1032D, /*end*/ 0x10340, WordBreakProperty.ALetter], - [/*start*/ 0x10341, /*end*/ 0x10341, WordBreakProperty.ALetter], - [/*start*/ 0x10342, /*end*/ 0x10349, WordBreakProperty.ALetter], - [/*start*/ 0x1034A, /*end*/ 0x1034A, WordBreakProperty.ALetter], - [/*start*/ 0x10350, /*end*/ 0x10375, WordBreakProperty.ALetter], - [/*start*/ 0x10376, /*end*/ 0x1037A, WordBreakProperty.Extend], - [/*start*/ 0x10380, /*end*/ 0x1039D, WordBreakProperty.ALetter], - [/*start*/ 0x103A0, /*end*/ 0x103C3, WordBreakProperty.ALetter], - [/*start*/ 0x103C8, /*end*/ 0x103CF, WordBreakProperty.ALetter], - [/*start*/ 0x103D1, /*end*/ 0x103D5, WordBreakProperty.ALetter], - [/*start*/ 0x10400, /*end*/ 0x1044F, WordBreakProperty.ALetter], - [/*start*/ 0x10450, /*end*/ 0x1049D, WordBreakProperty.ALetter], - [/*start*/ 0x104A0, /*end*/ 0x104A9, WordBreakProperty.Numeric], - [/*start*/ 0x104B0, /*end*/ 0x104D3, WordBreakProperty.ALetter], - [/*start*/ 0x104D8, /*end*/ 0x104FB, WordBreakProperty.ALetter], - [/*start*/ 0x10500, /*end*/ 0x10527, WordBreakProperty.ALetter], - [/*start*/ 0x10530, /*end*/ 0x10563, WordBreakProperty.ALetter], - [/*start*/ 0x10600, /*end*/ 0x10736, WordBreakProperty.ALetter], - [/*start*/ 0x10740, /*end*/ 0x10755, WordBreakProperty.ALetter], - [/*start*/ 0x10760, /*end*/ 0x10767, WordBreakProperty.ALetter], - [/*start*/ 0x10800, /*end*/ 0x10805, WordBreakProperty.ALetter], - [/*start*/ 0x10808, /*end*/ 0x10808, WordBreakProperty.ALetter], - [/*start*/ 0x1080A, /*end*/ 0x10835, WordBreakProperty.ALetter], - [/*start*/ 0x10837, /*end*/ 0x10838, WordBreakProperty.ALetter], - [/*start*/ 0x1083C, /*end*/ 0x1083C, WordBreakProperty.ALetter], - [/*start*/ 0x1083F, /*end*/ 0x10855, WordBreakProperty.ALetter], - [/*start*/ 0x10860, /*end*/ 0x10876, WordBreakProperty.ALetter], - [/*start*/ 0x10880, /*end*/ 0x1089E, WordBreakProperty.ALetter], - [/*start*/ 0x108E0, /*end*/ 0x108F2, WordBreakProperty.ALetter], - [/*start*/ 0x108F4, /*end*/ 0x108F5, WordBreakProperty.ALetter], - [/*start*/ 0x10900, /*end*/ 0x10915, WordBreakProperty.ALetter], - [/*start*/ 0x10920, /*end*/ 0x10939, WordBreakProperty.ALetter], - [/*start*/ 0x10980, /*end*/ 0x109B7, WordBreakProperty.ALetter], - [/*start*/ 0x109BE, /*end*/ 0x109BF, WordBreakProperty.ALetter], - [/*start*/ 0x10A00, /*end*/ 0x10A00, WordBreakProperty.ALetter], - [/*start*/ 0x10A01, /*end*/ 0x10A03, WordBreakProperty.Extend], - [/*start*/ 0x10A05, /*end*/ 0x10A06, WordBreakProperty.Extend], - [/*start*/ 0x10A0C, /*end*/ 0x10A0F, WordBreakProperty.Extend], - [/*start*/ 0x10A10, /*end*/ 0x10A13, WordBreakProperty.ALetter], - [/*start*/ 0x10A15, /*end*/ 0x10A17, WordBreakProperty.ALetter], - [/*start*/ 0x10A19, /*end*/ 0x10A35, WordBreakProperty.ALetter], - [/*start*/ 0x10A38, /*end*/ 0x10A3A, WordBreakProperty.Extend], - [/*start*/ 0x10A3F, /*end*/ 0x10A3F, WordBreakProperty.Extend], - [/*start*/ 0x10A60, /*end*/ 0x10A7C, WordBreakProperty.ALetter], - [/*start*/ 0x10A80, /*end*/ 0x10A9C, WordBreakProperty.ALetter], - [/*start*/ 0x10AC0, /*end*/ 0x10AC7, WordBreakProperty.ALetter], - [/*start*/ 0x10AC9, /*end*/ 0x10AE4, WordBreakProperty.ALetter], - [/*start*/ 0x10AE5, /*end*/ 0x10AE6, WordBreakProperty.Extend], - [/*start*/ 0x10B00, /*end*/ 0x10B35, WordBreakProperty.ALetter], - [/*start*/ 0x10B40, /*end*/ 0x10B55, WordBreakProperty.ALetter], - [/*start*/ 0x10B60, /*end*/ 0x10B72, WordBreakProperty.ALetter], - [/*start*/ 0x10B80, /*end*/ 0x10B91, WordBreakProperty.ALetter], - [/*start*/ 0x10C00, /*end*/ 0x10C48, WordBreakProperty.ALetter], - [/*start*/ 0x10C80, /*end*/ 0x10CB2, WordBreakProperty.ALetter], - [/*start*/ 0x10CC0, /*end*/ 0x10CF2, WordBreakProperty.ALetter], - [/*start*/ 0x10D00, /*end*/ 0x10D23, WordBreakProperty.ALetter], - [/*start*/ 0x10D24, /*end*/ 0x10D27, WordBreakProperty.Extend], - [/*start*/ 0x10D30, /*end*/ 0x10D39, WordBreakProperty.Numeric], - [/*start*/ 0x10F00, /*end*/ 0x10F1C, WordBreakProperty.ALetter], - [/*start*/ 0x10F27, /*end*/ 0x10F27, WordBreakProperty.ALetter], - [/*start*/ 0x10F30, /*end*/ 0x10F45, WordBreakProperty.ALetter], - [/*start*/ 0x10F46, /*end*/ 0x10F50, WordBreakProperty.Extend], - [/*start*/ 0x10FE0, /*end*/ 0x10FF6, WordBreakProperty.ALetter], - [/*start*/ 0x11000, /*end*/ 0x11000, WordBreakProperty.Extend], - [/*start*/ 0x11001, /*end*/ 0x11001, WordBreakProperty.Extend], - [/*start*/ 0x11002, /*end*/ 0x11002, WordBreakProperty.Extend], - [/*start*/ 0x11003, /*end*/ 0x11037, WordBreakProperty.ALetter], - [/*start*/ 0x11038, /*end*/ 0x11046, WordBreakProperty.Extend], - [/*start*/ 0x11066, /*end*/ 0x1106F, WordBreakProperty.Numeric], - [/*start*/ 0x1107F, /*end*/ 0x11081, WordBreakProperty.Extend], - [/*start*/ 0x11082, /*end*/ 0x11082, WordBreakProperty.Extend], - [/*start*/ 0x11083, /*end*/ 0x110AF, WordBreakProperty.ALetter], - [/*start*/ 0x110B0, /*end*/ 0x110B2, WordBreakProperty.Extend], - [/*start*/ 0x110B3, /*end*/ 0x110B6, WordBreakProperty.Extend], - [/*start*/ 0x110B7, /*end*/ 0x110B8, WordBreakProperty.Extend], - [/*start*/ 0x110B9, /*end*/ 0x110BA, WordBreakProperty.Extend], - [/*start*/ 0x110BD, /*end*/ 0x110BD, WordBreakProperty.Format], - [/*start*/ 0x110CD, /*end*/ 0x110CD, WordBreakProperty.Format], - [/*start*/ 0x110D0, /*end*/ 0x110E8, WordBreakProperty.ALetter], - [/*start*/ 0x110F0, /*end*/ 0x110F9, WordBreakProperty.Numeric], - [/*start*/ 0x11100, /*end*/ 0x11102, WordBreakProperty.Extend], - [/*start*/ 0x11103, /*end*/ 0x11126, WordBreakProperty.ALetter], - [/*start*/ 0x11127, /*end*/ 0x1112B, WordBreakProperty.Extend], - [/*start*/ 0x1112C, /*end*/ 0x1112C, WordBreakProperty.Extend], - [/*start*/ 0x1112D, /*end*/ 0x11134, WordBreakProperty.Extend], - [/*start*/ 0x11136, /*end*/ 0x1113F, WordBreakProperty.Numeric], - [/*start*/ 0x11144, /*end*/ 0x11144, WordBreakProperty.ALetter], - [/*start*/ 0x11145, /*end*/ 0x11146, WordBreakProperty.Extend], - [/*start*/ 0x11150, /*end*/ 0x11172, WordBreakProperty.ALetter], - [/*start*/ 0x11173, /*end*/ 0x11173, WordBreakProperty.Extend], - [/*start*/ 0x11176, /*end*/ 0x11176, WordBreakProperty.ALetter], - [/*start*/ 0x11180, /*end*/ 0x11181, WordBreakProperty.Extend], - [/*start*/ 0x11182, /*end*/ 0x11182, WordBreakProperty.Extend], - [/*start*/ 0x11183, /*end*/ 0x111B2, WordBreakProperty.ALetter], - [/*start*/ 0x111B3, /*end*/ 0x111B5, WordBreakProperty.Extend], - [/*start*/ 0x111B6, /*end*/ 0x111BE, WordBreakProperty.Extend], - [/*start*/ 0x111BF, /*end*/ 0x111C0, WordBreakProperty.Extend], - [/*start*/ 0x111C1, /*end*/ 0x111C4, WordBreakProperty.ALetter], - [/*start*/ 0x111C9, /*end*/ 0x111CC, WordBreakProperty.Extend], - [/*start*/ 0x111D0, /*end*/ 0x111D9, WordBreakProperty.Numeric], - [/*start*/ 0x111DA, /*end*/ 0x111DA, WordBreakProperty.ALetter], - [/*start*/ 0x111DC, /*end*/ 0x111DC, WordBreakProperty.ALetter], - [/*start*/ 0x11200, /*end*/ 0x11211, WordBreakProperty.ALetter], - [/*start*/ 0x11213, /*end*/ 0x1122B, WordBreakProperty.ALetter], - [/*start*/ 0x1122C, /*end*/ 0x1122E, WordBreakProperty.Extend], - [/*start*/ 0x1122F, /*end*/ 0x11231, WordBreakProperty.Extend], - [/*start*/ 0x11232, /*end*/ 0x11233, WordBreakProperty.Extend], - [/*start*/ 0x11234, /*end*/ 0x11234, WordBreakProperty.Extend], - [/*start*/ 0x11235, /*end*/ 0x11235, WordBreakProperty.Extend], - [/*start*/ 0x11236, /*end*/ 0x11237, WordBreakProperty.Extend], - [/*start*/ 0x1123E, /*end*/ 0x1123E, WordBreakProperty.Extend], - [/*start*/ 0x11280, /*end*/ 0x11286, WordBreakProperty.ALetter], - [/*start*/ 0x11288, /*end*/ 0x11288, WordBreakProperty.ALetter], - [/*start*/ 0x1128A, /*end*/ 0x1128D, WordBreakProperty.ALetter], - [/*start*/ 0x1128F, /*end*/ 0x1129D, WordBreakProperty.ALetter], - [/*start*/ 0x1129F, /*end*/ 0x112A8, WordBreakProperty.ALetter], - [/*start*/ 0x112B0, /*end*/ 0x112DE, WordBreakProperty.ALetter], - [/*start*/ 0x112DF, /*end*/ 0x112DF, WordBreakProperty.Extend], - [/*start*/ 0x112E0, /*end*/ 0x112E2, WordBreakProperty.Extend], - [/*start*/ 0x112E3, /*end*/ 0x112EA, WordBreakProperty.Extend], - [/*start*/ 0x112F0, /*end*/ 0x112F9, WordBreakProperty.Numeric], - [/*start*/ 0x11300, /*end*/ 0x11301, WordBreakProperty.Extend], - [/*start*/ 0x11302, /*end*/ 0x11303, WordBreakProperty.Extend], - [/*start*/ 0x11305, /*end*/ 0x1130C, WordBreakProperty.ALetter], - [/*start*/ 0x1130F, /*end*/ 0x11310, WordBreakProperty.ALetter], - [/*start*/ 0x11313, /*end*/ 0x11328, WordBreakProperty.ALetter], - [/*start*/ 0x1132A, /*end*/ 0x11330, WordBreakProperty.ALetter], - [/*start*/ 0x11332, /*end*/ 0x11333, WordBreakProperty.ALetter], - [/*start*/ 0x11335, /*end*/ 0x11339, WordBreakProperty.ALetter], - [/*start*/ 0x1133B, /*end*/ 0x1133C, WordBreakProperty.Extend], - [/*start*/ 0x1133D, /*end*/ 0x1133D, WordBreakProperty.ALetter], - [/*start*/ 0x1133E, /*end*/ 0x1133F, WordBreakProperty.Extend], - [/*start*/ 0x11340, /*end*/ 0x11340, WordBreakProperty.Extend], - [/*start*/ 0x11341, /*end*/ 0x11344, WordBreakProperty.Extend], - [/*start*/ 0x11347, /*end*/ 0x11348, WordBreakProperty.Extend], - [/*start*/ 0x1134B, /*end*/ 0x1134D, WordBreakProperty.Extend], - [/*start*/ 0x11350, /*end*/ 0x11350, WordBreakProperty.ALetter], - [/*start*/ 0x11357, /*end*/ 0x11357, WordBreakProperty.Extend], - [/*start*/ 0x1135D, /*end*/ 0x11361, WordBreakProperty.ALetter], - [/*start*/ 0x11362, /*end*/ 0x11363, WordBreakProperty.Extend], - [/*start*/ 0x11366, /*end*/ 0x1136C, WordBreakProperty.Extend], - [/*start*/ 0x11370, /*end*/ 0x11374, WordBreakProperty.Extend], - [/*start*/ 0x11400, /*end*/ 0x11434, WordBreakProperty.ALetter], - [/*start*/ 0x11435, /*end*/ 0x11437, WordBreakProperty.Extend], - [/*start*/ 0x11438, /*end*/ 0x1143F, WordBreakProperty.Extend], - [/*start*/ 0x11440, /*end*/ 0x11441, WordBreakProperty.Extend], - [/*start*/ 0x11442, /*end*/ 0x11444, WordBreakProperty.Extend], - [/*start*/ 0x11445, /*end*/ 0x11445, WordBreakProperty.Extend], - [/*start*/ 0x11446, /*end*/ 0x11446, WordBreakProperty.Extend], - [/*start*/ 0x11447, /*end*/ 0x1144A, WordBreakProperty.ALetter], - [/*start*/ 0x11450, /*end*/ 0x11459, WordBreakProperty.Numeric], - [/*start*/ 0x1145E, /*end*/ 0x1145E, WordBreakProperty.Extend], - [/*start*/ 0x1145F, /*end*/ 0x1145F, WordBreakProperty.ALetter], - [/*start*/ 0x11480, /*end*/ 0x114AF, WordBreakProperty.ALetter], - [/*start*/ 0x114B0, /*end*/ 0x114B2, WordBreakProperty.Extend], - [/*start*/ 0x114B3, /*end*/ 0x114B8, WordBreakProperty.Extend], - [/*start*/ 0x114B9, /*end*/ 0x114B9, WordBreakProperty.Extend], - [/*start*/ 0x114BA, /*end*/ 0x114BA, WordBreakProperty.Extend], - [/*start*/ 0x114BB, /*end*/ 0x114BE, WordBreakProperty.Extend], - [/*start*/ 0x114BF, /*end*/ 0x114C0, WordBreakProperty.Extend], - [/*start*/ 0x114C1, /*end*/ 0x114C1, WordBreakProperty.Extend], - [/*start*/ 0x114C2, /*end*/ 0x114C3, WordBreakProperty.Extend], - [/*start*/ 0x114C4, /*end*/ 0x114C5, WordBreakProperty.ALetter], - [/*start*/ 0x114C7, /*end*/ 0x114C7, WordBreakProperty.ALetter], - [/*start*/ 0x114D0, /*end*/ 0x114D9, WordBreakProperty.Numeric], - [/*start*/ 0x11580, /*end*/ 0x115AE, WordBreakProperty.ALetter], - [/*start*/ 0x115AF, /*end*/ 0x115B1, WordBreakProperty.Extend], - [/*start*/ 0x115B2, /*end*/ 0x115B5, WordBreakProperty.Extend], - [/*start*/ 0x115B8, /*end*/ 0x115BB, WordBreakProperty.Extend], - [/*start*/ 0x115BC, /*end*/ 0x115BD, WordBreakProperty.Extend], - [/*start*/ 0x115BE, /*end*/ 0x115BE, WordBreakProperty.Extend], - [/*start*/ 0x115BF, /*end*/ 0x115C0, WordBreakProperty.Extend], - [/*start*/ 0x115D8, /*end*/ 0x115DB, WordBreakProperty.ALetter], - [/*start*/ 0x115DC, /*end*/ 0x115DD, WordBreakProperty.Extend], - [/*start*/ 0x11600, /*end*/ 0x1162F, WordBreakProperty.ALetter], - [/*start*/ 0x11630, /*end*/ 0x11632, WordBreakProperty.Extend], - [/*start*/ 0x11633, /*end*/ 0x1163A, WordBreakProperty.Extend], - [/*start*/ 0x1163B, /*end*/ 0x1163C, WordBreakProperty.Extend], - [/*start*/ 0x1163D, /*end*/ 0x1163D, WordBreakProperty.Extend], - [/*start*/ 0x1163E, /*end*/ 0x1163E, WordBreakProperty.Extend], - [/*start*/ 0x1163F, /*end*/ 0x11640, WordBreakProperty.Extend], - [/*start*/ 0x11644, /*end*/ 0x11644, WordBreakProperty.ALetter], - [/*start*/ 0x11650, /*end*/ 0x11659, WordBreakProperty.Numeric], - [/*start*/ 0x11680, /*end*/ 0x116AA, WordBreakProperty.ALetter], - [/*start*/ 0x116AB, /*end*/ 0x116AB, WordBreakProperty.Extend], - [/*start*/ 0x116AC, /*end*/ 0x116AC, WordBreakProperty.Extend], - [/*start*/ 0x116AD, /*end*/ 0x116AD, WordBreakProperty.Extend], - [/*start*/ 0x116AE, /*end*/ 0x116AF, WordBreakProperty.Extend], - [/*start*/ 0x116B0, /*end*/ 0x116B5, WordBreakProperty.Extend], - [/*start*/ 0x116B6, /*end*/ 0x116B6, WordBreakProperty.Extend], - [/*start*/ 0x116B7, /*end*/ 0x116B7, WordBreakProperty.Extend], - [/*start*/ 0x116B8, /*end*/ 0x116B8, WordBreakProperty.ALetter], - [/*start*/ 0x116C0, /*end*/ 0x116C9, WordBreakProperty.Numeric], - [/*start*/ 0x1171D, /*end*/ 0x1171F, WordBreakProperty.Extend], - [/*start*/ 0x11720, /*end*/ 0x11721, WordBreakProperty.Extend], - [/*start*/ 0x11722, /*end*/ 0x11725, WordBreakProperty.Extend], - [/*start*/ 0x11726, /*end*/ 0x11726, WordBreakProperty.Extend], - [/*start*/ 0x11727, /*end*/ 0x1172B, WordBreakProperty.Extend], - [/*start*/ 0x11730, /*end*/ 0x11739, WordBreakProperty.Numeric], - [/*start*/ 0x11800, /*end*/ 0x1182B, WordBreakProperty.ALetter], - [/*start*/ 0x1182C, /*end*/ 0x1182E, WordBreakProperty.Extend], - [/*start*/ 0x1182F, /*end*/ 0x11837, WordBreakProperty.Extend], - [/*start*/ 0x11838, /*end*/ 0x11838, WordBreakProperty.Extend], - [/*start*/ 0x11839, /*end*/ 0x1183A, WordBreakProperty.Extend], - [/*start*/ 0x118A0, /*end*/ 0x118DF, WordBreakProperty.ALetter], - [/*start*/ 0x118E0, /*end*/ 0x118E9, WordBreakProperty.Numeric], - [/*start*/ 0x118FF, /*end*/ 0x118FF, WordBreakProperty.ALetter], - [/*start*/ 0x119A0, /*end*/ 0x119A7, WordBreakProperty.ALetter], - [/*start*/ 0x119AA, /*end*/ 0x119D0, WordBreakProperty.ALetter], - [/*start*/ 0x119D1, /*end*/ 0x119D3, WordBreakProperty.Extend], - [/*start*/ 0x119D4, /*end*/ 0x119D7, WordBreakProperty.Extend], - [/*start*/ 0x119DA, /*end*/ 0x119DB, WordBreakProperty.Extend], - [/*start*/ 0x119DC, /*end*/ 0x119DF, WordBreakProperty.Extend], - [/*start*/ 0x119E0, /*end*/ 0x119E0, WordBreakProperty.Extend], - [/*start*/ 0x119E1, /*end*/ 0x119E1, WordBreakProperty.ALetter], - [/*start*/ 0x119E3, /*end*/ 0x119E3, WordBreakProperty.ALetter], - [/*start*/ 0x119E4, /*end*/ 0x119E4, WordBreakProperty.Extend], - [/*start*/ 0x11A00, /*end*/ 0x11A00, WordBreakProperty.ALetter], - [/*start*/ 0x11A01, /*end*/ 0x11A0A, WordBreakProperty.Extend], - [/*start*/ 0x11A0B, /*end*/ 0x11A32, WordBreakProperty.ALetter], - [/*start*/ 0x11A33, /*end*/ 0x11A38, WordBreakProperty.Extend], - [/*start*/ 0x11A39, /*end*/ 0x11A39, WordBreakProperty.Extend], - [/*start*/ 0x11A3A, /*end*/ 0x11A3A, WordBreakProperty.ALetter], - [/*start*/ 0x11A3B, /*end*/ 0x11A3E, WordBreakProperty.Extend], - [/*start*/ 0x11A47, /*end*/ 0x11A47, WordBreakProperty.Extend], - [/*start*/ 0x11A50, /*end*/ 0x11A50, WordBreakProperty.ALetter], - [/*start*/ 0x11A51, /*end*/ 0x11A56, WordBreakProperty.Extend], - [/*start*/ 0x11A57, /*end*/ 0x11A58, WordBreakProperty.Extend], - [/*start*/ 0x11A59, /*end*/ 0x11A5B, WordBreakProperty.Extend], - [/*start*/ 0x11A5C, /*end*/ 0x11A89, WordBreakProperty.ALetter], - [/*start*/ 0x11A8A, /*end*/ 0x11A96, WordBreakProperty.Extend], - [/*start*/ 0x11A97, /*end*/ 0x11A97, WordBreakProperty.Extend], - [/*start*/ 0x11A98, /*end*/ 0x11A99, WordBreakProperty.Extend], - [/*start*/ 0x11A9D, /*end*/ 0x11A9D, WordBreakProperty.ALetter], - [/*start*/ 0x11AC0, /*end*/ 0x11AF8, WordBreakProperty.ALetter], - [/*start*/ 0x11C00, /*end*/ 0x11C08, WordBreakProperty.ALetter], - [/*start*/ 0x11C0A, /*end*/ 0x11C2E, WordBreakProperty.ALetter], - [/*start*/ 0x11C2F, /*end*/ 0x11C2F, WordBreakProperty.Extend], - [/*start*/ 0x11C30, /*end*/ 0x11C36, WordBreakProperty.Extend], - [/*start*/ 0x11C38, /*end*/ 0x11C3D, WordBreakProperty.Extend], - [/*start*/ 0x11C3E, /*end*/ 0x11C3E, WordBreakProperty.Extend], - [/*start*/ 0x11C3F, /*end*/ 0x11C3F, WordBreakProperty.Extend], - [/*start*/ 0x11C40, /*end*/ 0x11C40, WordBreakProperty.ALetter], - [/*start*/ 0x11C50, /*end*/ 0x11C59, WordBreakProperty.Numeric], - [/*start*/ 0x11C72, /*end*/ 0x11C8F, WordBreakProperty.ALetter], - [/*start*/ 0x11C92, /*end*/ 0x11CA7, WordBreakProperty.Extend], - [/*start*/ 0x11CA9, /*end*/ 0x11CA9, WordBreakProperty.Extend], - [/*start*/ 0x11CAA, /*end*/ 0x11CB0, WordBreakProperty.Extend], - [/*start*/ 0x11CB1, /*end*/ 0x11CB1, WordBreakProperty.Extend], - [/*start*/ 0x11CB2, /*end*/ 0x11CB3, WordBreakProperty.Extend], - [/*start*/ 0x11CB4, /*end*/ 0x11CB4, WordBreakProperty.Extend], - [/*start*/ 0x11CB5, /*end*/ 0x11CB6, WordBreakProperty.Extend], - [/*start*/ 0x11D00, /*end*/ 0x11D06, WordBreakProperty.ALetter], - [/*start*/ 0x11D08, /*end*/ 0x11D09, WordBreakProperty.ALetter], - [/*start*/ 0x11D0B, /*end*/ 0x11D30, WordBreakProperty.ALetter], - [/*start*/ 0x11D31, /*end*/ 0x11D36, WordBreakProperty.Extend], - [/*start*/ 0x11D3A, /*end*/ 0x11D3A, WordBreakProperty.Extend], - [/*start*/ 0x11D3C, /*end*/ 0x11D3D, WordBreakProperty.Extend], - [/*start*/ 0x11D3F, /*end*/ 0x11D45, WordBreakProperty.Extend], - [/*start*/ 0x11D46, /*end*/ 0x11D46, WordBreakProperty.ALetter], - [/*start*/ 0x11D47, /*end*/ 0x11D47, WordBreakProperty.Extend], - [/*start*/ 0x11D50, /*end*/ 0x11D59, WordBreakProperty.Numeric], - [/*start*/ 0x11D60, /*end*/ 0x11D65, WordBreakProperty.ALetter], - [/*start*/ 0x11D67, /*end*/ 0x11D68, WordBreakProperty.ALetter], - [/*start*/ 0x11D6A, /*end*/ 0x11D89, WordBreakProperty.ALetter], - [/*start*/ 0x11D8A, /*end*/ 0x11D8E, WordBreakProperty.Extend], - [/*start*/ 0x11D90, /*end*/ 0x11D91, WordBreakProperty.Extend], - [/*start*/ 0x11D93, /*end*/ 0x11D94, WordBreakProperty.Extend], - [/*start*/ 0x11D95, /*end*/ 0x11D95, WordBreakProperty.Extend], - [/*start*/ 0x11D96, /*end*/ 0x11D96, WordBreakProperty.Extend], - [/*start*/ 0x11D97, /*end*/ 0x11D97, WordBreakProperty.Extend], - [/*start*/ 0x11D98, /*end*/ 0x11D98, WordBreakProperty.ALetter], - [/*start*/ 0x11DA0, /*end*/ 0x11DA9, WordBreakProperty.Numeric], - [/*start*/ 0x11EE0, /*end*/ 0x11EF2, WordBreakProperty.ALetter], - [/*start*/ 0x11EF3, /*end*/ 0x11EF4, WordBreakProperty.Extend], - [/*start*/ 0x11EF5, /*end*/ 0x11EF6, WordBreakProperty.Extend], - [/*start*/ 0x12000, /*end*/ 0x12399, WordBreakProperty.ALetter], - [/*start*/ 0x12400, /*end*/ 0x1246E, WordBreakProperty.ALetter], - [/*start*/ 0x12480, /*end*/ 0x12543, WordBreakProperty.ALetter], - [/*start*/ 0x13000, /*end*/ 0x1342E, WordBreakProperty.ALetter], - [/*start*/ 0x13430, /*end*/ 0x13438, WordBreakProperty.Format], - [/*start*/ 0x14400, /*end*/ 0x14646, WordBreakProperty.ALetter], - [/*start*/ 0x16800, /*end*/ 0x16A38, WordBreakProperty.ALetter], - [/*start*/ 0x16A40, /*end*/ 0x16A5E, WordBreakProperty.ALetter], - [/*start*/ 0x16A60, /*end*/ 0x16A69, WordBreakProperty.Numeric], - [/*start*/ 0x16AD0, /*end*/ 0x16AED, WordBreakProperty.ALetter], - [/*start*/ 0x16AF0, /*end*/ 0x16AF4, WordBreakProperty.Extend], - [/*start*/ 0x16B00, /*end*/ 0x16B2F, WordBreakProperty.ALetter], - [/*start*/ 0x16B30, /*end*/ 0x16B36, WordBreakProperty.Extend], - [/*start*/ 0x16B40, /*end*/ 0x16B43, WordBreakProperty.ALetter], - [/*start*/ 0x16B50, /*end*/ 0x16B59, WordBreakProperty.Numeric], - [/*start*/ 0x16B63, /*end*/ 0x16B77, WordBreakProperty.ALetter], - [/*start*/ 0x16B7D, /*end*/ 0x16B8F, WordBreakProperty.ALetter], - [/*start*/ 0x16E40, /*end*/ 0x16E7F, WordBreakProperty.ALetter], - [/*start*/ 0x16F00, /*end*/ 0x16F4A, WordBreakProperty.ALetter], - [/*start*/ 0x16F4F, /*end*/ 0x16F4F, WordBreakProperty.Extend], - [/*start*/ 0x16F50, /*end*/ 0x16F50, WordBreakProperty.ALetter], - [/*start*/ 0x16F51, /*end*/ 0x16F87, WordBreakProperty.Extend], - [/*start*/ 0x16F8F, /*end*/ 0x16F92, WordBreakProperty.Extend], - [/*start*/ 0x16F93, /*end*/ 0x16F9F, WordBreakProperty.ALetter], - [/*start*/ 0x16FE0, /*end*/ 0x16FE1, WordBreakProperty.ALetter], - [/*start*/ 0x16FE3, /*end*/ 0x16FE3, WordBreakProperty.ALetter], - [/*start*/ 0x1B000, /*end*/ 0x1B000, WordBreakProperty.Katakana], - [/*start*/ 0x1B164, /*end*/ 0x1B167, WordBreakProperty.Katakana], - [/*start*/ 0x1BC00, /*end*/ 0x1BC6A, WordBreakProperty.ALetter], - [/*start*/ 0x1BC70, /*end*/ 0x1BC7C, WordBreakProperty.ALetter], - [/*start*/ 0x1BC80, /*end*/ 0x1BC88, WordBreakProperty.ALetter], - [/*start*/ 0x1BC90, /*end*/ 0x1BC99, WordBreakProperty.ALetter], - [/*start*/ 0x1BC9D, /*end*/ 0x1BC9E, WordBreakProperty.Extend], - [/*start*/ 0x1BCA0, /*end*/ 0x1BCA3, WordBreakProperty.Format], - [/*start*/ 0x1D165, /*end*/ 0x1D166, WordBreakProperty.Extend], - [/*start*/ 0x1D167, /*end*/ 0x1D169, WordBreakProperty.Extend], - [/*start*/ 0x1D16D, /*end*/ 0x1D172, WordBreakProperty.Extend], - [/*start*/ 0x1D173, /*end*/ 0x1D17A, WordBreakProperty.Format], - [/*start*/ 0x1D17B, /*end*/ 0x1D182, WordBreakProperty.Extend], - [/*start*/ 0x1D185, /*end*/ 0x1D18B, WordBreakProperty.Extend], - [/*start*/ 0x1D1AA, /*end*/ 0x1D1AD, WordBreakProperty.Extend], - [/*start*/ 0x1D242, /*end*/ 0x1D244, WordBreakProperty.Extend], - [/*start*/ 0x1D400, /*end*/ 0x1D454, WordBreakProperty.ALetter], - [/*start*/ 0x1D456, /*end*/ 0x1D49C, WordBreakProperty.ALetter], - [/*start*/ 0x1D49E, /*end*/ 0x1D49F, WordBreakProperty.ALetter], - [/*start*/ 0x1D4A2, /*end*/ 0x1D4A2, WordBreakProperty.ALetter], - [/*start*/ 0x1D4A5, /*end*/ 0x1D4A6, WordBreakProperty.ALetter], - [/*start*/ 0x1D4A9, /*end*/ 0x1D4AC, WordBreakProperty.ALetter], - [/*start*/ 0x1D4AE, /*end*/ 0x1D4B9, WordBreakProperty.ALetter], - [/*start*/ 0x1D4BB, /*end*/ 0x1D4BB, WordBreakProperty.ALetter], - [/*start*/ 0x1D4BD, /*end*/ 0x1D4C3, WordBreakProperty.ALetter], - [/*start*/ 0x1D4C5, /*end*/ 0x1D505, WordBreakProperty.ALetter], - [/*start*/ 0x1D507, /*end*/ 0x1D50A, WordBreakProperty.ALetter], - [/*start*/ 0x1D50D, /*end*/ 0x1D514, WordBreakProperty.ALetter], - [/*start*/ 0x1D516, /*end*/ 0x1D51C, WordBreakProperty.ALetter], - [/*start*/ 0x1D51E, /*end*/ 0x1D539, WordBreakProperty.ALetter], - [/*start*/ 0x1D53B, /*end*/ 0x1D53E, WordBreakProperty.ALetter], - [/*start*/ 0x1D540, /*end*/ 0x1D544, WordBreakProperty.ALetter], - [/*start*/ 0x1D546, /*end*/ 0x1D546, WordBreakProperty.ALetter], - [/*start*/ 0x1D54A, /*end*/ 0x1D550, WordBreakProperty.ALetter], - [/*start*/ 0x1D552, /*end*/ 0x1D6A5, WordBreakProperty.ALetter], - [/*start*/ 0x1D6A8, /*end*/ 0x1D6C0, WordBreakProperty.ALetter], - [/*start*/ 0x1D6C2, /*end*/ 0x1D6DA, WordBreakProperty.ALetter], - [/*start*/ 0x1D6DC, /*end*/ 0x1D6FA, WordBreakProperty.ALetter], - [/*start*/ 0x1D6FC, /*end*/ 0x1D714, WordBreakProperty.ALetter], - [/*start*/ 0x1D716, /*end*/ 0x1D734, WordBreakProperty.ALetter], - [/*start*/ 0x1D736, /*end*/ 0x1D74E, WordBreakProperty.ALetter], - [/*start*/ 0x1D750, /*end*/ 0x1D76E, WordBreakProperty.ALetter], - [/*start*/ 0x1D770, /*end*/ 0x1D788, WordBreakProperty.ALetter], - [/*start*/ 0x1D78A, /*end*/ 0x1D7A8, WordBreakProperty.ALetter], - [/*start*/ 0x1D7AA, /*end*/ 0x1D7C2, WordBreakProperty.ALetter], - [/*start*/ 0x1D7C4, /*end*/ 0x1D7CB, WordBreakProperty.ALetter], - [/*start*/ 0x1D7CE, /*end*/ 0x1D7FF, WordBreakProperty.Numeric], - [/*start*/ 0x1DA00, /*end*/ 0x1DA36, WordBreakProperty.Extend], - [/*start*/ 0x1DA3B, /*end*/ 0x1DA6C, WordBreakProperty.Extend], - [/*start*/ 0x1DA75, /*end*/ 0x1DA75, WordBreakProperty.Extend], - [/*start*/ 0x1DA84, /*end*/ 0x1DA84, WordBreakProperty.Extend], - [/*start*/ 0x1DA9B, /*end*/ 0x1DA9F, WordBreakProperty.Extend], - [/*start*/ 0x1DAA1, /*end*/ 0x1DAAF, WordBreakProperty.Extend], - [/*start*/ 0x1E000, /*end*/ 0x1E006, WordBreakProperty.Extend], - [/*start*/ 0x1E008, /*end*/ 0x1E018, WordBreakProperty.Extend], - [/*start*/ 0x1E01B, /*end*/ 0x1E021, WordBreakProperty.Extend], - [/*start*/ 0x1E023, /*end*/ 0x1E024, WordBreakProperty.Extend], - [/*start*/ 0x1E026, /*end*/ 0x1E02A, WordBreakProperty.Extend], - [/*start*/ 0x1E100, /*end*/ 0x1E12C, WordBreakProperty.ALetter], - [/*start*/ 0x1E130, /*end*/ 0x1E136, WordBreakProperty.Extend], - [/*start*/ 0x1E137, /*end*/ 0x1E13D, WordBreakProperty.ALetter], - [/*start*/ 0x1E140, /*end*/ 0x1E149, WordBreakProperty.Numeric], - [/*start*/ 0x1E14E, /*end*/ 0x1E14E, WordBreakProperty.ALetter], - [/*start*/ 0x1E2C0, /*end*/ 0x1E2EB, WordBreakProperty.ALetter], - [/*start*/ 0x1E2EC, /*end*/ 0x1E2EF, WordBreakProperty.Extend], - [/*start*/ 0x1E2F0, /*end*/ 0x1E2F9, WordBreakProperty.Numeric], - [/*start*/ 0x1E800, /*end*/ 0x1E8C4, WordBreakProperty.ALetter], - [/*start*/ 0x1E8D0, /*end*/ 0x1E8D6, WordBreakProperty.Extend], - [/*start*/ 0x1E900, /*end*/ 0x1E943, WordBreakProperty.ALetter], - [/*start*/ 0x1E944, /*end*/ 0x1E94A, WordBreakProperty.Extend], - [/*start*/ 0x1E94B, /*end*/ 0x1E94B, WordBreakProperty.ALetter], - [/*start*/ 0x1E950, /*end*/ 0x1E959, WordBreakProperty.Numeric], - [/*start*/ 0x1EE00, /*end*/ 0x1EE03, WordBreakProperty.ALetter], - [/*start*/ 0x1EE05, /*end*/ 0x1EE1F, WordBreakProperty.ALetter], - [/*start*/ 0x1EE21, /*end*/ 0x1EE22, WordBreakProperty.ALetter], - [/*start*/ 0x1EE24, /*end*/ 0x1EE24, WordBreakProperty.ALetter], - [/*start*/ 0x1EE27, /*end*/ 0x1EE27, WordBreakProperty.ALetter], - [/*start*/ 0x1EE29, /*end*/ 0x1EE32, WordBreakProperty.ALetter], - [/*start*/ 0x1EE34, /*end*/ 0x1EE37, WordBreakProperty.ALetter], - [/*start*/ 0x1EE39, /*end*/ 0x1EE39, WordBreakProperty.ALetter], - [/*start*/ 0x1EE3B, /*end*/ 0x1EE3B, WordBreakProperty.ALetter], - [/*start*/ 0x1EE42, /*end*/ 0x1EE42, WordBreakProperty.ALetter], - [/*start*/ 0x1EE47, /*end*/ 0x1EE47, WordBreakProperty.ALetter], - [/*start*/ 0x1EE49, /*end*/ 0x1EE49, WordBreakProperty.ALetter], - [/*start*/ 0x1EE4B, /*end*/ 0x1EE4B, WordBreakProperty.ALetter], - [/*start*/ 0x1EE4D, /*end*/ 0x1EE4F, WordBreakProperty.ALetter], - [/*start*/ 0x1EE51, /*end*/ 0x1EE52, WordBreakProperty.ALetter], - [/*start*/ 0x1EE54, /*end*/ 0x1EE54, WordBreakProperty.ALetter], - [/*start*/ 0x1EE57, /*end*/ 0x1EE57, WordBreakProperty.ALetter], - [/*start*/ 0x1EE59, /*end*/ 0x1EE59, WordBreakProperty.ALetter], - [/*start*/ 0x1EE5B, /*end*/ 0x1EE5B, WordBreakProperty.ALetter], - [/*start*/ 0x1EE5D, /*end*/ 0x1EE5D, WordBreakProperty.ALetter], - [/*start*/ 0x1EE5F, /*end*/ 0x1EE5F, WordBreakProperty.ALetter], - [/*start*/ 0x1EE61, /*end*/ 0x1EE62, WordBreakProperty.ALetter], - [/*start*/ 0x1EE64, /*end*/ 0x1EE64, WordBreakProperty.ALetter], - [/*start*/ 0x1EE67, /*end*/ 0x1EE6A, WordBreakProperty.ALetter], - [/*start*/ 0x1EE6C, /*end*/ 0x1EE72, WordBreakProperty.ALetter], - [/*start*/ 0x1EE74, /*end*/ 0x1EE77, WordBreakProperty.ALetter], - [/*start*/ 0x1EE79, /*end*/ 0x1EE7C, WordBreakProperty.ALetter], - [/*start*/ 0x1EE7E, /*end*/ 0x1EE7E, WordBreakProperty.ALetter], - [/*start*/ 0x1EE80, /*end*/ 0x1EE89, WordBreakProperty.ALetter], - [/*start*/ 0x1EE8B, /*end*/ 0x1EE9B, WordBreakProperty.ALetter], - [/*start*/ 0x1EEA1, /*end*/ 0x1EEA3, WordBreakProperty.ALetter], - [/*start*/ 0x1EEA5, /*end*/ 0x1EEA9, WordBreakProperty.ALetter], - [/*start*/ 0x1EEAB, /*end*/ 0x1EEBB, WordBreakProperty.ALetter], - [/*start*/ 0x1F130, /*end*/ 0x1F149, WordBreakProperty.ALetter], - [/*start*/ 0x1F150, /*end*/ 0x1F169, WordBreakProperty.ALetter], - [/*start*/ 0x1F170, /*end*/ 0x1F189, WordBreakProperty.ALetter], - [/*start*/ 0x1F1E6, /*end*/ 0x1F1FF, WordBreakProperty.Regional_Indicator], - [/*start*/ 0x1F3FB, /*end*/ 0x1F3FF, WordBreakProperty.Extend], - [/*start*/ 0xE0001, /*end*/ 0xE0001, WordBreakProperty.Format], - [/*start*/ 0xE0020, /*end*/ 0xE007F, WordBreakProperty.Extend], - [/*start*/ 0xE0100, /*end*/ 0xE01EF, WordBreakProperty.Extend], -]; -} -} \ No newline at end of file diff --git a/common/predictive-text/worker/worker-interfaces.ts b/common/predictive-text/worker/worker-interfaces.ts index bd3ed674c39e72907574057bd8db9df564ec425e..32e5c6051515c2bac100e642efd19378ca0b958c 100644 --- a/common/predictive-text/worker/worker-interfaces.ts +++ b/common/predictive-text/worker/worker-interfaces.ts @@ -118,19 +118,35 @@ interface WordbreakMessage { context: Context; } +/** + * The LMLayer can be in one of the following states. The LMLayer can only produce predictions in the 'ready' state. + */ +type LMLayerWorkerState = LMLayerWorkerUnconfiguredState | LMLayerWorkerModellessState | LMLayerWorkerReadyState; /** - * Represents a state in the LMLayer. + * Represents the unconfigured state of the LMLayer. */ -interface LMLayerWorkerState { - /** - * Informative property. Name of the state. Currently, the LMLayerWorker can only - * be the following states: - */ - name: 'unconfigured' | 'modelless' | 'ready'; +interface LMLayerWorkerUnconfiguredState { + name: 'unconfigured'; handleMessage(payload: IncomingMessage): void; } +/** + * Represents the pre-model-load state of the LMLayer. + */ +interface LMLayerWorkerModellessState { + name: 'modelless'; + handleMessage(payload: IncomingMessage): void; +} + +/** + * Represents the 'ready' state of the LMLayer. + */ +interface LMLayerWorkerReadyState { + name: 'ready'; + handleMessage(payload: IncomingMessage): void; + compositor: ModelCompositor; +} /** * Constructors that return worker internal models. diff --git a/android/crowdin.yml b/crowdin.yml similarity index 63% rename from android/crowdin.yml rename to crowdin.yml index c9c097429a9aa9fe461204ca51973d09e387bdad..61c0085eef2d8eebd7bbd822374000991fd7a33f 100644 --- a/android/crowdin.yml +++ b/crowdin.yml @@ -1,3 +1,7 @@ +# +# Shared Crowdin control for all Keyman platforms +# + # # Your Crowdin credentials # @@ -20,30 +24,72 @@ files: # dest: crowdin path in https://crowdin.com/project/keyman # translation: local path where downloaded translations from crowdin go + # Android files - - source: /KMEA/app/src/main/res/values/strings.xml - dest: /android/KMEA/strings.xml - translation: /KMEA/app/src/main/res/values-%android_code%/strings.xml + + - source: /android/KMEA/app/src/main/res/values/strings.xml + dest: /android/engine/strings.xml + translation: /android/KMEA/app/src/main/res/values-%android_code%/strings.xml languages_mapping: # Prevent invalid region pap-rPAP android_code: pap: pap - - source: /KMAPro/kMAPro/src/main/res/values/strings.xml - dest: /android/KMAPro/strings.xml - translation: /KMAPro/kMAPro/src/main/res/values-%android_code%/strings.xml + - source: /android/KMAPro/kMAPro/src/main/res/values/strings.xml + dest: /android/app/strings.xml + translation: /android/KMAPro/kMAPro/src/main/res/values-%android_code%/strings.xml languages_mapping: # Prevent invalid region pap-rPAP android_code: pap: pap + # Windows files + # Note: we use type: android for the Windows project files + + - source: /windows/src/desktop/kmshell/xml/strings.xml + dest: /windows/strings.xml + translation: /windows/src/desktop/kmshell/locale/%locale%/%original_file_name% + type: android + + - source: /window/src/desktop/setup/locale/en/strings.xml + dest: /windows/setup/strings.xml + translation: /windows/src/desktop/setup/locale/%locale%/%original_file_name% + type: android + + # iOS files + + - source: /ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/en.lproj/ResourceInfoView.strings + dest: /ios/engine/ResourceInfoView.strings + translation: /ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/%osx_code%/%original_file_name% + + - source: /ios/engine/KMEI/KeymanEngine/en.lproj/Localizable.strings + dest: /ios/engine/Localizable.strings + translation: /ios/engine/KMEI/KeymanEngine/%osx_code%/%original_file_name% + + - source: /ios/engine/KMEI/KeymanEngine/en.lproj/Localizable.stringsdict + dest: /ios/engine/Localizable.stringsdict + translation: /ios/engine/KMEI/KeymanEngine/%osx_code%/%original_file_name% + + - source: /ios/keyman/Keyman/Keyman/en.lproj/Localizable.strings + dest: /ios/app/Localizable.strings + translation: /ios/keyman/Keyman/Keyman/%osx_code%/%original_file_name% + + # Linux files + + - source: /linux/keyman-config/locale/keyman-config.pot + dest: /linux/keyman-config.pot + translation: /linux/keyman-config/locale/%locale_with_underscore%.po + type: gettext + update_option: update_as_unapproved + + # crowdin parameters descriptions: # # Source files filter # e.g. "/resources/en/*.json" # - + # # Where translations will be placed # e.g. "/resources/%two_letters_code%/%original_file_name%" diff --git a/developer/js/.npmignore b/developer/js/.npmignore index 884d65b27d9c9f1b52e4e64782e60a74a4555b1a..71822622d03656046df335213cedb5acd5b151d1 100644 --- a/developer/js/.npmignore +++ b/developer/js/.npmignore @@ -2,5 +2,4 @@ build.sh source/* tests/* -*.js.map tsconfig.json diff --git a/developer/js/build.sh b/developer/js/build.sh index c804baef62d328b89509deeb364f746809d2e073..eccc7baf76d9a2cf743e7a5dd9623fe01770e975 100755 --- a/developer/js/build.sh +++ b/developer/js/build.sh @@ -6,12 +6,16 @@ # Exit on command failure and when using unset variables: set -eu -# Include some helper functions from resources -. ../../resources/shellHelperFunctions.sh +## START STANDARD BUILD SCRIPT INCLUDE +# adjust relative paths as necessary +THIS_SCRIPT="$(greadlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink -f "${BASH_SOURCE[0]}")" +. "$(dirname "$THIS_SCRIPT")/../../resources/build/build-utils.sh" +. "$KEYMAN_ROOT/resources/shellHelperFunctions.sh" +## END STANDARD BUILD SCRIPT INCLUDE EX_USAGE=64 # Where to find lexical model types. -LEXICAL_MODELS_TYPES=../../common/lexical-model-types +LEXICAL_MODELS_TYPES=../../common/models/types # Build the main script. @@ -51,9 +55,11 @@ while [[ $# -gt 0 ]] ; do display_usage exit ;; + -skip-package-install|-S) + install_dependencies=0 + ;; -test) run_tests=1 - install_dependencies=1 ;; -tdd) run_tests=1 @@ -130,10 +136,7 @@ type npm >/dev/null ||\ fail "Build environment setup error detected! Please ensure Node.js is installed!" if (( install_dependencies )) ; then - # Ensure that the local npm package can be require()'d. - (cd $LEXICAL_MODELS_TYPES && npm link .) || fail "Could not link lexical-model-types" - - npm install || fail "Could not download dependencies." + verify_npm_setup fi if [ -n "$publish_version" ]; then diff --git a/developer/js/libexec/create-override-script-regexp.ts b/developer/js/libexec/create-override-script-regexp.ts new file mode 100755 index 0000000000000000000000000000000000000000..7cc262282a36047bb3be88e704b9f07d33bc4262 --- /dev/null +++ b/developer/js/libexec/create-override-script-regexp.ts @@ -0,0 +1,145 @@ +#!/usr/bin/env npx ts-node + +/** + * Prints a JavaScript regular expression suitable for use in the + * **overrideScriptDefaults** word breaker decorator. + * + * This regular expression matches letters or marks in scripts that + * conventionally use spaces. This way, the word breaker can make sure to keep + * contiguous spans of these characters together! + * + * If you need to add more Unicode blocks, customize SPACELESS_SCRIPT_BLOCKS. + */ + +import {readFileSync} from "fs"; +import * as path from "path"; + +// Where to find UnicodeData.txt and Blocks.txt +const UCD_DIR = path.join("..", "..", "resources", "standards-data", "unicode-character-database"); + +const SPACELESS_SCRIPT_BLOCKS = new Set([ + "Myanmar", // a.k.a., Burmese + "Lao", + "Thai", + "Khmer", + "Katakana", + "Katakana Phonetic Extensions", + // Add more scripts here, as necessary! +]); + +let blockIter = blocks(); +let block = nextBlock(); + +let eligibleCharacters = []; + +// @ts-ignore: TypeScript complains that it can't compile for..of over a +// generator without --downlevelIteration, but it works anyway? +for (let {codePoint, generalCategory} of unicodeData()) { + if (!block.contains(codePoint)) { + block = nextBlock(); + } + console.assert(block.contains(codePoint)); + + if (SPACELESS_SCRIPT_BLOCKS.has(block.name) && isLetterOrMark(generalCategory)) { + eligibleCharacters.push(codePoint); + } +} + +const ranges = groupCodePointsIntoRanges(eligibleCharacters); + +const characterClasses = ranges.map(([lower, upper]) => { + if (lower === upper) { + return unicodeEscape(lower); + } else if (lower === upper - 1) { + return unicodeEscape(lower) + unicodeEscape(upper); + } else { + return `${unicodeEscape(lower)}-${unicodeEscape(upper)}`; + } +}).join(""); + +console.log(`/** + * AUTOMATICALLY GENERATED FILE. DO NOT MODIFY + * See: libexec/create-override-script-regexp.ts for details! + */ +export const HAS_SOUTHEAST_ASIAN_LETTER = /[${characterClasses}]/;`); + + +////////////////////////////////// Helpers /////////////////////////////////// + +function* unicodeData() { + let unicodeDataFile = readFileSync(path.join(UCD_DIR, "UnicodeData.txt"), "UTF-8"); + for (let line of unicodeDataFile.split("\n")) { + if (line.trim() == "") { + continue; + } + + let parts = line.split(";") + yield { + codePoint: parseInt(parts[0], 16), + generalCategory: parts[2], + } + } +} + +function* blocks() { + let blocksFile = readFileSync(path.join(UCD_DIR, "Blocks.txt"), "UTF-8"); + for (let line of blocksFile.split("\n")) { + if (line.trim() === "") { + continue; + } + if (line.startsWith("#")) { + continue; + } + + let [range, name] = line.split("; "); + let [lower, upper] = range.split("..").map(s => parseInt(s, 16)); + + yield { + name, lower, upper, + contains(codePoint: number) { + return lower <= codePoint && codePoint <= upper; + } + } + } +} + +function nextBlock() { + let {value} = blockIter.next(); + if (!value) { + throw new Error("ran out of blocks"); + } + return value; +} + +function isLetterOrMark(category: string): boolean { + return category.startsWith("L") || category.startsWith("M"); +} + +function groupCodePointsIntoRanges(characters: number[]): [number, number][] { + let ranges = []; + + let previousCharacter = characters[0]; + const candidates = characters.slice(1); + let currentRange: [number, number] = [previousCharacter, previousCharacter]; + for (let codePoint of candidates) { + if (codePoint === previousCharacter + 1) { + currentRange[1] = codePoint; + } else { + ranges.push(currentRange); + currentRange = [codePoint, codePoint]; + } + + previousCharacter = codePoint; + } + + return ranges; +} + +function unicodeEscape(codePoint: number) { + if (codePoint > 0xFFFF) { + throw new Error("non-BMP code points not supported"); + } + + let hex = codePoint.toString(16).toUpperCase().padStart(4,'0'); + return `\\u${hex}`; +} diff --git a/developer/js/package-lock.json b/developer/js/package-lock.json index 8dabb9e2ac02b0e2ee44d8f7cc79567fc2f2c115..b685b9fa65df0d44c32e7ead1b9c5eb3c6012a4a 100644 --- a/developer/js/package-lock.json +++ b/developer/js/package-lock.json @@ -1,6 +1,6 @@ { "name": "@keymanapp/lexical-model-compiler", - "version": "13.0.2500-alpha", + "version": "14.0.144", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -782,11 +782,6 @@ "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", "dev": true }, - "typescript": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.6.3.tgz", - "integrity": "sha512-N7bceJL1CtRQ2RiG0AQME13ksR7DiuQh/QehubYcghzv20tnh+MQnQIuJddTmsbqYj+dztchykemz0zFzlvdQw==" - }, "util.promisify": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/util.promisify/-/util.promisify-1.0.0.tgz", diff --git a/developer/js/package.json b/developer/js/package.json index 31b8ee6f30a9f5c1e581f1146a38aadb2560c5c6..378ddf5238a48e94ca92d51df61369ed14cfd5df 100644 --- a/developer/js/package.json +++ b/developer/js/package.json @@ -1,6 +1,6 @@ { "name": "@keymanapp/lexical-model-compiler", - "version": "13.0.2500-alpha", + "version": "14.0.144", "description": "Keyman Developer lexical model compiler", "keywords": [ "keyboard", @@ -12,7 +12,6 @@ "scripts": { "build": "tsc", "test": "mocha", - "install": "npm link @keymanapp/lexical-model-types", "prepublishOnly": "npm run build" }, "repository": { @@ -38,11 +37,14 @@ "node": ">=12.0.0" }, "dependencies": { + "@keymanapp/models-types": "^14.0.144", "commander": "^3.0.0", - "typescript": "^3.2.4", + "typescript": "^3.8.3", "xml2js": "^0.4.19" }, "devDependencies": { + "@keymanapp/models-templates": "^14.0.144", + "@keymanapp/models-wordbreakers": "^14.0.144", "@types/chai": "^4.1.7", "@types/mocha": "^5.2.7", "@types/node": "^10.14.6", diff --git a/developer/js/source/errors.ts b/developer/js/source/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..c84b790a985ac6451ef6445dc9a4bcd34e4fd295 --- /dev/null +++ b/developer/js/source/errors.ts @@ -0,0 +1,197 @@ +/** + * Log levels. + * + * Note: Currently, this acts like a bit set, where the upper 4 bits of an + * unsigned 16 bit value are the log level flags. + */ +export enum LogLevel { + CERR_FATAL = 0x8000, + CERR_ERROR = 0x4000, + CERR_WARNING = 0x2000, + // Note: 0x01000 is a memory error, but that is never raised in TypeScript + CERR_INFO = 0x0000, // N.B., not in widespread use +}; + +/** + * Error codes. Use these when logging messages. + * + * Extends https://github.com/keymanapp/keyman/blob/99db3c0d2448f448242e6397f9d72e9a7ccee4b9/windows/src/global/inc/Comperr.h + */ +export enum KeymanCompilerError { + CERR_LEXICAL_MODEL_MIN = 0x0800, + CERR_LEXICAL_MODEL_MAX = 0x08FF, + + + CERR_FATAL_LM = LogLevel.CERR_FATAL | CERR_LEXICAL_MODEL_MIN, + /* Place all fatal LM compiler errors here! */ + + CERR_ERROR_LM = LogLevel.CERR_ERROR | CERR_LEXICAL_MODEL_MIN, + /* Place all recoverable LM compiler errors here! */ + + CERR_WARN_LM = LogLevel.CERR_WARNING | CERR_LEXICAL_MODEL_MIN, + /* Place all LM compiler warnings here! */ + CWARN_MixedNormalizationForms = 0x2801, + CWARN_DuplicateWordInSameFile = 0x2802, + + /* Errors that are not specific to the lexical model compiler: */ + CWARN_TooManyErrorsOrWarnings = 0x20A7, +} + +/** + * Human-readable titles for the various log levels. + * + * Taken from https://github.com/keymanapp/keyman/blob/d83cfffe511ce65b781f919e89e3693146844849/windows/src/developer/TIKE/project/Keyman.Developer.System.Project.ProjectLog.pas#L39-L46 + */ +const LOG_LEVEL_TITLE: {[level in LogLevel]: string} = { + [LogLevel.CERR_INFO]: '', + [LogLevel.CERR_WARNING]: 'Warning', + [LogLevel.CERR_ERROR]: 'Error', + [LogLevel.CERR_FATAL]: 'Fatal Error', +}; + +/** + * How many errors or warnings are too many! + */ +export const MAX_MESSAGES = 100; + +/** + * Direct where log messages go. + */ +let _logHandler: (log: LogMessage) => void = printLogs; + +/** + * How many logs or warnings have been witnessed so far. + */ +let _messagesSeen = 0; + +/** + * Logs compiler messages (warnings, errors, logs). + * + * @param code Error code + * @param message A helpful message! + * @param source [optional] the filename/line number in the source that induced this error + * + * @see https://github.com/keymanapp/keyman/blob/99db3c0d2448f448242e6397f9d72e9a7ccee4b9/windows/src/developer/TIKE/project/Keyman.Developer.System.Project.ProjectLog.pas#L60-L77 + */ +export function log(code: KeymanCompilerError, message: string, source?: FilenameAndLineNo) { + // Ignore the request if there are too many messages + if (_messagesSeen > MAX_MESSAGES) + return; + + let logMessage = source + ? new LogMessageFromSource(code, message, source) + : new OrdinaryLogMessage(code, message); + + _logHandler(logMessage) + _messagesSeen++; + + if (_messagesSeen > MAX_MESSAGES) { + _logHandler(new OrdinaryLogMessage( + KeymanCompilerError.CWARN_TooManyErrorsOrWarnings, + `More than ${MAX_MESSAGES} warnings or errors received; suppressing further messages` + )); + } +} + +/** + * Override where log messages go. + * + * @param fn The desired log message handler. + */ +export function redirectLogMessagesTo(fn: (log: LogMessage) => void) { + _logHandler = fn; +} + +/** + * Reset the log message handler to the default. + */ +export function resetLogMessageHandler() { + _logHandler = printLogs; + _messagesSeen = 0; +} + +/** + * Prints log messages to stdout. The default log action. + */ +export function printLogs(log: LogMessage): void { + console.log(log.format()); +} + +/** + * Duct tapes together a filename and a line number of a log. + */ +interface FilenameAndLineNo { + readonly filename: string; + readonly lineno: number; +} + +/** + * A log message that knows how to format itself. + */ +export interface LogMessage { + readonly code: KeymanCompilerError; + readonly level: LogLevel; + readonly message: string; + + format(): string; +} + +/** + * Concrete implementation of the log message. + */ +class OrdinaryLogMessage implements LogMessage { + readonly code: KeymanCompilerError; + readonly message: string; + + constructor(code: KeymanCompilerError, message: string) { + this.code = code; + this.message = message; + } + + get level(): LogLevel { + return this.code & 0xF000; + } + + determineLogLevelTitle(): string { + return LOG_LEVEL_TITLE[this.level] || ''; + } + + format(): string { + let prefix = this.determineLogLevelTitle(); + if (prefix) + prefix = `${prefix}: `; + + return `${prefix}${h(this.code)} ${this.message}` + } +} + +/** + * A log message with a filename and line number. + */ +class LogMessageFromSource extends OrdinaryLogMessage { + readonly filename: string; + readonly lineno: number; + + constructor(code: KeymanCompilerError, message: string, source: FilenameAndLineNo) { + super(code, message); + this.filename = source.filename; + this.lineno = source.lineno; + } + + format(): string { + let originalMessage = super.format(); + return `${this.filename} (${this.lineno}): ${originalMessage}`; + } +} + +/** + * Format a number as a zero-padded 4 digit hexadecimal. + */ +function h(n: number) { + let formatted = n.toString(16).toUpperCase(); + if (formatted.length < 4) { + formatted = '0'.repeat(4 - formatted.length); + } + + return formatted; +} \ No newline at end of file diff --git a/developer/js/source/lexical-model-compiler/build-trie.ts b/developer/js/source/lexical-model-compiler/build-trie.ts index 2652e809e7e34257d3060e5e27b4b8db20b36aa7..2137b5c3d457a732c7ec9fb3dbc0a897fd475fb3 100644 --- a/developer/js/source/lexical-model-compiler/build-trie.ts +++ b/developer/js/source/lexical-model-compiler/build-trie.ts @@ -1,10 +1,17 @@ import { readFileSync } from "fs"; +import { log, KeymanCompilerError } from "../errors"; + +// Supports LF or CRLF line terminators. +const NEWLINE_SEPARATOR = /\u000d?\u000a/; /** - * A word list is an array of pairs: the concrete word form itself, followed by - * a non-negative count. + * A word list is (conceptually) an array of pairs: the concrete word form itself + a + * non-negative count. + * + * Since each word should only appear once within the list, we represent it with + * an associative array pattern keyed by the wordform. */ -type WordList = [string, number][]; +export type WordList = {[wordform: string]: number}; /** * Returns a data structure that can be loaded by the TrieModel. @@ -19,30 +26,43 @@ export function createTrieDataStructure(filenames: string[], searchTermToKey?: ( throw new TypeError("searchTermToKey must be explicitly specified") } // Make one big word list out of all of the filenames provided. - let wordlist = filenames - .map(parseWordListFromFilename) - .reduce((bigWordlist, current) => bigWordlist.concat(current), []); + let wordlist: WordList = {}; + filenames.forEach(filename => parseWordListFromFilename(wordlist, filename)); + let trie = Trie.buildTrie(wordlist, searchTermToKey as Trie.SearchTermToKey); return JSON.stringify(trie); } /** - * Parses a word list from its filename. - * + * Parses a word list from a file, merging duplicate entries. + * * The word list may be encoded in: - * + * * - UTF-8, with or without BOM [exported by most software] * - UTF-16, little endian, with BOM [exported by Microsoft Excel] - * + * + * @param wordlist word list to merge entries into (may have existing entries) + * @param filename filename of the word list + */ +export function parseWordListFromFilename(wordlist: WordList, filename: string): void { + _parseWordList(wordlist, new WordListFromFilename(filename)); +} + +/** + * Parses a word list from a string. The string should have multiple lines + * with LF or CRLF line terminators. + * + * @param wordlist word list to merge entries into (may have existing entries) * @param filename filename of the word list */ -export function parseWordListFromFilename(filename: string): WordList { - let contents = readFileSync(filename, detectEncoding(filename)); - return parseWordList(contents); +export function parseWordListFromContents(wordlist: WordList, contents: string): void { + _parseWordList(wordlist, new WordListFromMemory(contents)); } /** - * Reads a tab-separated values file into a word list. + * Reads a tab-separated values file into a word list. This function converts all + * entries into NFC and merges duplicate entries across wordlists. Duplication is + * on the basis of character-for-character equality after normalisation to NFC. * * Format specification: * @@ -60,20 +80,20 @@ export function parseWordListFromFilename(filename: string): WordList { * - column 2 (optional): the count: a non-negative integer specifying how many * times this entry has appeared in the corpus. Blank means 'indeterminate'. * - column 3 (optional): comment: an informative comment, ignored by the tool. + * + * @param wordlist word list to merge entries into (may have existing entries) + * @param contents contents of the file to import */ -export function parseWordList(contents: string): WordList { - // Supports LF or CRLF line terminators. - const NEWLINE_SEPARATOR = /\u000d?\u000a/; +function _parseWordList(wordlist: WordList, source: WordListSource): void { const TAB = "\t"; - // TODO: format validation. - let lines = contents.split(NEWLINE_SEPARATOR); - let result: WordList = []; - for (let line of lines) { + let wordsSeenInThisFile = new Set(); + + for (let [lineno, line] of source.lines()) { // Remove the byte-order mark (BOM) from the beginning of the string. // Because `contents` can be the concatenation of several files, we have to remove // the BOM from every possible start of file -- i.e., beginning of every line. - line = line.replace(/^\uFEFF/, ''); + line = line.replace(/^\uFEFF/, '').trim(); if (line.startsWith('#') || line === "") { continue; // skip comments and empty lines @@ -83,8 +103,20 @@ export function parseWordList(contents: string): WordList { let [wordform, countText] = line.split(TAB); // Clean the word form. - // TODO: what happens if we get duplicate forms? - wordform = wordform.normalize('NFC').trim(); + let original = wordform; + + wordform = wordform.normalize('NFC'); + if (original !== wordform) { + // Mixed normalization forms are yucky! Warn about it. + log( + KeymanCompilerError.CWARN_MixedNormalizationForms, + `“${wordform}” is not in Unicode NFC. Automatically converting to NFC.`, + {filename: source.name, lineno} + ) + } + + wordform = wordform.trim() + countText = (countText || '').trim(); let count = parseInt(countText, 10); @@ -94,9 +126,63 @@ export function parseWordList(contents: string): WordList { // Treat it like a hapax legonmenom -- it exist, but only once. count = 1; } - result.push([wordform, count]); + + if (wordsSeenInThisFile.has(wordform)) { + // The same word seen across multiple files is fine, + // but a word seen multiple times in one file is a problem! + log( + KeymanCompilerError.CWARN_DuplicateWordInSameFile, + `duplicate word “${wordform}” found in same file; summing counts`, + {filename: source.name, lineno} + ) + } + wordsSeenInThisFile.add(wordform); + + wordlist[wordform] = (wordlist[wordform] || 0) + count; } - return result; +} + +type LineNoAndText = [number, string]; + +interface WordListSource { + readonly name: string; + lines(): Iterable; +} + +class WordListFromMemory implements WordListSource { + readonly name = ''; + private readonly _contents: string; + + constructor(contents: string) { + this._contents = contents; + } + + *lines() { + yield *enumerateLines(this._contents.split(NEWLINE_SEPARATOR)); + } +} + +class WordListFromFilename { + readonly name: string; + constructor(filename: string) { + this.name = filename; + } + + *lines() { + let contents = readFileSync(this.name, detectEncoding(this.name)); + yield *enumerateLines(contents.split(NEWLINE_SEPARATOR)); + } +} + +/** + * Yields pairs of [lineno, line], given an Array of lines. + */ +function* enumerateLines(lines: string[]): Generator { + let i = 1; + for (let line of lines) { + yield [i, line]; + i++; + } } namespace Trie { @@ -227,7 +313,7 @@ namespace Trie { * @param words a list of word and count pairs. */ buildFromWordList(words: WordList): Trie { - for (let [wordform, weight] of words) { + for (let [wordform, weight] of Object.entries(words)) { let key = this.toKey(wordform); addUnsorted(this.root, { key, weight, content: wordform }, 0); } @@ -399,7 +485,7 @@ namespace Trie { * NFKD neutralizes some funky distinctions, e.g., ꬲ, e, e should all be the * same character; plus, it's an easy way to separate a Latin character from * its diacritics; Even then, orthographies regularly use code points - * that, under NFKD normalization, do NOT decompose appropriately for your + * that, under NFKD normalization, do NOT decompose appropriately for your * language (e.g., SENĆOŦEN, Plains Cree in syllabics). * * Use this in early iterations of the model. For a production lexical model, @@ -418,17 +504,17 @@ export function defaultSearchTermToKey(wordform: string): string { /** * Detects the encoding of a text file. - * + * * Supported encodings are: - * + * * - UTF-8, with or without BOM * - UTF-16, little endian, with BOM - * + * * UTF-16 in big endian is explicitly NOT supported! The reason is two-fold: * 1) Node does not support it without resorting to an external library (or * swapping every byte in the file!); and 2) I'm not sure anything actually * outputs in this format anyway! - * + * * @param filename filename of the file to detect encoding */ function detectEncoding(filename: string): 'utf8' | 'utf16le' { diff --git a/developer/js/source/lexical-model-compiler/join-word-breaker-decorator.ts b/developer/js/source/lexical-model-compiler/join-word-breaker-decorator.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e02ca891e38b0f80c485db1f3df618ffc3353e2 --- /dev/null +++ b/developer/js/source/lexical-model-compiler/join-word-breaker-decorator.ts @@ -0,0 +1,134 @@ +/// + +/** + * Returns a word breaker that joins spans of an existing word breaker. + * Spans are joined if they are connected by a delimiter. + * + * @param breaker The word breaker whose results will be decorated. + * @param joiners What delimiters should be used to join spans. + */ +export function decorateWithJoin(breaker: WordBreakingFunction, joiners: string[]): WordBreakingFunction { + // Make a copy so that if the original array is accidentally mutated, it + // won't affect the joiner. + const delimiters = joiners.concat(); + + return function (input: string): Span[] { + let originalSpans = breaker(input); + + // Implements a finite-state transducer (FST) where: + // - Transductions are pushed onto a stack + // - There are three states: + // - empty stack (initial state) + // - unjoined + // - joined + // - all three states are accepting states + // - there is NO backtracking on the input + // (hence the for-loop over the input tape) + // - each state is a JavaScript callback (function) + let state = emptyStack; + let stack: Span[] = []; + for (let span of originalSpans) { + state = state(span); + } + + return stack; + + /******************* States *******************/ + function emptyStack(span: Span) { + stack.push(span); + + if (isJoiner(span)) { + return joined; + } else { + return unjoined + } + } + + function unjoined(span: Span) { + // NB: stack has at least one span in it + if (isJoiner(span)) { + if (spansAreBackToBack(lastFrom(stack), span)) { + concatLastSpanInStackWith(span); + } else { + // Spans are non-contiguous, so don't join them! + stack.push(span); + } + return joined; + + } else { + // Span cannot be joined + stack.push(span); + return unjoined; + } + } + + function joined(span: Span) { + // NB: stack has at least one span in it + if (!spansAreBackToBack(lastFrom(stack), span)) { + // Spans are non-contiguous and cannot be joined: + stack.push(span); + return unjoined; + } + + // Spans are contiguous + concatLastSpanInStackWith(span); + if (isJoiner(span)) { + return joined; + } else { + return unjoined; + } + } + + /****************** Helpers ******************/ + function concatLastSpanInStackWith(span: Span) { + let lastIndex = stack.length - 1; + + let top = stack[lastIndex]; + let joinedSpan = concatenateSpans(top, span); + stack[lastIndex] = joinedSpan; + } + } + + function isJoiner(span: Span) { + return includes(delimiters, span.text); + } + + /** + * Returns true when the spans are contiguous. + * Order matters when calling this function! + */ + function spansAreBackToBack(former: Span, latter: Span): boolean { + return former.end === latter.start; + } + + function concatenateSpans(former: Span, latter: Span) { + if (latter.start !== former.end) { + throw new Error(`Cannot concatenate non-contiguous spans: ${JSON.stringify(former)}/${JSON.stringify(latter)}`); + } + + return { + start: former.start, + end: latter.end, + length: former.length + latter.length, + text: former.text + latter.text + }; + } + + /** + * When Array.prototype.include() doesn't exist: + */ + function includes(haystack: T[], needle: T): boolean { + for (let item of haystack) { + if (item === needle) + return true; + } + return false; + } + + /** + * Get the last element from the array. + */ + function lastFrom(array: T[]): T | undefined { + return array[array.length - 1]; + } +} diff --git a/developer/js/source/lexical-model-compiler/lexical-model-compiler.ts b/developer/js/source/lexical-model-compiler/lexical-model-compiler.ts index dbd5e9ce08204486b539a6b4305c73eba3507dc6..bcfaecea6f69e43ff2142eb70da5dfc960ce0dce 100644 --- a/developer/js/source/lexical-model-compiler/lexical-model-compiler.ts +++ b/developer/js/source/lexical-model-compiler/lexical-model-compiler.ts @@ -9,6 +9,8 @@ import * as ts from "typescript"; import * as fs from "fs"; import * as path from "path"; import { createTrieDataStructure, defaultSearchTermToKey } from "./build-trie"; +import {decorateWithJoin} from "./join-word-breaker-decorator"; +import {decorateWithScriptOverrides} from "./script-overrides-decorator"; export default class LexicalModelCompiler { @@ -93,11 +95,44 @@ export class ModelSourceError extends Error { * breaking function. */ function compileWordBreaker(spec: WordBreakerSpec): string { - if (typeof spec.use === "string") { + let wordBreakerCode = compileInnerWordBreaker(spec.use); + + if (spec.joinWordsAt) { + wordBreakerCode = compileJoinDecorator(spec, wordBreakerCode); + } + + if (spec.overrideScriptDefaults) { + wordBreakerCode = compileScriptOverrides(spec, wordBreakerCode); + } + + return wordBreakerCode; +} + +function compileJoinDecorator(spec: WordBreakerSpec, existingWordBreakerCode: string) { + // Bundle the source of the join decorator, as an IIFE, + // like this: (function join(breaker, joiners) {/*...*/}(breaker, joiners)) + // The decorator will run IMMEDIATELY when the model is loaded, + // by the LMLayer returning the decorated word breaker to the + // LMLayer model. + let joinerExpr: string = JSON.stringify(spec.joinWordsAt) + return `(${decorateWithJoin.toString()}(${existingWordBreakerCode}, ${joinerExpr}))`; +} + +function compileScriptOverrides(spec: WordBreakerSpec, existingWordBreakerCode: string) { + return `(${decorateWithScriptOverrides.toString()}(${existingWordBreakerCode}, '${spec.overrideScriptDefaults}'))`; +} + +/** + * Compiles the base word breaker, that may be decorated later. + * Returns the source code of a JavaScript expression. + */ +function compileInnerWordBreaker(spec: SimpleWordBreakerSpec): string { + if (typeof spec === "string") { // It must be a builtin word breaker, so just instantiate it. - return `wordBreakers['${spec.use}']`; + return `wordBreakers['${spec}']`; } else { - return spec.use.toString() + // It must be a function: + return spec.toString() // Note: the .toString() might just be the property name, but we want a // plain function: .replace(/^wordBreak(ing|er)\b/, 'function'); diff --git a/developer/js/source/lexical-model-compiler/lexical-model.ts b/developer/js/source/lexical-model-compiler/lexical-model.ts index b705ced2faa301a08849d1430eb1adb172bedda9..4d62462f22e4ee09accb51ae69029a37e2985ecc 100644 --- a/developer/js/source/lexical-model-compiler/lexical-model.ts +++ b/developer/js/source/lexical-model-compiler/lexical-model.ts @@ -2,7 +2,6 @@ * Interfaces and constants used by the lexical model compiler. These target * the LMLayer's internal worker code, so we provide those definitions too. */ -/// interface LexicalModelDeclaration { readonly format: 'trie-1.0'|'fst-foma-1.0'|'custom-1.0', @@ -14,16 +13,65 @@ interface LexicalModelDeclaration { * * Can support all old word breaking specification, * but can also be extended with options. + * + * @since 14.0 */ interface WordBreakerSpec { readonly use: SimpleWordBreakerSpec; + /** + * If present, joins words that were split by the word breaker + * together at the given strings. e.g., + * + * joinWordsAt: ['-'] // to keep hyphenated items together + * + * @since 14.0 + */ + readonly joinWordsAt?: string[]; + + /** + * Overrides word splitting behaviour for certain scripts. + * For example, specifing that spaces break words in certain South-East + * Asian scripts that otherwise do not use spaces. + * + * @since 14.0 + */ + readonly overrideScriptDefaults?: OverrideScriptDefaults; } /** - * Keyman 11.0+ word breaker specification: + * Simplified word breaker specification. + * + * @since 11.0 */ type SimpleWordBreakerSpec = 'default' | 'ascii' | WordBreakingFunction; +/** + * Override the default word breaking behaviour for some scripts. + * + * There is currently only one option: + * + * 'break-words-at-spaces' + * : some South-East Asian scripts conventionally do not use space or any + * explicit word boundary character to write word breaks. These scripts are: + * + * * Burmese + * * Khmer + * * Thai + * * Laos + * + * (this list may be incomplete and extended in the future) + * + * For these scripts, the default word breaker breaks at **every** + * letter/syllable/ideograph. However, in languages that use these scripts BUT + * use spaces (or some other delimier) as word breaks, enable + * 'break-words-at-spaces'; enabling 'break-words-at-spaces' prevents the word + * breaker from making too many breaks in these scripts. + * + * @since 14.0 + */ +type OverrideScriptDefaults = 'break-words-at-spaces'; + + interface LexicalModelSource extends LexicalModelDeclaration { readonly sources: Array; /** diff --git a/developer/js/source/lexical-model-compiler/script-overrides-decorator.ts b/developer/js/source/lexical-model-compiler/script-overrides-decorator.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a1685aa3fa475f61c131c4676fc4e154d8a2ad5 --- /dev/null +++ b/developer/js/source/lexical-model-compiler/script-overrides-decorator.ts @@ -0,0 +1,75 @@ +/// + +export function decorateWithScriptOverrides(breaker: WordBreakingFunction, option: OverrideScriptDefaults) { + if (option !== 'break-words-at-spaces') { + throw new Error(`Unsupported script override: ${option}`) + } + + /** + * Matches if when a span contains a Southeast-Asian letter or mark anywhere. + * This makes it a candidate for joining. + * + * See: libexec/create-override-script-regexp.ts for how this RegExp was + * generated. + * + * Last updated for Unicode 13.0.0. + */ + const HAS_SOUTHEAST_ASIAN_LETTER = /[\u0E01-\u0E3A\u0E40-\u0E4E\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0EDC-\u0EDF\u1000-\u103F\u1050-\u108F\u109A-\u109D\u1780-\u17D3\u17D7\u17DC\u17DD\u30A1-\u30FA\u30FC-\u30FF]/; + + return function enhancedBreaker(phrase: string): Span[] { + let originalSpans = breaker(phrase); + + if (originalSpans.length === 0) { + return []; + } + + let outputSpans = [originalSpans.shift()]; + for (let currentSpan of originalSpans) { + let previousSpan = lastFrom(outputSpans); + + if (spansAreBackToBack(previousSpan, currentSpan) && + hasSouthEastAsianLetter(previousSpan) && + hasSouthEastAsianLetter(currentSpan) + ) { + // previous span SHOULD be joined with current! + outputSpans[outputSpans.length - 1] = concatenateSpans(previousSpan, currentSpan); + } else { + outputSpans.push(currentSpan); + } + } + + return outputSpans; + } + + function hasSouthEastAsianLetter(span: Span) { + return HAS_SOUTHEAST_ASIAN_LETTER.test(span.text); + } + + /** + * Returns true when the spans are contiguous. + * Order matters when calling this function! + */ + function spansAreBackToBack(former: Span, latter: Span): boolean { + return former.end === latter.start; + } + + function concatenateSpans(former: Span, latter: Span) { + if (latter.start !== former.end) { + throw new Error(`Cannot concatenate non-contiguous spans: ${JSON.stringify(former)}/${JSON.stringify(latter)}`); + } + + return { + start: former.start, + end: latter.end, + length: former.length + latter.length, + text: former.text + latter.text + }; + } + + /** + * Get the last element from the array. + */ + function lastFrom(array: T[]): T | undefined { + return array[array.length - 1]; + } +} diff --git a/developer/js/tests/fixtures/example.qaa.joinwordbreaker/example.qaa.joinwordbreaker.model.ts b/developer/js/tests/fixtures/example.qaa.joinwordbreaker/example.qaa.joinwordbreaker.model.ts new file mode 100644 index 0000000000000000000000000000000000000000..985b9afea9e9af819a42fa38f746dfa32655fe39 --- /dev/null +++ b/developer/js/tests/fixtures/example.qaa.joinwordbreaker/example.qaa.joinwordbreaker.model.ts @@ -0,0 +1,10 @@ +const source: LexicalModelSource = { + format: 'trie-1.0', + sources: ['wordlist.tsv'], + /* Keyman 14.0+ word breaker specification: */ + wordBreaker: { + use: 'default', + joinWordsAt: [':', '-', '·'] + } +}; +export default source; diff --git a/developer/js/tests/fixtures/example.qaa.joinwordbreaker/wordlist.tsv b/developer/js/tests/fixtures/example.qaa.joinwordbreaker/wordlist.tsv new file mode 100644 index 0000000000000000000000000000000000000000..a0e3e97e3dbc4e38c1c6ea7e865dc748f7c532ec --- /dev/null +++ b/developer/js/tests/fixtures/example.qaa.joinwordbreaker/wordlist.tsv @@ -0,0 +1,3 @@ +Kanien'kehá:ka 1000 +amiskwaciy-wâskahikan 100 +cel·la 10 diff --git a/developer/js/tests/fixtures/example.qaa.scriptusesspaces/example.qaa.scriptusesspaces.model.ts b/developer/js/tests/fixtures/example.qaa.scriptusesspaces/example.qaa.scriptusesspaces.model.ts new file mode 100644 index 0000000000000000000000000000000000000000..76c08f1cc5bebde7dfc4d01b219b5c2e97443b15 --- /dev/null +++ b/developer/js/tests/fixtures/example.qaa.scriptusesspaces/example.qaa.scriptusesspaces.model.ts @@ -0,0 +1,10 @@ +const source: LexicalModelSource = { + format: 'trie-1.0', + sources: ['wordlist.tsv'], + /* Keyman 14.0+ word breaker specification: */ + wordBreaker: { + use: 'default', + overrideScriptDefaults: 'break-words-at-spaces', + } +}; +export default source; diff --git a/developer/js/tests/fixtures/example.qaa.scriptusesspaces/wordlist.tsv b/developer/js/tests/fixtures/example.qaa.scriptusesspaces/wordlist.tsv new file mode 100644 index 0000000000000000000000000000000000000000..87ce25c39a691b89a1df5d4ef58bf886f2ed4ee5 --- /dev/null +++ b/developer/js/tests/fixtures/example.qaa.scriptusesspaces/wordlist.tsv @@ -0,0 +1,8 @@ +ເກ໌າະ 675 +ເຢາະ 285 +ຢັອຫ 246 +ສນາ 99 +ບຣອມ 69 +ລະ 40 +ຈາກ 26 +ກ໌ນິ 26 diff --git a/developer/js/tests/helpers/index.ts b/developer/js/tests/helpers/index.ts index 10f2db822592789aaee4ca9853bba2e99eb85b1c..3719548037881fa10e54b06e0d170dfab6e87675 100644 --- a/developer/js/tests/helpers/index.ts +++ b/developer/js/tests/helpers/index.ts @@ -1,8 +1,11 @@ +/// + /** * Helpers and utilities for the Mocha tests. */ import * as path from 'path'; import {assert} from 'chai'; +import {LogMessage, KeymanCompilerError, redirectLogMessagesTo, resetLogMessageHandler, LogLevel} from '../../dist/errors'; export interface CompilationResult { hasSyntaxError: boolean; @@ -87,8 +90,27 @@ export function compileModelSourceCode(code: string) { } }); + // We expect the compiled model to reach into the `wordBreaker` namespace, + // and maybe get a function. Problem is, we don't know + // what functions are available! + // This proxy allows us to intercept + // wordBreakers.* + // meaning that when the compiled code tries to do this: + // + // wordBreaker["someWordBreaker"] + // + // ...we can intercept the name "someWordBreaker". + let wordBreakerNamespace = new Proxy({}, { + get(_target, property) { + if (typeof property !== 'string') + throw new Error(`Don't know how to handle non-string property: ${String(property)}`); + return function dummyWordBreaker() { + } + } + }); + try { - module(fakeLMLayerWorker, modelsNamespace, {}); + module(fakeLMLayerWorker, modelsNamespace, wordBreakerNamespace); } catch (err) { error = err; } @@ -98,6 +120,64 @@ export function compileModelSourceCode(code: string) { }; } +/** + * Enables one to query log messages after they have been logged. + */ +export class LogHoarder { + private messages: LogMessage[] = []; + + /** + * Get rid of all log messages seen. + */ + clear() { + this.messages = []; + } + + /** + * Hoards a log message for later perusal. + */ + handleLog(log: LogMessage) { + this.messages.push(log); + } + + /** + * Has an error message with this code been witnessed? + */ + hasSeenCode(code: KeymanCompilerError): boolean { + return Boolean(this.messages.find(log => log.code === code)); + } + + /** + * Have any warnings been logged? + */ + hasSeenWarnings(): boolean { + return this.messages + .filter(log => log.level === LogLevel.CERR_WARNING) + .length > 0; + } + + /** + * Overrides the global log handler, allowing one to browse log messages + * later. + * + * Remember to uninstall the log handler afterwards! + */ + install(): this { + redirectLogMessagesTo(this.handleLog.bind(this)); + return this; + } + + /** + * Return the log message handler to its default. + * + * Note: You MUST uninstall the hoarder after use! + * It's recommended you put this in an afterEach() callback. + */ + uninstall() { + resetLogMessageHandler() + } +} + type ModuleType = (a: LMLayerWorker, b: ModelsNamespace, c: WordBreakersNamespace) => any; interface LMLayerWorker { loadModel(model: object): void; diff --git a/developer/js/tests/test-compile-model.ts b/developer/js/tests/test-compile-model.ts index 40be060cca17a4771166a006cb17a3e03a339ba7..9003ac133039773eb9361056bbd71683bea2f269 100644 --- a/developer/js/tests/test-compile-model.ts +++ b/developer/js/tests/test-compile-model.ts @@ -10,7 +10,9 @@ describe('compileModel', function () { 'example.qaa.sencoten', 'example.qaa.trivial', 'example.qaa.utf16le', - 'example.qaa.wordbreaker' + 'example.qaa.wordbreaker', + 'example.qaa.joinwordbreaker', + 'example.qaa.scriptusesspaces', ]; for (let modelID of MODELS) { diff --git a/developer/js/tests/test-error-logger.ts b/developer/js/tests/test-error-logger.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad0a3cbadbca20f579a351f1723f383c2b09a696 --- /dev/null +++ b/developer/js/tests/test-error-logger.ts @@ -0,0 +1,38 @@ +import { MAX_MESSAGES, KeymanCompilerError, log } from "../dist/errors" +import { LogHoarder } from "./helpers" +import { assert } from "chai" + +describe('error logger', function () { + beforeEach(function () { + this.logHoarder = (new LogHoarder).install() + }) + + afterEach(function () { + this.logHoarder.uninstall(); + delete this.logHoarder; + }) + + it('should stop logging messages **after** a maximum', function () { + for (let i = 0; i < MAX_MESSAGES; i++) { + log(KeymanCompilerError.CWARN_DuplicateWordInSameFile, "fake error"); + } + + // We've logged *just enough messages. This error should not be found: + assert.isFalse(this.logHoarder.hasSeenCode( + KeymanCompilerError.CWARN_TooManyErrorsOrWarnings + )); + + // Log just one too many: + log(KeymanCompilerError.CWARN_DuplicateWordInSameFile, "fake error"); + + assert.isTrue(this.logHoarder.hasSeenCode( + KeymanCompilerError.CWARN_TooManyErrorsOrWarnings + )); + + // Log a DIFFERENT error -- it should not appear in the log + log(KeymanCompilerError.CWARN_MixedNormalizationForms, "fake error"); + assert.isFalse(this.logHoarder.hasSeenCode( + KeymanCompilerError.CWARN_MixedNormalizationForms + )); + }) +}) \ No newline at end of file diff --git a/developer/js/tests/test-join-word-breaker.ts b/developer/js/tests/test-join-word-breaker.ts new file mode 100644 index 0000000000000000000000000000000000000000..c46c4a2d6a93560e87ad2b47550dcaf8f7805bcf --- /dev/null +++ b/developer/js/tests/test-join-word-breaker.ts @@ -0,0 +1,99 @@ +var assert = require('chai').assert; + +const defaultWordBreaker = require('@keymanapp/models-wordbreakers').wordBreakers['default']; +import {decorateWithJoin} from '../dist/lexical-model-compiler/join-word-breaker-decorator'; + + +describe('The join word breaker decorator', function () { + it('should decorate an existing word breaker', function () { + let breakWords = decorateWithJoin(defaultWordBreaker, ['-']); + assert.isFunction(breakWords); + }); + + const TEST_CASES: [string, string[], string[], string[]][] = [ + /* input, joiners, default breaks, breaks with joins */ + // Original test case from https://github.com/keymanapp/keyman/issues/2753 + ['khui-chhùi', ['-'], ["khui", "-", "chhùi"], ["khui-chhùi"]], + + // Plains Cree SRO: + ['ê-kotiskâwêyâhk', ['-'], ['ê', '-', 'kotiskâwêyâhk'], ['ê-kotiskâwêyâhk']], + + // Edge cases: + + // Joiner alone: + ['-', ['-'], ['-'], ['-']], + // Joiner at the end: + ['ni-', ['-'], ['ni', '-'], ['ni-']], + // Joiner at the end: + ['-ân', ['-'], ['-', 'ân'], ['-ân']], + + // This was my guiding test case: + [ + "-yâhk ê-nitawi-kotiskâwêyâhk ni-", + ["-"], + ["-", "yâhk", "ê", "-", "nitawi", "-", "kotiskâwêyâhk", "ni", "-"], + ["-yâhk", "ê-nitawi-kotiskâwêyâhk", "ni-"] + ], + + // Do not perform any joins: + ["hello world", ["-"], ["hello", "world"], ["hello", "world"]], + + // Joining using multiple joiners + [ + "Email: no-body@example.com", + ["@", "-"], + ["Email", ":", "no", "-", "body", "@", "example.com"], + ["Email", ":", "no-body@example.com"] + ], + + // Joining with two or more joiners in a row + [ + "nobody@@example.com", + ["@"], + ["nobody", "@", "@", "example.com"], + ["nobody@@example.com"] + ], + + // it should NOT join non-contiguous spans: + [ + "this- is -bad", + ["-"], + ["this", "-", "is", "-", "bad"], + ["this-", "is", "-bad"] + ], + + // different but adjacent joiners + [ + "I made the kawé:-conjugator.", + ["-", ":"], + ["I", "made", "the", "kawé", ":", "-", "conjugator", "."], + ["I", "made", "the", "kawé:-conjugator", "."] + ], + + // 3+ joiners in a row + [ + // NB: – is U+2001 EN DASH + "This language is nut–=💠¤~ty!", + ["~", "–", "¤", "=", "💠"], + ["This", "language", "is", "nut", "–", "=", "💠", "¤", "~", "ty", "!"], + ["This", "language", "is", "nut–=💠¤~ty", "!"], + ], + ] + + for (let [phrase, joiners, unjoined, expected] of TEST_CASES) { + it(`should break «${[phrase]}» as [${expected.join(' ;; ')}]`, function () { + let breakWords = decorateWithJoin(defaultWordBreaker, joiners); + let unjoinedResult = defaultWordBreaker(phrase).map(onlyText); + assert.deepEqual(unjoinedResult, unjoined); + let actualResult = breakWords(phrase).map(onlyText); + assert.deepEqual(actualResult, expected); + }); + } + + /** + * Get just the text from a span. + */ + function onlyText(span: Span) { + return span.text; + } +}); diff --git a/developer/js/tests/test-override-script-defaults.ts b/developer/js/tests/test-override-script-defaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..42d58a064b076d363e9c99b1b0a5fb41c50e4ff6 --- /dev/null +++ b/developer/js/tests/test-override-script-defaults.ts @@ -0,0 +1,34 @@ +var assert = require('chai').assert; + +const defaultWordBreaker = require('@keymanapp/models-wordbreakers').wordBreakers['default']; +import {decorateWithScriptOverrides} from '../dist/lexical-model-compiler/script-overrides-decorator'; + +const THIN_SPACE = "\u2009"; + +describe('The script overrides word breaker decorator', function () { + it('should decorate an existing word breaker', function () { + let breakWords = decorateWithScriptOverrides(defaultWordBreaker, 'break-words-at-spaces') + assert.isFunction(breakWords); + }); + + // I do not read this script or language so I have NO idea what this says + // ¯\_(ツ)_/¯ + const phraseComponents = ["ຈາກ", THIN_SPACE, "ກ໌ນິ", THIN_SPACE, "ສນາ", THIN_SPACE, "ເກ໌າະ", THIN_SPACE, "ຢັອຫ", THIN_SPACE, "ລະ", THIN_SPACE, "ບຣອມ", THIN_SPACE, "ເຢາະ", ","]; + const phraseSpans = phraseComponents.filter(span => span !== THIN_SPACE); + const phrase = phraseComponents.join(""); + const expectedNumSpans = phraseSpans.length; + + it(`should break «${[phrase]}» as ${expectedNumSpans} spans`, function () { + let breakWords = decorateWithScriptOverrides(defaultWordBreaker, 'break-words-at-spaces'); + let defaultResult = defaultWordBreaker(phrase); + + assert.isAbove(defaultResult.length, expectedNumSpans); + let actualResult = breakWords(phrase); + assert.lengthOf(actualResult, expectedNumSpans); + assert.deepEqual(actualResult.map(grabText), phraseSpans); + }); + + function grabText(span: Span) { + return span.text; + } +}); diff --git a/developer/js/tests/test-parse-wordlist.ts b/developer/js/tests/test-parse-wordlist.ts index 66297d63ed8a1f06c7905ebadcb33ae7756b871a..3d0c7a565b1c839538335537064036dd7432b684 100644 --- a/developer/js/tests/test-parse-wordlist.ts +++ b/developer/js/tests/test-parse-wordlist.ts @@ -1,57 +1,127 @@ -import {parseWordList, parseWordListFromFilename} from '../dist/lexical-model-compiler/build-trie'; +import {parseWordListFromContents, parseWordListFromFilename, WordList} from '../dist/lexical-model-compiler/build-trie'; import {assert} from 'chai'; import 'mocha'; -import { makePathToFixture } from './helpers'; +import { makePathToFixture, LogHoarder } from './helpers'; +import { KeymanCompilerError } from '../dist/errors'; const BOM = '\ufeff'; -const SENCOTEN_WORDLIST = [ - ['TŦE', 13644], - ['E', 9134], - ['SEN', 4816], - ['Ȼ', 3479], - ['SW̱', 2621], - ['NIȽ', 2314], - ['U¸', 2298], - ['I¸', 1988], - ['ȻSE', 1925], - ['I', 1884] -]; - -describe('parseWordList', function () { +const SENCOTEN_WORDLIST = { + 'TŦE': 13644, + 'E': 9134, + 'SEN': 4816, + 'Ȼ': 3479, + 'SW̱': 2621, + 'NIȽ': 2314, + 'U¸': 2298, + 'I¸': 1988, + 'ȻSE': 1925, + 'I': 1884 +}; + +describe('parsing a word list', function () { + beforeEach(function () { + this.logHoarder = (new LogHoarder).install() + }) + + afterEach(function () { + this.logHoarder.uninstall(); + delete this.logHoarder; + }) + it('should remove the UTF-8 byte order mark from files', function () { let word = 'hello'; let count = 1; - let expected = [ - [word, count] - ]; + let expected: WordList = {}; + expected[word] = count; + let file = `# this is a comment\n${word}\t${count}`; - let withoutBOM = parseWordList(file); + let withoutBOM: WordList = {}; + parseWordListFromContents(withoutBOM, file); assert.deepEqual(withoutBOM, expected, "expected regular file to parse properly"); - let withBOM = parseWordList(`${BOM}${file}`) + assert.isFalse(this.logHoarder.hasSeenWarnings()); + + let withBOM: WordList = {}; + parseWordListFromContents(withBOM, `${BOM}${file}`) assert.deepEqual(withBOM, expected, "expected BOM to be ignored"); + assert.isFalse(this.logHoarder.hasSeenWarnings()); }); it('should read word lists in UTF-8', function () { // N.B.: this is the format exported by Google Drive when selecting "TSV". const filename = makePathToFixture('example.qaa.sencoten', 'wordlist.tsv'); - let wordlist = parseWordListFromFilename(filename); + let wordlist: WordList = {}; + parseWordListFromFilename(wordlist, filename); + assert.deepEqual(wordlist, SENCOTEN_WORDLIST); + assert.isFalse(this.logHoarder.hasSeenWarnings()); }); it('should read word lists in UTF-16 little-endian (with BOM)', function () { // N.B.: this is the format exported by MS Excel when selecting // "UTF-16" text (tested on Excel for macOS). const filename = makePathToFixture('example.qaa.utf16le', 'wordlist.txt'); - let wordlist = parseWordListFromFilename(filename); + let wordlist: WordList = {}; + parseWordListFromFilename(wordlist, filename); + assert.deepEqual(wordlist, SENCOTEN_WORDLIST); + assert.isFalse(this.logHoarder.hasSeenWarnings()); }); it('should NOT read word lists in UTF-16 big-endian (with BOM)', function () { // N.B.: Does anything output this format...? const filename = makePathToFixture('example.qaa.utf16be', 'wordlist.txt'); + let wordlist: WordList = {}; assert.throws(() => { - parseWordListFromFilename(filename); + parseWordListFromFilename(wordlist, filename); }, 'UTF-16BE is unsupported'); }); -}); + it('should merge duplicate entries in a wordlist', function () { + // Tests that we merge NFC+NFD entries and identical entries, trimming whitespace + // Note building the wordlist from an array to make clear that we have unnormalised inputs + const words = [ + 'hello', //1 + 'hello\u0301', //2, NFD helló + 'hell\u00f3', //3, NFC helló + ' hello ', //4, expect to trim whitespace + 'hello']; //5 + + const expected: WordList = { + 'hello': 10, /* 1+4+5 trimmed and identical */ + 'hell\u00f3': 5, /* 2+3 normalised to NFC */ + }; + + // Build a wordlist from the array + let file = `# this is a comment\n`; + for(let i = 0; i < words.length; i++) { + file += `${words[i]}\t${i+1}\n`; + } + let repeatedWords: WordList = {}; + parseWordListFromContents(repeatedWords, file); + + assert.deepEqual(repeatedWords, expected); + + assert.isTrue(this.logHoarder.hasSeenWarnings()); + // hello has been seen multiple times: + assert.isTrue(this.logHoarder.hasSeenCode(KeymanCompilerError.CWARN_DuplicateWordInSameFile)); + // helló and hello + U+0301 have both been seen: + assert.isTrue(this.logHoarder.hasSeenCode(KeymanCompilerError.CWARN_MixedNormalizationForms)); + + // Let's parse another file: + + this.logHoarder.clear(); + // Now, parse a DIFFERENT file, but with an NFD entry. + parseWordListFromContents(repeatedWords, "hello\u0301\t5\n"); + assert.isTrue(this.logHoarder.hasSeenWarnings()) + // hello + U+0301 (NFD) has been seen, but... + assert.isTrue(this.logHoarder.hasSeenCode(KeymanCompilerError.CWARN_MixedNormalizationForms)); + // BUT! We have not seen a duplicate **within the same file** + assert.isFalse(this.logHoarder.hasSeenCode(KeymanCompilerError.CWARN_DuplicateWordInSameFile)); + + assert.deepEqual(repeatedWords, { + hello: expected['hello'], + // should have seen more of this entry: + "hell\u00f3": expected["hell\u00f3"] + 5, + }); + }); +}); diff --git a/docs/npm-packages.md b/docs/npm-packages.md index b16a5f6deaf533c58c621a4de968709d180847d6..207499af99c1bd8c97dc13eb06aa0c36cbe1f079 100644 --- a/docs/npm-packages.md +++ b/docs/npm-packages.md @@ -12,7 +12,7 @@ Packages are **never** published from a developer's machine. List of current npm packages ---------------------------- - * `@keymanapp/lexical-model-types` -- located at `common/lexical-model-types` + * `@keymanapp/models-types` -- located at `common/models-types` * `@keymanapp/lexical-model-compiler` -- located at `developer/js` For CI developers diff --git a/docs/settings/README.md b/docs/settings/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7fee4d58cae4a37f2c559c6e4b6109a427354ca2 --- /dev/null +++ b/docs/settings/README.md @@ -0,0 +1,8 @@ +# Settings directory + +The subdirectories here contain settings files for VSCode that might be helpful to get started. + +## Usage + +Create a `.vscode` subdirectory in the root `keyman` source directory (i.e. in `../..`) and copy +the relevant settings files there. diff --git a/docs/settings/linux/c_cpp_properties.json b/docs/settings/linux/c_cpp_properties.json new file mode 100644 index 0000000000000000000000000000000000000000..13ff111c62975de6f8fbbfe4dc5d2e6535e10df4 --- /dev/null +++ b/docs/settings/linux/c_cpp_properties.json @@ -0,0 +1,17 @@ +{ + "configurations": [ + { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [], + "compilerPath": "/usr/lib/ccache/clang", + "cStandard": "c11", + "cppStandard": "c++14", + "intelliSenseMode": "clang-x64", + "compileCommands": "${workspaceFolder}/linux/keyboardprocessor/compile_commands.json" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/docs/settings/linux/extensions.json b/docs/settings/linux/extensions.json new file mode 100644 index 0000000000000000000000000000000000000000..c03958b519b2c52df9000560b8f7fb7b73d9d405 --- /dev/null +++ b/docs/settings/linux/extensions.json @@ -0,0 +1,9 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "asabil.meson", + "EditorConfig.editorconfig", + "ms-python.python", + ] +} diff --git a/docs/settings/linux/launch.json b/docs/settings/linux/launch.json new file mode 100644 index 0000000000000000000000000000000000000000..e3fcde5bbac9b1d0c7b906d0a8abc4f8a1b53d56 --- /dev/null +++ b/docs/settings/linux/launch.json @@ -0,0 +1,23 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Current File", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal" + }, + { + "name": "km-config", + "type": "python", + "request": "launch", + "program": "linux/keyman-config/km-config", + "cwd": "${workspaceFolder}", + "console": "integratedTerminal" + } + ] +} diff --git a/docs/settings/linux/settings.json b/docs/settings/linux/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..1476b35a91d28cb725d2bac8c743fb24ba840ce3 --- /dev/null +++ b/docs/settings/linux/settings.json @@ -0,0 +1,17 @@ +{ + // Settings for keyman-config unit tests. You'll have to change these if you want + // to run other tests. + "python.envFile": "${workspaceFolder}/linux/keyman-config/tests/python.env", + "python.testing.unittestArgs": [ + "-v", + "-s", "linux/keyman-config/tests", + "-p", "test_*.py" + ], + "python.testing.unittestEnabled": true, + "python.testing.pytestEnabled": false, + "python.testing.nosetestsEnabled": false, + "python.linting.enabled": true, + // We use flake8 for Python linting - install with `pip3 install flake8` + "python.linting.flake8Enabled": true, + "python.pythonPath": "/usr/bin/python3" +} diff --git a/ios/.gitignore b/ios/.gitignore index a722c278c9b15c2257313f649b6268180aa4d1dc..2f451173f78d00535b21f32f54abd4887bb73600 100644 --- a/ios/.gitignore +++ b/ios/.gitignore @@ -13,9 +13,13 @@ engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/keymanios.js engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/keymanweb-osk.ttf engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/kmwosk.css engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/keyman.js.map +engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/keyman-sentry.js Keyman 2* Carthage # Explicitly ignores just the SWKeyboard scheme; testing against different # targets makes a lot of noise. -**/SWKeyboard.scheme \ No newline at end of file +**/SWKeyboard.scheme + +# Ignores exported localization files. +en.xcloc \ No newline at end of file diff --git a/ios/README.md b/ios/README.md index cef19ed90560a99c9cb16027da50f592c02d8840..107ce7725d63d68341b1974a8986220f96d82347 100644 --- a/ios/README.md +++ b/ios/README.md @@ -7,7 +7,8 @@ * Carthage (`brew install carthage`) * [Node.js](https://nodejs.org/) 8.9+ (for building KeymanWeb) * Coreutils (`brew install coreutils`) -* sentry-cli (`brew install getsentry/tools/sentry-cli) to utilize Sentry-based error reporting +* sentry-cli (`brew install getsentry/tools/sentry-cli`) to utilize Sentry-based error reporting +* jq (`brew install jq`) ## Keyman App @@ -61,7 +62,7 @@ To build in Xcode, The framework will be built to **engine/KMEI/build/(Debug|Release)-universal/KeymanEngine.framework**. If it doesn't build, and you have upgraded from Xcode 10.0 (or earlier) to 10.1 (or later), it may not -build due to "Could not find any available simulators for iOS" error from Carthage, probably while +build due to "Could not find any available simulators for iOS" error from Carthage, probably while building DeviceKit. Xcode 10.1 changed the output format which confuses Carthage. Upgrade Carthage: ``` brew upgrade carthage diff --git a/ios/crowdin.yml b/ios/crowdin.yml deleted file mode 100644 index 30c139fd6dbff6d9c64ef894675d7057fdc50e87..0000000000000000000000000000000000000000 --- a/ios/crowdin.yml +++ /dev/null @@ -1,151 +0,0 @@ -# -# Your Crowdin credentials -# -project_id_env: "CROWDIN_PROJECT_ID" -api_token_env: "CROWDIN_PERSONAL_TOKEN" -base_path: . # local base path -base_url: https://api.crowdin.com - -# -# Choose file structure in Crowdin -# e.g. true or false -# -preserve_hierarchy: true - -# -# Files configuration -# -files: - # source: local path of file that gets uploaded to crowdin - # dest: crowdin path in https://crowdin.com/project/keyman - # translation: local path where downloaded translations from crowdin go - - # iOS files - - source: /engine/KMEI/KeymanEngine/Classes/LanguagePicker/en.lproj/ResourceInfoView.strings - dest: /ios/KMEI/LanguagePicker/ResourceInfoView.strings - translation: /engine/KMEI/KeymanEngine/Classes/LanguagePicker/%osx_code%/%original_file_name% - - - source: /engine/KMEI/KeymanEngine/en.lproj/Localizable.strings - dest: /ios/KMEI/Localizable.strings - translation: /engine/KMEI/KeymanEngine/%osx_code%/%original_file_name% - - - source: /keyman/Keyman/Keyman/en.lproj/Localizable.strings - dest: /ios/keyman/Localizable.strings - translation: /keyman/Keyman/Keyman/%osx_code%/%original_file_name% - - # crowdin parameters descriptions: - - # - # Source files filter - # e.g. "/resources/en/*.json" - # - - # - # Where translations will be placed - # e.g. "/resources/%two_letters_code%/%original_file_name%" - # - #"translation" : "", - - # - # Files or directories for ignore - # e.g. ["/**/?.txt", "/**/[0-9].txt", "/**/*\?*.txt"] - # - #"ignore" : [], - - # - # The dest allows you to specify a file name in Crowdin - # e.g. "/messages.json" - # - #"dest" : "", - - # - # File type - # e.g. "json" - # - #"type" : "", - - # - # The parameter "update_option" is optional. If it is not set, after the files update the translations for changed strings will be removed. Use to fix typos and for minor changes in the source strings - # e.g. "update_as_unapproved" or "update_without_changes" - # - #"update_option" : "", - - # - # Start block (for XML only) - # - - # - # Defines whether to translate tags attributes. - # e.g. 0 or 1 (Default is 1) - # - # "translate_attributes" : 1, - - # - # Defines whether to translate texts placed inside the tags. - # e.g. 0 or 1 (Default is 1) - # - # "translate_content" : 1, - - # - # This is an array of strings, where each item is the XPaths to DOM element that should be imported - # e.g. ["/content/text", "/content/text[@value]"] - # - # "translatable_elements" : [], - - # - # Defines whether to split long texts into smaller text segments - # e.g. 0 or 1 (Default is 1) - # - # "content_segmentation" : 1, - - # - # End block (for XML only) - # - - # - # Start .properties block - # - - # - # Defines whether single quote should be escaped by another single quote or backslash in exported translations - # e.g. 0 or 1 or 2 or 3 (Default is 3) - # 0 - do not escape single quote; - # 1 - escape single quote by another single quote; - # 2 - escape single quote by backslash; - # 3 - escape single quote by another single quote only in strings containing variables ( {0} ). - # - # "escape_quotes" : 3, - - # - # Defines whether any special characters (=, :, ! and #) should be escaped by backslash in exported translations. - # e.g. 0 or 1 (Default is 0) - # 0 - do not escape special characters - # 1 - escape special characters by a backslash - # - # "escape_special_characters": 0 - # - - # - # End .properties block - # - - # - # Often software projects have custom names for the directories where translations are placed. crowdin-cli allows you to map your own languages to be understandable by Crowdin. - # - #"languages_mapping" : { - # "two_letters_code" : { - # "crowdin_language_code" : "local_name" - # } - #}, - - # - # Does the first line contain header? - # e.g. true or false - # - #"first_line_contains_header" : true, - - # - # for spreadsheets - # e.g. "identifier,source_phrase,context,uk,ru,fr" - # - # "scheme" : "", diff --git a/ios/engine/KMEI/KeymanEngine.xcodeproj/project.pbxproj b/ios/engine/KMEI/KeymanEngine.xcodeproj/project.pbxproj index ccecf50246b26bc6de8725e9158ec3737f2030fa..3f043a9fe3c0f85ce6b96cf6bf9dcfa158586abf 100644 --- a/ios/engine/KMEI/KeymanEngine.xcodeproj/project.pbxproj +++ b/ios/engine/KMEI/KeymanEngine.xcodeproj/project.pbxproj @@ -49,13 +49,9 @@ 9A0FCA0922D7C58B00D33F86 /* Keyman.bundle in Resources */ = {isa = PBXBuildFile; fileRef = F27FCB51157FE3CE00FBBA20 /* Keyman.bundle */; }; 9A3B14D2229370B20052A11F /* InstalledLanguagesViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A3B14D1229370B20052A11F /* InstalledLanguagesViewController.swift */; }; 9A3E832522EAC14A00D22D2A /* KeyboardSwitcherViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A3E832422EAC14A00D22D2A /* KeyboardSwitcherViewController.swift */; }; - 9A4609972241B39B00B0BFD1 /* LexicalModelInfoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A4609962241B39B00B0BFD1 /* LexicalModelInfoViewController.swift */; }; 9A4609992242047400B0BFD1 /* LexicalModelAPICall.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A4609982242047400B0BFD1 /* LexicalModelAPICall.swift */; }; 9A60764422893A4E003BCFBA /* SettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A60764322893A4E003BCFBA /* SettingsViewController.swift */; }; 9A9CB08022416E5400231FB9 /* LexicalModelPickerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A9CB07F22416E5400231FB9 /* LexicalModelPickerViewController.swift */; }; - 9A9CB0822241704800231FB9 /* APILexicalModelRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A9CB0812241704800231FB9 /* APILexicalModelRepository.swift */; }; - 9A9CB084224170F700231FB9 /* LexicalModelRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A9CB083224170F700231FB9 /* LexicalModelRepository.swift */; }; - 9A9CB0862241717C00231FB9 /* LexicalModelRepositoryDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A9CB0852241717C00231FB9 /* LexicalModelRepositoryDelegate.swift */; }; 9AD4F53C229F85AC007992D3 /* LanguageSettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD4F53A229F85AC007992D3 /* LanguageSettingsViewController.swift */; }; 9AD4F53D229F85AC007992D3 /* LanguageSettingsViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9AD4F53B229F85AC007992D3 /* LanguageSettingsViewController.xib */; }; 9AD4F53F22A8A286007992D3 /* LanguageSettingsViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9AD4F53B229F85AC007992D3 /* LanguageSettingsViewController.xib */; }; @@ -87,7 +83,6 @@ C059FCBD1FD9266C00BD1A64 /* XCGLogger.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1687ACCC1FD8DE5300926D69 /* XCGLogger.framework */; }; C059FCBE1FD9266C00BD1A64 /* Zip.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 165C8B8B1FD8220600D4A78D /* Zip.framework */; }; C05B14331FD914870082A316 /* Log.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05B14321FD914870082A316 /* Log.swift */; }; - C05F432D1FBD5A4C0058CBD4 /* KeyboardAPICall.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05F432C1FBD5A4C0058CBD4 /* KeyboardAPICall.swift */; }; C05F43311FBD62550058CBD4 /* JSONDecoder.DateDecodingStrategy+ISO8601Fallback.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05F43301FBD62550058CBD4 /* JSONDecoder.DateDecodingStrategy+ISO8601Fallback.swift */; }; C06085B41F9485E40057E5B9 /* UIButton+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = C06085B31F9485E40057E5B9 /* UIButton+Helpers.swift */; }; C06D372F1F81F4E100F61AE0 /* KeymanEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = C06D372D1F81F4E100F61AE0 /* KeymanEngine.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -110,9 +105,6 @@ C07705DE1FD8ED9E00D2F3C7 /* ObjcExceptionBridging.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 1687ACCD1FD8DE5300926D69 /* ObjcExceptionBridging.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; C07705DF1FD8ED9E00D2F3C7 /* XCGLogger.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1687ACCC1FD8DE5300926D69 /* XCGLogger.framework */; }; C07705E01FD8ED9E00D2F3C7 /* XCGLogger.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 1687ACCC1FD8DE5300926D69 /* XCGLogger.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - C07A9D8A1FD1762700828ADD /* KeyboardRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = C07A9D891FD1762700828ADD /* KeyboardRepository.swift */; }; - C07A9D8C1FD176AB00828ADD /* KeyboardRepositoryDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C07A9D8B1FD176AB00828ADD /* KeyboardRepositoryDelegate.swift */; }; - C07A9D8E1FD1798900828ADD /* APIKeyboardRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = C07A9D8D1FD1798900828ADD /* APIKeyboardRepository.swift */; }; C082CE151F90AFD400860F02 /* Collection+SafeAccess.swift in Sources */ = {isa = PBXBuildFile; fileRef = C082CE141F90AFD400860F02 /* Collection+SafeAccess.swift */; }; C08E698D1FDA392D0026056B /* Migrations.swift in Sources */ = {isa = PBXBuildFile; fileRef = C08E698C1FDA392D0026056B /* Migrations.swift */; }; C08E69911FDA6F6F0026056B /* FullKeyboardID.swift in Sources */ = {isa = PBXBuildFile; fileRef = C08E69901FDA6F6F0026056B /* FullKeyboardID.swift */; }; @@ -126,6 +118,12 @@ C0D3F3601F9F3AD80055C7CF /* InstallableKeyboard.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0D3F35F1F9F3AD80055C7CF /* InstallableKeyboard.swift */; }; C0E30C8C1FC40D0400C80416 /* Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0E30C8B1FC40D0400C80416 /* Storage.swift */; }; C0EF3E7B1F95B65300CE9BD4 /* KeymanWebDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0EF3E7A1F95B65300CE9BD4 /* KeymanWebDelegate.swift */; }; + CE02EE0C24A5863100D58F92 /* Queries.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CE02EE0B24A5863100D58F92 /* Queries.bundle */; }; + CE02EE0E24A5869500D58F92 /* Queries.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE02EE0D24A5869500D58F92 /* Queries.swift */; }; + CE02EE1024A5892200D58F92 /* URLSessionDataTaskMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE02EE0F24A5892200D58F92 /* URLSessionDataTaskMock.swift */; }; + CE07E3D2247E3FB100DFA9D2 /* HTTPDownloaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE07E3D1247E3FB100DFA9D2 /* HTTPDownloaderTests.swift */; }; + CE07E3D6247E41DB00DFA9D2 /* URLSessionMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE07E3D5247E41DB00DFA9D2 /* URLSessionMock.swift */; }; + CE07E3D8247E43CB00DFA9D2 /* URLSessionDownloadTaskMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE07E3D7247E43CB00DFA9D2 /* URLSessionDownloadTaskMock.swift */; }; CE17ABDE23069E76005FBB14 /* LanguageResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE17ABDD23069E76005FBB14 /* LanguageResource.swift */; }; CE1E1EC12303C8CC001C7BE0 /* ResourceDownloadStatusToolbar.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE1E1EC02303C8CC001C7BE0 /* ResourceDownloadStatusToolbar.swift */; }; CE1F67A32304EB3800FF6972 /* ResourceDownloadManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE1F67A22304EB3800FF6972 /* ResourceDownloadManager.swift */; }; @@ -153,10 +151,12 @@ CE4459F523FBBB8F003151FD /* XCGLogger.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 1687ACCC1FD8DE5300926D69 /* XCGLogger.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; CE4459F623FBBB8F003151FD /* Zip.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 165C8B8B1FD8220600D4A78D /* Zip.framework */; }; CE4459F723FBBB8F003151FD /* Zip.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 165C8B8B1FD8220600D4A78D /* Zip.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + CE46D65D247B93C9005FD506 /* (null) in Resources */ = {isa = PBXBuildFile; }; + CE5C8BE324B5B3BA00FAFB7F /* Queries+LexicalModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE5C8BE224B5B3BA00FAFB7F /* Queries+LexicalModel.swift */; }; + CE5C8BE524B5BD1C00FAFB7F /* QueryModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE5C8BE424B5BD1C00FAFB7F /* QueryModelTests.swift */; }; CE67D961228A6F190029F2B5 /* KeyboardCommandStructs.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE67D960228A6F190029F2B5 /* KeyboardCommandStructs.swift */; }; CE71705823A9C14D00A924A1 /* ResourceFileManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE71705723A9C14D00A924A1 /* ResourceFileManager.swift */; }; CE71705F23A9C97F00A924A1 /* PackageInstallViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE71705E23A9C97F00A924A1 /* PackageInstallViewController.swift */; }; - CE754A0223D151B90030CB79 /* ResourceInfoView.xib in Resources */ = {isa = PBXBuildFile; fileRef = CE754A0123D151B90030CB79 /* ResourceInfoView.xib */; }; CE754A0423D162E90030CB79 /* ResourceInfoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE754A0323D162E90030CB79 /* ResourceInfoViewController.swift */; }; CE79B24923C711FF007E72AE /* KeyboardScaleMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE79B24823C711FF007E72AE /* KeyboardScaleMap.swift */; }; CE7A26D123CEE5790005955C /* Keyboard Colors.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = CE7A26D023CEE5790005955C /* Keyboard Colors.xcassets */; }; @@ -173,21 +173,62 @@ CE808A4D236697D500713E6B /* Reachability.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A0FC9FC22D66D9E00D33F86 /* Reachability.framework */; }; CE808A4F236697D800713E6B /* XCGLogger.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1687ACCC1FD8DE5300926D69 /* XCGLogger.framework */; }; CE808A532366980A00713E6B /* Zip.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 165C8B8B1FD8220600D4A78D /* Zip.framework */; }; + CE867FEF2485E97A00B2EAED /* KMPMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE867FEE2485E97A00B2EAED /* KMPMetadata.swift */; }; + CE867FF12485EE1500B2EAED /* KMPInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE867FF02485EE1500B2EAED /* KMPInfo.swift */; }; + CE87751E24C68DA500B1475A /* KeyboardSearchViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE87751D24C68DA500B1475A /* KeyboardSearchViewController.swift */; }; + CE88042F247F4B97009BCA1A /* ExpectationDownloaderDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE88042E247F4B97009BCA1A /* ExpectationDownloaderDelegate.swift */; }; + CE88143A24A9B7F4002809C3 /* ResourceDownloadQueueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE88143924A9B7F4002809C3 /* ResourceDownloadQueueTests.swift */; }; + CE89641F24A4686000D5EB8E /* Queries.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE89641E24A4686000D5EB8E /* Queries.swift */; }; + CE89642124A468B200D5EB8E /* Queries+PackageVersion.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE89642024A468B200D5EB8E /* Queries+PackageVersion.swift */; }; + CE89642524A46D0000D5EB8E /* QueryPackageVersionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE89642424A46D0000D5EB8E /* QueryPackageVersionTests.swift */; }; + CE8B0BBD248734240045EB2E /* KeymanPackageTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE8B0BBC248734240045EB2E /* KeymanPackageTests.swift */; }; + CE8B0BBF248764ED0045EB2E /* KMPResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE8B0BBE248764ED0045EB2E /* KMPResource.swift */; }; + CE8B5BB22491DA540075CCB0 /* 13.0 Cloud to Package Migration.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CE8B5BB12491DA530075CCB0 /* 13.0 Cloud to Package Migration.bundle */; }; CE8EDEB123F53D1A009E1FF6 /* FileManagementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A079DD1223194B100581263 /* FileManagementTests.swift */; }; CE8EDEB323F53F96009E1FF6 /* VersionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE8EDEB223F53F96009E1FF6 /* VersionTests.swift */; }; + CE96E42B24D1229A005B8E5A /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = CE96E42D24D1229A005B8E5A /* Localizable.stringsdict */; }; + CE973D812484A56500F66045 /* PackageJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE973D802484A56500F66045 /* PackageJSON.swift */; }; + CE973D832484A5DC00F66045 /* PackageJSON.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CE973D822484A5DB00F66045 /* PackageJSON.bundle */; }; + CE973D852484A71700F66045 /* KMPJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE973D842484A71700F66045 /* KMPJSONTests.swift */; }; + CE973D872484BBC200F66045 /* KMPLanguage.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE973D862484BBC200F66045 /* KMPLanguage.swift */; }; + CE973D892484DBA600F66045 /* KMPSystem.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE973D882484DBA600F66045 /* KMPSystem.swift */; }; + CE973D8B2484DCA300F66045 /* KMPOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE973D8A2484DCA300F66045 /* KMPOptions.swift */; }; + CE973D8D2484DD1900F66045 /* KMPFile.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE973D8C2484DD1900F66045 /* KMPFile.swift */; }; CE976D4F23FA380700FFDF3A /* Reachability.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A0FC9FC22D66D9E00D33F86 /* Reachability.framework */; }; CE976D5023FA380700FFDF3A /* Reachability.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 9A0FC9FC22D66D9E00D33F86 /* Reachability.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + CE97866224C7DD1A00C5DCBC /* KeyboardSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE97866124C7DD1A00C5DCBC /* KeyboardSearchTests.swift */; }; + CE99350E24D7CCFC00202DA3 /* LanguagePickAssociator.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE99350D24D7CCFC00202DA3 /* LanguagePickAssociator.swift */; }; + CE99351024D8018B00202DA3 /* LanguagePickAssociatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE99350F24D8018B00202DA3 /* LanguagePickAssociatorTests.swift */; }; + CE9A749A24DBA576003C3B65 /* AssociatingPackageInstallerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE9A749924DBA576003C3B65 /* AssociatingPackageInstallerTests.swift */; }; + CE9A7A7924DA55D5007CCB5F /* AssociatingPackageInstaller.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE9A7A7824DA55D5007CCB5F /* AssociatingPackageInstaller.swift */; }; CE9B440C23FE49F000499CAB /* Migrations.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE9B440B23FE49F000499CAB /* Migrations.swift */; }; CE9B440F23FE4E7500499CAB /* 12.0 Ad-hoc Migration.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CE9B440D23FE4E7400499CAB /* 12.0 Ad-hoc Migration.bundle */; }; CE9B441023FE4E7500499CAB /* Simple 12.0 Migration.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CE9B440E23FE4E7500499CAB /* Simple 12.0 Migration.bundle */; }; CE9CD88023FCC1CA002BF2F8 /* TestUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE9CD87F23FCC1CA002BF2F8 /* TestUtils.swift */; }; CE9CD88323FCC4E3002BF2F8 /* UserDefaults.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE9CD88223FCC4E3002BF2F8 /* UserDefaults.swift */; }; + CE9ECB1E24D3A8CC007C5718 /* PackageInstallView_iPad.xib in Resources */ = {isa = PBXBuildFile; fileRef = CE9ECB1D24D3A8CC007C5718 /* PackageInstallView_iPad.xib */; }; + CEA1486C2407808F00C6ECD2 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = CEA1486F2407808F00C6ECD2 /* Localizable.strings */; }; + CEA1486D2407808F00C6ECD2 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = CEA1486F2407808F00C6ECD2 /* Localizable.strings */; }; + CEA14870240780E100C6ECD2 /* ResourceInfoView.xib in Resources */ = {isa = PBXBuildFile; fileRef = CEA14872240780E100C6ECD2 /* ResourceInfoView.xib */; }; + CE9E95CD24CE786900F6DD78 /* UniversalLinks.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE9E95CC24CE786900F6DD78 /* UniversalLinks.swift */; }; + CE9E95CF24CE7A2C00F6DD78 /* UniversalLinkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE9E95CE24CE7A2C00F6DD78 /* UniversalLinkTests.swift */; }; + CEA6BA9D249872E8002D44CE /* Simple 13.0 Migration.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CEA6BA9C249872E7002D44CE /* Simple 13.0 Migration.bundle */; }; + CEA70CCF24CAC3AE001C12E6 /* Obsoletions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA70CCE24CAC3AE001C12E6 /* Obsoletions.swift */; }; + CEA9670924BEC4030035AACF /* ResourceUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA9670824BEC4030035AACF /* ResourceUpdateTests.swift */; }; + CEA9670B24BEC8030035AACF /* EngineStateBundler.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA9670A24BEC8030035AACF /* EngineStateBundler.swift */; }; + CEA9670D24BEEFF80035AACF /* khmer_angkor update-base.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CEA9670C24BEEFF80035AACF /* khmer_angkor update-base.bundle */; }; + CEA9670F24BEF05A0035AACF /* Updates.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA9670E24BEF05A0035AACF /* Updates.swift */; }; + CEB8276724C6811800F3D39C /* KeymanHostTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEB8276624C6811800F3D39C /* KeymanHostTests.swift */; }; CEC0C66C2410AC9A003E1BCD /* Sentry.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CEC0C66B2410AC9A003E1BCD /* Sentry.framework */; }; CEC0C6772410E049003E1BCD /* SentryManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEC0C6762410E049003E1BCD /* SentryManager.swift */; }; + CED8B63224A9C2400054E300 /* ResourceDownloadManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CED8B63124A9C2400054E300 /* ResourceDownloadManagerTests.swift */; }; CEDFEF8F23FE43B700BECF39 /* MigrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEDFEF8E23FE43B700BECF39 /* MigrationTests.swift */; }; + CEE0321124C56735005BFC73 /* Packages.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEE0321024C56735005BFC73 /* Packages.swift */; }; + CEE0321324C58C90005BFC73 /* KeymanHosts.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEE0321224C58C90005BFC73 /* KeymanHosts.swift */; }; CEF888D223FE6ADF00667693 /* No-defaults 10.0 Migration.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CEF888D023FE6ADE00667693 /* No-defaults 10.0 Migration.bundle */; }; CEF888D323FE6ADF00667693 /* Simple 10.0 Migration.bundle in Resources */ = {isa = PBXBuildFile; fileRef = CEF888D123FE6ADF00667693 /* Simple 10.0 Migration.bundle */; }; CEF888D523FE786C00667693 /* KeyboardScaleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEF888D423FE786C00667693 /* KeyboardScaleTests.swift */; }; + CEF9367824D3B0B20031C70D /* PackageInstallView_iPhone.xib in Resources */ = {isa = PBXBuildFile; fileRef = CEF9367724D3B0B20031C70D /* PackageInstallView_iPhone.xib */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -353,14 +394,10 @@ 9A0FC9FC22D66D9E00D33F86 /* Reachability.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Reachability.framework; path = ../../Carthage/Build/iOS/Reachability.framework; sourceTree = ""; }; 9A3B14D1229370B20052A11F /* InstalledLanguagesViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = InstalledLanguagesViewController.swift; path = Settings/InstalledLanguagesViewController.swift; sourceTree = ""; }; 9A3E832422EAC14A00D22D2A /* KeyboardSwitcherViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardSwitcherViewController.swift; sourceTree = ""; }; - 9A4609962241B39B00B0BFD1 /* LexicalModelInfoViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LexicalModelInfoViewController.swift; sourceTree = ""; }; 9A4609982242047400B0BFD1 /* LexicalModelAPICall.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LexicalModelAPICall.swift; sourceTree = ""; }; 9A60763C22892485003BCFBA /* Settings.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Settings.storyboard; path = Settings/Settings.storyboard; sourceTree = ""; }; 9A60764322893A4E003BCFBA /* SettingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SettingsViewController.swift; path = Settings/SettingsViewController.swift; sourceTree = ""; }; 9A9CB07F22416E5400231FB9 /* LexicalModelPickerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LexicalModelPickerViewController.swift; sourceTree = ""; }; - 9A9CB0812241704800231FB9 /* APILexicalModelRepository.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APILexicalModelRepository.swift; sourceTree = ""; }; - 9A9CB083224170F700231FB9 /* LexicalModelRepository.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LexicalModelRepository.swift; sourceTree = ""; }; - 9A9CB0852241717C00231FB9 /* LexicalModelRepositoryDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LexicalModelRepositoryDelegate.swift; sourceTree = ""; }; 9AD4F53A229F85AC007992D3 /* LanguageSettingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = LanguageSettingsViewController.swift; path = Settings/LanguageSettingsViewController.swift; sourceTree = ""; }; 9AD4F53B229F85AC007992D3 /* LanguageSettingsViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = LanguageSettingsViewController.xib; path = Settings/LanguageSettingsViewController.xib; sourceTree = ""; }; 9ADC459B22E1895D004C78C6 /* LanguageLMDetailViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LanguageLMDetailViewController.swift; sourceTree = ""; }; @@ -388,16 +425,12 @@ C04C2A6C1F6B7D9A00BA42B6 /* LanguageViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LanguageViewController.swift; sourceTree = ""; }; C055E6EA1F99ED090035C2DD /* RegisteredFont.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RegisteredFont.swift; sourceTree = ""; }; C05B14321FD914870082A316 /* Log.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Log.swift; sourceTree = ""; }; - C05F432C1FBD5A4C0058CBD4 /* KeyboardAPICall.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardAPICall.swift; sourceTree = ""; }; C05F43301FBD62550058CBD4 /* JSONDecoder.DateDecodingStrategy+ISO8601Fallback.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "JSONDecoder.DateDecodingStrategy+ISO8601Fallback.swift"; sourceTree = ""; }; C06085B31F9485E40057E5B9 /* UIButton+Helpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIButton+Helpers.swift"; sourceTree = ""; }; C06D372B1F81F4E100F61AE0 /* KeymanEngine.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = KeymanEngine.framework; sourceTree = BUILT_PRODUCTS_DIR; }; C06D372D1F81F4E100F61AE0 /* KeymanEngine.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = KeymanEngine.h; sourceTree = ""; }; C06D372E1F81F4E100F61AE0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; C075EB051F8EFF870041F4BD /* String+Helpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Helpers.swift"; sourceTree = ""; }; - C07A9D891FD1762700828ADD /* KeyboardRepository.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardRepository.swift; sourceTree = ""; }; - C07A9D8B1FD176AB00828ADD /* KeyboardRepositoryDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardRepositoryDelegate.swift; sourceTree = ""; }; - C07A9D8D1FD1798900828ADD /* APIKeyboardRepository.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIKeyboardRepository.swift; sourceTree = ""; }; C07B42AE1F7CEE2700ECA97F /* SubKeysView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubKeysView.swift; sourceTree = ""; }; C082CE141F90AFD400860F02 /* Collection+SafeAccess.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Collection+SafeAccess.swift"; sourceTree = ""; }; C08C620B1F6792A200268D03 /* KeyboardPickerBarButtonItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KeyboardPickerBarButtonItem.swift; sourceTree = ""; }; @@ -419,6 +452,12 @@ C0ED71B21F6BB0B1002A2FD6 /* HTTPDownloadRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPDownloadRequest.swift; sourceTree = ""; }; C0ED71B41F6BBFAF002A2FD6 /* HTTPDownloader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPDownloader.swift; sourceTree = ""; }; C0EF3E7A1F95B65300CE9BD4 /* KeymanWebDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeymanWebDelegate.swift; sourceTree = ""; }; + CE02EE0B24A5863100D58F92 /* Queries.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = Queries.bundle; sourceTree = ""; }; + CE02EE0D24A5869500D58F92 /* Queries.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Queries.swift; sourceTree = ""; }; + CE02EE0F24A5892200D58F92 /* URLSessionDataTaskMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSessionDataTaskMock.swift; sourceTree = ""; }; + CE07E3D1247E3FB100DFA9D2 /* HTTPDownloaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPDownloaderTests.swift; sourceTree = ""; }; + CE07E3D5247E41DB00DFA9D2 /* URLSessionMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSessionMock.swift; sourceTree = ""; }; + CE07E3D7247E43CB00DFA9D2 /* URLSessionDownloadTaskMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSessionDownloadTaskMock.swift; sourceTree = ""; }; CE17ABDD23069E76005FBB14 /* LanguageResource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LanguageResource.swift; sourceTree = ""; }; CE1E1EC02303C8CC001C7BE0 /* ResourceDownloadStatusToolbar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResourceDownloadStatusToolbar.swift; sourceTree = ""; }; CE1F67A22304EB3800FF6972 /* ResourceDownloadManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResourceDownloadManager.swift; sourceTree = ""; }; @@ -432,30 +471,73 @@ CE4459CD23FBBA8D003151FD /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; CE4459D323FBBB34003151FD /* KeymanEngineTestHost.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = KeymanEngineTestHost.app; sourceTree = BUILT_PRODUCTS_DIR; }; CE4459ED23FBBB7F003151FD /* Carthage */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Carthage; path = ../../Carthage; sourceTree = ""; }; + CE5C8BE224B5B3BA00FAFB7F /* Queries+LexicalModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Queries+LexicalModel.swift"; sourceTree = ""; }; + CE5C8BE424B5BD1C00FAFB7F /* QueryModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueryModelTests.swift; sourceTree = ""; }; CE67D960228A6F190029F2B5 /* KeyboardCommandStructs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardCommandStructs.swift; sourceTree = ""; }; CE71705723A9C14D00A924A1 /* ResourceFileManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResourceFileManager.swift; sourceTree = ""; }; CE71705E23A9C97F00A924A1 /* PackageInstallViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PackageInstallViewController.swift; sourceTree = ""; }; - CE754A0123D151B90030CB79 /* ResourceInfoView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = ResourceInfoView.xib; sourceTree = ""; }; CE754A0323D162E90030CB79 /* ResourceInfoViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResourceInfoViewController.swift; sourceTree = ""; }; CE79B24823C711FF007E72AE /* KeyboardScaleMap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardScaleMap.swift; sourceTree = ""; }; CE7A26D023CEE5790005955C /* Keyboard Colors.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Keyboard Colors.xcassets"; sourceTree = ""; }; CE7A26D723CEEC630005955C /* Colors+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Colors+Extension.swift"; sourceTree = ""; }; CE7A26DA23CEEF640005955C /* Colors.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Colors.swift; sourceTree = ""; }; CE7ADD6523DE89FC00BC9A00 /* Alerts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Alerts.swift; sourceTree = ""; }; + CE867FEE2485E97A00B2EAED /* KMPMetadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KMPMetadata.swift; sourceTree = ""; }; + CE867FF02485EE1500B2EAED /* KMPInfo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KMPInfo.swift; sourceTree = ""; }; + CE87751D24C68DA500B1475A /* KeyboardSearchViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardSearchViewController.swift; sourceTree = ""; }; + CE88042E247F4B97009BCA1A /* ExpectationDownloaderDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExpectationDownloaderDelegate.swift; sourceTree = ""; }; + CE88143924A9B7F4002809C3 /* ResourceDownloadQueueTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResourceDownloadQueueTests.swift; sourceTree = ""; }; + CE89641E24A4686000D5EB8E /* Queries.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Queries.swift; sourceTree = ""; }; + CE89642024A468B200D5EB8E /* Queries+PackageVersion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Queries+PackageVersion.swift"; sourceTree = ""; }; + CE89642424A46D0000D5EB8E /* QueryPackageVersionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueryPackageVersionTests.swift; sourceTree = ""; }; + CE8B0BBC248734240045EB2E /* KeymanPackageTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeymanPackageTests.swift; sourceTree = ""; }; + CE8B0BBE248764ED0045EB2E /* KMPResource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KMPResource.swift; sourceTree = ""; }; + CE8B5BB12491DA530075CCB0 /* 13.0 Cloud to Package Migration.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = "13.0 Cloud to Package Migration.bundle"; sourceTree = ""; }; CE8EDEB223F53F96009E1FF6 /* VersionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VersionTests.swift; sourceTree = ""; }; + CE96E42C24D1229A005B8E5A /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = ""; }; + CE973D802484A56500F66045 /* PackageJSON.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PackageJSON.swift; sourceTree = ""; }; + CE973D822484A5DB00F66045 /* PackageJSON.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = PackageJSON.bundle; sourceTree = ""; }; + CE973D842484A71700F66045 /* KMPJSONTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KMPJSONTests.swift; sourceTree = ""; }; + CE973D862484BBC200F66045 /* KMPLanguage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KMPLanguage.swift; sourceTree = ""; }; + CE973D882484DBA600F66045 /* KMPSystem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KMPSystem.swift; sourceTree = ""; }; + CE973D8A2484DCA300F66045 /* KMPOptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KMPOptions.swift; sourceTree = ""; }; + CE973D8C2484DD1900F66045 /* KMPFile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KMPFile.swift; sourceTree = ""; }; + CE97866124C7DD1A00C5DCBC /* KeyboardSearchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardSearchTests.swift; sourceTree = ""; }; + CE99350D24D7CCFC00202DA3 /* LanguagePickAssociator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LanguagePickAssociator.swift; sourceTree = ""; }; + CE99350F24D8018B00202DA3 /* LanguagePickAssociatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LanguagePickAssociatorTests.swift; sourceTree = ""; }; + CE9A749924DBA576003C3B65 /* AssociatingPackageInstallerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociatingPackageInstallerTests.swift; sourceTree = ""; }; + CE9A7A7824DA55D5007CCB5F /* AssociatingPackageInstaller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociatingPackageInstaller.swift; sourceTree = ""; }; CE9B440B23FE49F000499CAB /* Migrations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Migrations.swift; sourceTree = ""; }; CE9B440D23FE4E7400499CAB /* 12.0 Ad-hoc Migration.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = "12.0 Ad-hoc Migration.bundle"; sourceTree = ""; }; CE9B440E23FE4E7500499CAB /* Simple 12.0 Migration.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = "Simple 12.0 Migration.bundle"; sourceTree = ""; }; CE9CD87F23FCC1CA002BF2F8 /* TestUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestUtils.swift; sourceTree = ""; }; CE9CD88223FCC4E3002BF2F8 /* UserDefaults.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserDefaults.swift; sourceTree = ""; }; + CE9ECB1D24D3A8CC007C5718 /* PackageInstallView_iPad.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = PackageInstallView_iPad.xib; sourceTree = ""; }; + CEA1486E2407808F00C6ECD2 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = ""; }; + CEA14871240780E100C6ECD2 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/ResourceInfoView.xib; sourceTree = ""; }; + CEA14874240780EF00C6ECD2 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/ResourceInfoView.strings; sourceTree = ""; }; + CEA148772407869200C6ECD2 /* km */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = km; path = km.lproj/ResourceInfoView.strings; sourceTree = ""; }; + CE9E95CC24CE786900F6DD78 /* UniversalLinks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniversalLinks.swift; sourceTree = ""; }; + CE9E95CE24CE7A2C00F6DD78 /* UniversalLinkTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniversalLinkTests.swift; sourceTree = ""; }; + CEA6BA9C249872E7002D44CE /* Simple 13.0 Migration.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = "Simple 13.0 Migration.bundle"; sourceTree = ""; }; + CEA70CCE24CAC3AE001C12E6 /* Obsoletions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Obsoletions.swift; sourceTree = ""; }; + CEA9670824BEC4030035AACF /* ResourceUpdateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResourceUpdateTests.swift; sourceTree = ""; }; + CEA9670A24BEC8030035AACF /* EngineStateBundler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EngineStateBundler.swift; sourceTree = ""; }; + CEA9670C24BEEFF80035AACF /* khmer_angkor update-base.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = "khmer_angkor update-base.bundle"; sourceTree = ""; }; + CEA9670E24BEF05A0035AACF /* Updates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Updates.swift; sourceTree = ""; }; + CEB8276624C6811800F3D39C /* KeymanHostTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeymanHostTests.swift; sourceTree = ""; }; CEC0C66B2410AC9A003E1BCD /* Sentry.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Sentry.framework; path = ../../Carthage/Build/iOS/Sentry.framework; sourceTree = ""; }; CEC0C6762410E049003E1BCD /* SentryManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SentryManager.swift; sourceTree = ""; }; CECB38931F2199BC0098882F /* Reachability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Reachability.h; path = KeymanEngine/lib/Reachability/Reachability.h; sourceTree = SOURCE_ROOT; }; CECB38941F2199BC0098882F /* Reachability.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Reachability.m; path = KeymanEngine/lib/Reachability/Reachability.m; sourceTree = SOURCE_ROOT; }; + CED8B63124A9C2400054E300 /* ResourceDownloadManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResourceDownloadManagerTests.swift; sourceTree = ""; }; CEDFEF8E23FE43B700BECF39 /* MigrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MigrationTests.swift; sourceTree = ""; }; + CEE0321024C56735005BFC73 /* Packages.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Packages.swift; sourceTree = ""; }; + CEE0321224C58C90005BFC73 /* KeymanHosts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeymanHosts.swift; sourceTree = ""; }; CEF888D023FE6ADE00667693 /* No-defaults 10.0 Migration.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = "No-defaults 10.0 Migration.bundle"; sourceTree = ""; }; CEF888D123FE6ADF00667693 /* Simple 10.0 Migration.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = "Simple 10.0 Migration.bundle"; sourceTree = ""; }; CEF888D423FE786C00667693 /* KeyboardScaleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardScaleTests.swift; sourceTree = ""; }; + CEF9367724D3B0B20031C70D /* PackageInstallView_iPhone.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = PackageInstallView_iPhone.xib; sourceTree = ""; }; F243887E14BBD43000A3E055 /* KeymanEngineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = KeymanEngineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; F243889014BBD43100A3E055 /* KeymanEngine-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "KeymanEngine-Prefix.pch"; sourceTree = ""; }; F27FCAEE157FD59100FBBA20 /* Keyman-iphoneos.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Keyman-iphoneos.xcconfig"; sourceTree = ""; }; @@ -683,11 +765,24 @@ CE9CD88123FCC4C7002BF2F8 /* TestUtils */, CE37C38923FCC9AF007031C6 /* resources */, 9A079DD1223194B100581263 /* FileManagementTests.swift */, + CE8B0BBC248734240045EB2E /* KeymanPackageTests.swift */, + CE07E3D1247E3FB100DFA9D2 /* HTTPDownloaderTests.swift */, 9A079DD3223194B100581263 /* Info.plist */, CE8EDEB223F53F96009E1FF6 /* VersionTests.swift */, + CEB8276624C6811800F3D39C /* KeymanHostTests.swift */, CE4459CD23FBBA8D003151FD /* AppDelegate.swift */, CEF888D423FE786C00667693 /* KeyboardScaleTests.swift */, + CE97866124C7DD1A00C5DCBC /* KeyboardSearchTests.swift */, + CE9A749924DBA576003C3B65 /* AssociatingPackageInstallerTests.swift */, + CE99350F24D8018B00202DA3 /* LanguagePickAssociatorTests.swift */, CEDFEF8E23FE43B700BECF39 /* MigrationTests.swift */, + CE973D842484A71700F66045 /* KMPJSONTests.swift */, + CE89642424A46D0000D5EB8E /* QueryPackageVersionTests.swift */, + CE5C8BE424B5BD1C00FAFB7F /* QueryModelTests.swift */, + CED8B63124A9C2400054E300 /* ResourceDownloadManagerTests.swift */, + CEA9670824BEC4030035AACF /* ResourceUpdateTests.swift */, + CE88143924A9B7F4002809C3 /* ResourceDownloadQueueTests.swift */, + CE9E95CE24CE7A2C00F6DD78 /* UniversalLinkTests.swift */, ); path = KeymanEngineTests; sourceTree = ""; @@ -729,16 +824,10 @@ 9A079E3C223B5FAF00581263 /* InstallableLexicalModel.swift */, C055E6EA1F99ED090035C2DD /* RegisteredFont.swift */, C007C4641F9F52D8006461B9 /* LanguagesAPICall.swift */, - C05F432C1FBD5A4C0058CBD4 /* KeyboardAPICall.swift */, 9A4609982242047400B0BFD1 /* LexicalModelAPICall.swift */, C042ED5C1FC6A65A001D82F4 /* Version.swift */, C08E69901FDA6F6F0026056B /* FullKeyboardID.swift */, 9A079E42223B61AE00581263 /* FullLexicalModelID.swift */, - 1645D5942036C6FF0076C51B /* KeymanPackage.swift */, - 9A079E39223AFF3C00581263 /* KeyboardKeymanPackage.swift */, - 9A079DC9222E050E00581263 /* LexicalModelKeymanPackage.swift */, - 1645D5962036C9F80076C51B /* KMPKeyboard.swift */, - 9A079E362238680700581263 /* KMPLexicalModel.swift */, ); path = Model; sourceTree = ""; @@ -760,6 +849,8 @@ C06D372C1F81F4E100F61AE0 /* KeymanEngine */ = { isa = PBXGroup; children = ( + CEA1486F2407808F00C6ECD2 /* Localizable.strings */, + CE96E42D24D1229A005B8E5A /* Localizable.stringsdict */, CE7A26D023CEE5790005955C /* Keyboard Colors.xcassets */, C06D372D1F81F4E100F61AE0 /* KeymanEngine.h */, C06D372E1F81F4E100F61AE0 /* Info.plist */, @@ -770,17 +861,15 @@ path = KeymanEngine; sourceTree = ""; }; - C07A9D881FD1760800828ADD /* KeyboardRepository */ = { + CE07E3D3247E418800DFA9D2 /* Downloading */ = { isa = PBXGroup; children = ( - C07A9D891FD1762700828ADD /* KeyboardRepository.swift */, - 9A9CB083224170F700231FB9 /* LexicalModelRepository.swift */, - C07A9D8B1FD176AB00828ADD /* KeyboardRepositoryDelegate.swift */, - 9A9CB0852241717C00231FB9 /* LexicalModelRepositoryDelegate.swift */, - C07A9D8D1FD1798900828ADD /* APIKeyboardRepository.swift */, - 9A9CB0812241704800231FB9 /* APILexicalModelRepository.swift */, - ); - path = KeyboardRepository; + CE07E3D5247E41DB00DFA9D2 /* URLSessionMock.swift */, + CE02EE0F24A5892200D58F92 /* URLSessionDataTaskMock.swift */, + CE07E3D7247E43CB00DFA9D2 /* URLSessionDownloadTaskMock.swift */, + CE88042E247F4B97009BCA1A /* ExpectationDownloaderDelegate.swift */, + ); + path = Downloading; sourceTree = ""; }; CE25CCBB1F1DA72A005AA2BC /* HTTPRequest */ = { @@ -795,6 +884,11 @@ CE37C38923FCC9AF007031C6 /* resources */ = { isa = PBXGroup; children = ( + CEA9670C24BEEFF80035AACF /* khmer_angkor update-base.bundle */, + CE02EE0B24A5863100D58F92 /* Queries.bundle */, + CEA6BA9C249872E7002D44CE /* Simple 13.0 Migration.bundle */, + CE8B5BB12491DA530075CCB0 /* 13.0 Cloud to Package Migration.bundle */, + CE973D822484A5DB00F66045 /* PackageJSON.bundle */, CEF888D023FE6ADE00667693 /* No-defaults 10.0 Migration.bundle */, CEF888D123FE6ADF00667693 /* Simple 10.0 Migration.bundle */, CE9B440D23FE4E7400499CAB /* 12.0 Ad-hoc Migration.bundle */, @@ -818,19 +912,68 @@ isa = PBXGroup; children = ( CE1F67A22304EB3800FF6972 /* ResourceDownloadManager.swift */, + CE87751D24C68DA500B1475A /* KeyboardSearchViewController.swift */, + CEF9367724D3B0B20031C70D /* PackageInstallView_iPhone.xib */, + CE9ECB1D24D3A8CC007C5718 /* PackageInstallView_iPad.xib */, CE22DFB9230B94DB00A4551C /* ResourceDownloadQueue.swift */, CE71705723A9C14D00A924A1 /* ResourceFileManager.swift */, CE71705E23A9C97F00A924A1 /* PackageInstallViewController.swift */, + CE99350D24D7CCFC00202DA3 /* LanguagePickAssociator.swift */, + C0E30C8B1FC40D0400C80416 /* Storage.swift */, + CE9A7A7824DA55D5007CCB5F /* AssociatingPackageInstaller.swift */, ); path = "Resource Management"; sourceTree = ""; }; + CE867FF22485F38300B2EAED /* kmp.json */ = { + isa = PBXGroup; + children = ( + 1645D5962036C9F80076C51B /* KMPKeyboard.swift */, + CE867FF02485EE1500B2EAED /* KMPInfo.swift */, + CE867FEE2485E97A00B2EAED /* KMPMetadata.swift */, + CE973D862484BBC200F66045 /* KMPLanguage.swift */, + 9A079E362238680700581263 /* KMPLexicalModel.swift */, + CE973D882484DBA600F66045 /* KMPSystem.swift */, + CE973D8A2484DCA300F66045 /* KMPOptions.swift */, + CE973D8C2484DD1900F66045 /* KMPFile.swift */, + CE8B0BBE248764ED0045EB2E /* KMPResource.swift */, + ); + path = kmp.json; + sourceTree = ""; + }; + CE89641B24A4665700D5EB8E /* Queries */ = { + isa = PBXGroup; + children = ( + CE89641E24A4686000D5EB8E /* Queries.swift */, + CE89642024A468B200D5EB8E /* Queries+PackageVersion.swift */, + CE5C8BE224B5B3BA00FAFB7F /* Queries+LexicalModel.swift */, + ); + path = Queries; + sourceTree = ""; + }; + CE973D7F2484A07300F66045 /* KMP Packaging */ = { + isa = PBXGroup; + children = ( + 1645D5942036C6FF0076C51B /* KeymanPackage.swift */, + 9A079E39223AFF3C00581263 /* KeyboardKeymanPackage.swift */, + 9A079DC9222E050E00581263 /* LexicalModelKeymanPackage.swift */, + CE867FF22485F38300B2EAED /* kmp.json */, + ); + name = "KMP Packaging"; + sourceTree = ""; + }; CE9CD88123FCC4C7002BF2F8 /* TestUtils */ = { isa = PBXGroup; children = ( + CE07E3D3247E418800DFA9D2 /* Downloading */, CE9CD87F23FCC1CA002BF2F8 /* TestUtils.swift */, + CEA9670A24BEC8030035AACF /* EngineStateBundler.swift */, CE9CD88223FCC4E3002BF2F8 /* UserDefaults.swift */, + CE973D802484A56500F66045 /* PackageJSON.swift */, CE37C38C23FCD41E007031C6 /* Keyboards.swift */, + CEE0321024C56735005BFC73 /* Packages.swift */, + CE02EE0D24A5869500D58F92 /* Queries.swift */, + CEA9670E24BEF05A0035AACF /* Updates.swift */, CE37C39023FCD617007031C6 /* LexicalModels.swift */, CE9B440B23FE49F000499CAB /* Migrations.swift */, ); @@ -910,8 +1053,7 @@ isa = PBXGroup; children = ( CE754A0323D162E90030CB79 /* ResourceInfoViewController.swift */, - CE754A0123D151B90030CB79 /* ResourceInfoView.xib */, - 9A4609962241B39B00B0BFD1 /* LexicalModelInfoViewController.swift */, + CEA14872240780E100C6ECD2 /* ResourceInfoView.xib */, 9A3E832422EAC14A00D22D2A /* KeyboardSwitcherViewController.swift */, 9A9CB07F22416E5400231FB9 /* LexicalModelPickerViewController.swift */, C092D8381F6A70C8005C5485 /* LanguageDetailViewController.swift */, @@ -928,12 +1070,13 @@ F273AB9615641D9300A47CEE /* Classes */ = { isa = PBXGroup; children = ( + CE973D7F2484A07300F66045 /* KMP Packaging */, CE71705923A9C7D300A924A1 /* Resource Management */, 165EB39F2098992D00040A69 /* Errors */, C055E6E81F99EA320035C2DD /* Extension */, C0452BA91F9F1CAF0064431A /* Model */, C024C9921FA6EB340060583B /* Notification */, - C07A9D881FD1760800828ADD /* KeyboardRepository */, + CE89641B24A4665700D5EB8E /* Queries */, 9A60763E22892495003BCFBA /* Settings */, CE25CCBB1F1DA72A005AA2BC /* HTTPRequest */, 987F00041AB8FCB700998116 /* KeyboardMenuView */, @@ -951,12 +1094,14 @@ CE7A26D723CEEC630005955C /* Colors+Extension.swift */, CE7A26DA23CEEF640005955C /* Colors.swift */, C0B09EAD1FCFD10F002F39AF /* FontManager.swift */, - C0E30C8B1FC40D0400C80416 /* Storage.swift */, + CEE0321224C58C90005BFC73 /* KeymanHosts.swift */, C0EF3E7A1F95B65300CE9BD4 /* KeymanWebDelegate.swift */, C05B14321FD914870082A316 /* Log.swift */, C08E698C1FDA392D0026056B /* Migrations.swift */, CE79B24823C711FF007E72AE /* KeyboardScaleMap.swift */, CE7ADD6523DE89FC00BC9A00 /* Alerts.swift */, + CEA70CCE24CAC3AE001C12E6 /* Obsoletions.swift */, + CE9E95CC24CE786900F6DD78 /* UniversalLinks.swift */, ); path = Classes; sourceTree = ""; @@ -1041,8 +1186,8 @@ C06D37271F81F4E100F61AE0 /* Frameworks */, C06D37281F81F4E100F61AE0 /* Headers */, C06D37291F81F4E100F61AE0 /* Resources */, - CE8D0366240F2FE4002D818C /* ShellScript */, CEC0C66F2410B005003E1BCD /* ShellScript */, + CE880430247F6EB6009BCA1A /* ShellScript */, ); buildRules = ( ); @@ -1152,6 +1297,7 @@ knownRegions = ( en, Base, + km, ); mainGroup = F243887314BBD43000A3E055; productRefGroup = F243887F14BBD43000A3E055 /* Products */; @@ -1180,13 +1326,19 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + CE46D65D247B93C9005FD506 /* (null) in Resources */, 9AD4F53F22A8A286007992D3 /* LanguageSettingsViewController.xib in Resources */, CE37C38B23FCC9EE007031C6 /* Keyboards.bundle in Resources */, CE9B441023FE4E7500499CAB /* Simple 12.0 Migration.bundle in Resources */, 9ADC45A022E1895D004C78C6 /* LanguageLMDetailViewController.xib in Resources */, + CE973D832484A5DC00F66045 /* PackageJSON.bundle in Resources */, CEF888D223FE6ADF00667693 /* No-defaults 10.0 Migration.bundle in Resources */, CE9B440F23FE4E7500499CAB /* 12.0 Ad-hoc Migration.bundle in Resources */, + CE8B5BB22491DA540075CCB0 /* 13.0 Cloud to Package Migration.bundle in Resources */, 9A0FCA0922D7C58B00D33F86 /* Keyman.bundle in Resources */, + CEA9670D24BEEFF80035AACF /* khmer_angkor update-base.bundle in Resources */, + CE02EE0C24A5863100D58F92 /* Queries.bundle in Resources */, + CEA6BA9D249872E8002D44CE /* Simple 13.0 Migration.bundle in Resources */, CEF888D323FE6ADF00667693 /* Simple 10.0 Migration.bundle in Resources */, CE37C38F23FCD52F007031C6 /* Lexical Models.bundle in Resources */, ); @@ -1197,10 +1349,14 @@ buildActionMask = 2147483647; files = ( C06D37601F82095200F61AE0 /* Keyman.bundle in Resources */, + CEA1486C2407808F00C6ECD2 /* Localizable.strings in Resources */, 9ADC459F22E1895D004C78C6 /* LanguageLMDetailViewController.xib in Resources */, - CE754A0223D151B90030CB79 /* ResourceInfoView.xib in Resources */, + CEA14870240780E100C6ECD2 /* ResourceInfoView.xib in Resources */, + CEF9367824D3B0B20031C70D /* PackageInstallView_iPhone.xib in Resources */, 9AD4F53D229F85AC007992D3 /* LanguageSettingsViewController.xib in Resources */, CE7A26D123CEE5790005955C /* Keyboard Colors.xcassets in Resources */, + CE9ECB1E24D3A8CC007C5718 /* PackageInstallView_iPad.xib in Resources */, + CE96E42B24D1229A005B8E5A /* Localizable.stringsdict in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1220,6 +1376,7 @@ 6CD5DFAB150F6DC8007A5DDE /* icon@2x.png in Resources */, 988B36B61ADF67290008752C /* inuktitut_pirurvik-1.0.js in Resources */, 98D4190C17695E58008D2FF3 /* Default-568h@2x.png in Resources */, + CEA1486D2407808F00C6ECD2 /* Localizable.strings in Resources */, CE7A26D423CEE71B0005955C /* Keyboard Colors.xcassets in Resources */, 988B36B91ADF728A0008752C /* inuktitut_latin-1.0.js in Resources */, ); @@ -1239,7 +1396,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "NAME=\"KeymanEngine\"\nUNIVERSAL_DIR=\"${BUILD_DIR}/${CONFIGURATION}-universal/${NAME}.framework\"\nIPHONE_DIR=\"${BUILD_DIR}/${CONFIGURATION}-iphoneos/${NAME}.framework\"\nSIMULATOR_DIR=\"${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${NAME}.framework\"\n\n# Build architecture that was not built\nif [ ${PLATFORM_NAME} = \"iphonesimulator\" ]; then\n xcodebuild -scheme \"${NAME}\" ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphoneos BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" build VERSION=$VERSION VERSION_WITH_TAG=$VERSION_WITH_TAG\nelse\n xcodebuild -scheme \"${NAME}\" -configuration ${CONFIGURATION} -sdk iphonesimulator BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" build VERSION=$VERSION VERSION_WITH_TAG=$VERSION_WITH_TAG\nfi\n\n# Clean\nrm -rf \"${UNIVERSAL_DIR}\"\nmkdir -p \"${UNIVERSAL_DIR}\"\n\n# Use iPhone framework as base\ncp -R \"${IPHONE_DIR}/\" \"${UNIVERSAL_DIR}/\"\n\n# Copy Swift modules from simulator build\ncp -R \"${SIMULATOR_DIR}/Modules/${NAME}.swiftmodule/\" \"${UNIVERSAL_DIR}/Modules/${NAME}.swiftmodule/\"\n\n# Create universal binary using lipo\nlipo -create \"${IPHONE_DIR}/${NAME}\" \"${SIMULATOR_DIR}/${NAME}\" -output \"${UNIVERSAL_DIR}/${NAME}\"\n"; + shellScript = "NAME=\"KeymanEngine\"\nUNIVERSAL_DIR=\"${BUILD_DIR}/${CONFIGURATION}-universal/${NAME}.framework\"\nIPHONE_DIR=\"${BUILD_DIR}/${CONFIGURATION}-iphoneos/${NAME}.framework\"\nSIMULATOR_DIR=\"${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${NAME}.framework\"\n\n# Build architecture that was not built\nif [ ${PLATFORM_NAME} = \"iphonesimulator\" ]; then\n xcodebuild -scheme \"${NAME}\" ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphoneos BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" build VERSION=$VERSION VERSION_WITH_TAG=$VERSION_WITH_TAG VERSION_ENVIRONMENT=$VERSION_ENVIRONMENT UPLOAD_SENTRY=$UPLOAD_SENTRY\nelse\n xcodebuild -scheme \"${NAME}\" -configuration ${CONFIGURATION} -sdk iphonesimulator BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" build VERSION=$VERSION VERSION_WITH_TAG=$VERSION_WITH_TAG VERSION_ENVIRONMENT=$VERSION_ENVIRONMENT UPLOAD_SENTRY=$UPLOAD_SENTRY\nfi\n\n# Clean\nrm -rf \"${UNIVERSAL_DIR}\"\nmkdir -p \"${UNIVERSAL_DIR}\"\n\n# Use iPhone framework as base\ncp -R \"${IPHONE_DIR}/\" \"${UNIVERSAL_DIR}/\"\n\n# Copy Swift modules from simulator build\ncp -R \"${SIMULATOR_DIR}/Modules/${NAME}.swiftmodule/\" \"${UNIVERSAL_DIR}/Modules/${NAME}.swiftmodule/\"\n\n# Create universal binary using lipo\nlipo -create \"${IPHONE_DIR}/${NAME}\" \"${SIMULATOR_DIR}/${NAME}\" -output \"${UNIVERSAL_DIR}/${NAME}\"\n"; }; C0A5FF381F6684A300BE740C /* ShellScript */ = { isa = PBXShellScriptBuildPhase; @@ -1267,7 +1424,7 @@ shellPath = /bin/sh; shellScript = "#if which swiftlint >/dev/null; then\n# swiftlint --config ../../.swiftlint.yml\n#else\n# echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\n#fi\n"; }; - CE8D0366240F2FE4002D818C /* ShellScript */ = { + CE880430247F6EB6009BCA1A /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -1282,7 +1439,8 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = ". \"$KEYMAN_ROOT/resources/build/xcode-utils.sh\"\n\n# Calls resource script to update build products' versioning.\nphaseSetBundleVersions true\n"; + shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n. \"$KEYMAN_ROOT/resources/build/xcode-utils.sh\"\n\nphaseSetBundleVersions true\n"; + showEnvVarsInLog = 0; }; CEC0C66F2410B005003E1BCD /* ShellScript */ = { isa = PBXShellScriptBuildPhase; @@ -1300,7 +1458,8 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n. \"$KEYMAN_ROOT/resources/build/xcode-utils.sh\"\n\n# Calls resource script to perform the dSYM upload\nphaseSentryDsymUpload \"keyman-ios\"\n"; + shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n. \"$KEYMAN_ROOT/resources/build/xcode-utils.sh\"\n\nif [ ${UPLOAD_SENTRY:-false} = true ]; then\n # Calls resource script to perform the dSYM upload\n phaseSentryDsymUpload \"keyman-ios\"\nfi\n"; + showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ @@ -1318,14 +1477,36 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + CE07E3D2247E3FB100DFA9D2 /* HTTPDownloaderTests.swift in Sources */, CE9B440C23FE49F000499CAB /* Migrations.swift in Sources */, + CEE0321124C56735005BFC73 /* Packages.swift in Sources */, + CE88042F247F4B97009BCA1A /* ExpectationDownloaderDelegate.swift in Sources */, + CE07E3D8247E43CB00DFA9D2 /* URLSessionDownloadTaskMock.swift in Sources */, CE37C39123FCD617007031C6 /* LexicalModels.swift in Sources */, CE37C38D23FCD41E007031C6 /* Keyboards.swift in Sources */, + CEA9670B24BEC8030035AACF /* EngineStateBundler.swift in Sources */, CE9CD88323FCC4E3002BF2F8 /* UserDefaults.swift in Sources */, + CE8B0BBD248734240045EB2E /* KeymanPackageTests.swift in Sources */, + CE02EE0E24A5869500D58F92 /* Queries.swift in Sources */, + CE973D852484A71700F66045 /* KMPJSONTests.swift in Sources */, + CE02EE1024A5892200D58F92 /* URLSessionDataTaskMock.swift in Sources */, + CE89642524A46D0000D5EB8E /* QueryPackageVersionTests.swift in Sources */, + CE5C8BE524B5BD1C00FAFB7F /* QueryModelTests.swift in Sources */, + CEA9670F24BEF05A0035AACF /* Updates.swift in Sources */, + CE97866224C7DD1A00C5DCBC /* KeyboardSearchTests.swift in Sources */, + CE9A749A24DBA576003C3B65 /* AssociatingPackageInstallerTests.swift in Sources */, CEF888D523FE786C00667693 /* KeyboardScaleTests.swift in Sources */, + CEA9670924BEC4030035AACF /* ResourceUpdateTests.swift in Sources */, + CE07E3D6247E41DB00DFA9D2 /* URLSessionMock.swift in Sources */, + CE99351024D8018B00202DA3 /* LanguagePickAssociatorTests.swift in Sources */, CE8EDEB323F53F96009E1FF6 /* VersionTests.swift in Sources */, + CEB8276724C6811800F3D39C /* KeymanHostTests.swift in Sources */, CEDFEF8F23FE43B700BECF39 /* MigrationTests.swift in Sources */, + CED8B63224A9C2400054E300 /* ResourceDownloadManagerTests.swift in Sources */, CE9CD88023FCC1CA002BF2F8 /* TestUtils.swift in Sources */, + CE9E95CF24CE7A2C00F6DD78 /* UniversalLinkTests.swift in Sources */, + CE973D812484A56500F66045 /* PackageJSON.swift in Sources */, + CE88143A24A9B7F4002809C3 /* ResourceDownloadQueueTests.swift in Sources */, CE8EDEB123F53D1A009E1FF6 /* FileManagementTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1338,6 +1519,7 @@ 9A079E43223B61AE00581263 /* FullLexicalModelID.swift in Sources */, C06D37341F81F5C300F61AE0 /* HTTPDownloader.swift in Sources */, C0452BAF1F9F22A80064431A /* Font.swift in Sources */, + CE973D892484DBA600F66045 /* KMPSystem.swift in Sources */, C0D3F3601F9F3AD80055C7CF /* InstallableKeyboard.swift in Sources */, CE7A26D923CEEC640005955C /* Colors+Extension.swift in Sources */, CE1E1EC12303C8CC001C7BE0 /* ResourceDownloadStatusToolbar.swift in Sources */, @@ -1347,23 +1529,27 @@ CE24ECF021B763740052D291 /* KeymanResponder+Types.swift in Sources */, C0324B8F1F8750B700AF3785 /* TextView.swift in Sources */, C08E698D1FDA392D0026056B /* Migrations.swift in Sources */, - C07A9D8C1FD176AB00828ADD /* KeyboardRepositoryDelegate.swift in Sources */, CE17ABDE23069E76005FBB14 /* LanguageResource.swift in Sources */, C024C9961FA6EC650060583B /* NotificationCenter+Typed.swift in Sources */, C06D37361F81F5C300F61AE0 /* KeyboardMenuView.swift in Sources */, CE67D961228A6F190029F2B5 /* KeyboardCommandStructs.swift in Sources */, - 9A4609972241B39B00B0BFD1 /* LexicalModelInfoViewController.swift in Sources */, + CE87751E24C68DA500B1475A /* KeyboardSearchViewController.swift in Sources */, + CE8B0BBF248764ED0045EB2E /* KMPResource.swift in Sources */, 9AD4F53C229F85AC007992D3 /* LanguageSettingsViewController.swift in Sources */, CE7A26DB23CEEF640005955C /* Colors.swift in Sources */, 9A9CB08022416E5400231FB9 /* LexicalModelPickerViewController.swift in Sources */, 9A079E3D223B5FAF00581263 /* InstallableLexicalModel.swift in Sources */, C06D37381F81F5C400F61AE0 /* SubKeysView.swift in Sources */, C0A93A541F8B21240079948B /* Manager.swift in Sources */, + CE99350E24D7CCFC00202DA3 /* LanguagePickAssociator.swift in Sources */, C024C9981FA6F2340060583B /* NotificationObserver.swift in Sources */, 9ADC459D22E1895D004C78C6 /* LanguageLMDetailViewController.swift in Sources */, C0B901AA1FA1AFC200764EB8 /* UserDefaults+Types.swift in Sources */, CE1F67A32304EB3800FF6972 /* ResourceDownloadManager.swift in Sources */, 9A079E372238680700581263 /* KMPLexicalModel.swift in Sources */, + CE9E95CD24CE786900F6DD78 /* UniversalLinks.swift in Sources */, + CE89641F24A4686000D5EB8E /* Queries.swift in Sources */, + CE5C8BE324B5B3BA00FAFB7F /* Queries+LexicalModel.swift in Sources */, 9A3E832522EAC14A00D22D2A /* KeyboardSwitcherViewController.swift in Sources */, C0324B911F8763E100AF3785 /* TextViewDelegateProxy.swift in Sources */, C0B09EAE1FCFD10F002F39AF /* FontManager.swift in Sources */, @@ -1371,13 +1557,12 @@ CEC0C6772410E049003E1BCD /* SentryManager.swift in Sources */, 9A079E3A223AFF3C00581263 /* KeyboardKeymanPackage.swift in Sources */, C06D37401F81F5C400F61AE0 /* LanguageDetailViewController.swift in Sources */, - 9A9CB0862241717C00231FB9 /* LexicalModelRepositoryDelegate.swift in Sources */, C0CB633C1FA6F61500617CDB /* Notifications.swift in Sources */, + CE867FF12485EE1500B2EAED /* KMPInfo.swift in Sources */, C0EF3E7B1F95B65300CE9BD4 /* KeymanWebDelegate.swift in Sources */, C06D37411F81F5C400F61AE0 /* LanguageViewController.swift in Sources */, C06D37421F81F5C400F61AE0 /* KeyboardPickerButton.swift in Sources */, 165EB3A12098993900040A69 /* KeyboardError.swift in Sources */, - C05F432D1FBD5A4C0058CBD4 /* KeyboardAPICall.swift in Sources */, CE7ADD6623DE89FC00BC9A00 /* Alerts.swift in Sources */, CE754A0423D162E90030CB79 /* ResourceInfoViewController.swift in Sources */, C055E6EB1F99ED090035C2DD /* RegisteredFont.swift in Sources */, @@ -1390,29 +1575,33 @@ C082CE151F90AFD400860F02 /* Collection+SafeAccess.swift in Sources */, C06D37441F81F5C400F61AE0 /* KeyboardNameTableViewCell.swift in Sources */, 9A3B14D2229370B20052A11F /* InstalledLanguagesViewController.swift in Sources */, - C07A9D8A1FD1762700828ADD /* KeyboardRepository.swift in Sources */, + CEE0321324C58C90005BFC73 /* KeymanHosts.swift in Sources */, C08E69911FDA6F6F0026056B /* FullKeyboardID.swift in Sources */, - 9A9CB0822241704800231FB9 /* APILexicalModelRepository.swift in Sources */, + CEA70CCF24CAC3AE001C12E6 /* Obsoletions.swift in Sources */, C040E5101F8606E300901EE4 /* TextField.swift in Sources */, CE71705823A9C14D00A924A1 /* ResourceFileManager.swift in Sources */, 9A082559227589360051EBB0 /* Formatter+ISODateExtension.swift in Sources */, + CE867FEF2485E97A00B2EAED /* KMPMetadata.swift in Sources */, C0324B8D1F87480700AF3785 /* TextFieldDelegateProxy.swift in Sources */, + CE973D8B2484DCA300F66045 /* KMPOptions.swift in Sources */, C075EB061F8EFF870041F4BD /* String+Helpers.swift in Sources */, 1645D5952036C6FF0076C51B /* KeymanPackage.swift in Sources */, 9A079E40223B602B00581263 /* LexicalModel.swift in Sources */, + CE9A7A7924DA55D5007CCB5F /* AssociatingPackageInstaller.swift in Sources */, C0E30C8C1FC40D0400C80416 /* Storage.swift in Sources */, C045148A1F85DF9100D88416 /* InputViewController.swift in Sources */, CE22DFBA230B94DB00A4551C /* ResourceDownloadQueue.swift in Sources */, - 9A9CB084224170F700231FB9 /* LexicalModelRepository.swift in Sources */, + CE973D872484BBC200F66045 /* KMPLanguage.swift in Sources */, + CE89642124A468B200D5EB8E /* Queries+PackageVersion.swift in Sources */, C06D37461F81F5C400F61AE0 /* PopoverView.swift in Sources */, 9A4609992242047400B0BFD1 /* LexicalModelAPICall.swift in Sources */, C007C4651F9F52D8006461B9 /* LanguagesAPICall.swift in Sources */, C024C9941FA6EB470060583B /* NotificationName.swift in Sources */, C0C16A891FA8146300F090BA /* KeymanWebViewController.swift in Sources */, + CE973D8D2484DD1900F66045 /* KMPFile.swift in Sources */, 9A079DCA222E050E00581263 /* LexicalModelKeymanPackage.swift in Sources */, 9A60764422893A4E003BCFBA /* SettingsViewController.swift in Sources */, C06085B41F9485E40057E5B9 /* UIButton+Helpers.swift in Sources */, - C07A9D8E1FD1798900828ADD /* APIKeyboardRepository.swift in Sources */, C0959CD41F99C44E00B616BC /* Constants.swift in Sources */, C0452BAD1F9F21270064431A /* Keyboard.swift in Sources */, CE79B24923C711FF007E72AE /* KeyboardScaleMap.swift in Sources */, @@ -1487,6 +1676,35 @@ }; /* End PBXTargetDependency section */ +/* Begin PBXVariantGroup section */ + CE96E42D24D1229A005B8E5A /* Localizable.stringsdict */ = { + isa = PBXVariantGroup; + children = ( + CE96E42C24D1229A005B8E5A /* en */, + ); + name = Localizable.stringsdict; + sourceTree = ""; + }; + CEA1486F2407808F00C6ECD2 /* Localizable.strings */ = { + isa = PBXVariantGroup; + children = ( + CEA1486E2407808F00C6ECD2 /* en */, + ); + name = Localizable.strings; + sourceTree = ""; + }; + CEA14872240780E100C6ECD2 /* ResourceInfoView.xib */ = { + isa = PBXVariantGroup; + children = ( + CEA14871240780E100C6ECD2 /* Base */, + CEA14874240780EF00C6ECD2 /* en */, + CEA148772407869200C6ECD2 /* km */, + ); + name = ResourceInfoView.xib; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + /* Begin XCBuildConfiguration section */ 98F9D6A41954112F0087AA43 /* Debug */ = { isa = XCBuildConfiguration; @@ -1698,6 +1916,8 @@ PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; PROVISIONING_PROFILE_SPECIFIER = ""; SKIP_INSTALL = YES; + STRIP_INSTALLED_PRODUCT = NO; + STRIP_SWIFT_SYMBOLS = NO; SUPPORTS_MACCATALYST = NO; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; @@ -1759,9 +1979,12 @@ isa = XCBuildConfiguration; baseConfigurationReference = F27FCAF6157FD95E00FBBA20 /* Keyman-lib.xcconfig */; buildSettings = { - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; ONLY_ACTIVE_ARCH = NO; PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + STRIP_STYLE = all; + STRIP_SWIFT_SYMBOLS = NO; VALID_ARCHS = "arm64 armv7s armv7 x86_64 i386"; }; name = Debug; @@ -1770,7 +1993,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = F27FCAF6157FD95E00FBBA20 /* Keyman-lib.xcconfig */; buildSettings = { - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; PRODUCT_NAME = "$(TARGET_NAME)"; VALID_ARCHS = "arm64 armv7s armv7 x86_64 i386"; }; @@ -1882,7 +2105,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; KEYMAN_ROOT = "$(SRCROOT)/../../.."; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -1944,7 +2167,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = F27FCAF6157FD95E00FBBA20 /* Keyman-lib.xcconfig */; buildSettings = { - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; ONLY_ACTIVE_ARCH = NO; PRODUCT_NAME = "$(TARGET_NAME)"; VALID_ARCHS = "arm64 armv7s armv7 x86_64 i386"; @@ -2141,7 +2364,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; KEYMAN_ROOT = "$(SRCROOT)/../../.."; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -2185,7 +2408,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; KEYMAN_ROOT = "$(SRCROOT)/../../.."; ONLY_ACTIVE_ARCH = NO; SDKROOT = iphoneos; diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Alerts.swift b/ios/engine/KMEI/KeymanEngine/Classes/Alerts.swift index 7e3ef343c27097ee670356c669a9ea07c19f6a2c..ce5dfd32bdf190ea3311eed817c571b872d4eed8 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Alerts.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Alerts.swift @@ -13,11 +13,23 @@ import Reachability open class Alerts { public typealias AcceptanceHandler = ((UIAlertAction)) -> Void + public static func constructActivitySpinner() -> UIActivityIndicatorView { + let activitySpinner: UIActivityIndicatorView + activitySpinner = UIActivityIndicatorView(style: .whiteLarge) + activitySpinner.hidesWhenStopped = true + activitySpinner.translatesAutoresizingMaskIntoConstraints = false + activitySpinner.backgroundColor = Colors.spinnerBackground + activitySpinner.layer.cornerRadius = 6.0 + activitySpinner.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, + .flexibleBottomMargin] + return activitySpinner + } + public static func showErrorAlert(in vc: UIViewController, title: String, msg: String, handler: @escaping AcceptanceHandler) { let alertController = UIAlertController(title: title, message: msg, preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "OK", + alertController.addAction(UIAlertAction(title: NSLocalizedString("command-ok", bundle: engineBundle, comment: ""), style: UIAlertAction.Style.default, handler: handler)) @@ -25,13 +37,16 @@ open class Alerts { } public static func showConnectionErrorAlert(in vc: UIViewController, handler: @escaping AcceptanceHandler) { - showErrorAlert(in: vc, title: "Connection Error", msg: "Could not reach Keyman server. Please try again later.", handler: handler) + showErrorAlert(in: vc, + title: NSLocalizedString("alert-no-connection-title", bundle: engineBundle, comment: ""), + msg: NSLocalizedString("alert-no-connection-detail", bundle: engineBundle, comment: ""), + handler: handler) } public static func showDownloadErrorAlert(in vc: UIViewController, handler: @escaping AcceptanceHandler) { var networkReachable: Reachability? do { - try networkReachable = Reachability(hostname: "keyman.com") + try networkReachable = Reachability(hostname: KeymanHosts.KEYMAN_COM.host!) } catch { log.debug("reachability could not start") } @@ -40,7 +55,10 @@ open class Alerts { showConnectionErrorAlert(in: vc, handler: handler) } else { // Show a different alert! - showErrorAlert(in: vc, title: "Download error", msg: "Error occurred during download or installation.", handler: handler) + showErrorAlert(in: vc, + title: NSLocalizedString("alert-download-error-title", bundle: engineBundle, comment: ""), + msg: NSLocalizedString("alert-download-error-detail", bundle: engineBundle, comment: ""), + handler: handler) } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Constants.swift b/ios/engine/KMEI/KeymanEngine/Classes/Constants.swift index 0e0282d9fcc4a41f641c7662edce8e54c5052464..f5df13d193b81c6ad3d3cde9353938a7b78f61ef 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Constants.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Constants.swift @@ -18,6 +18,9 @@ public enum Key { /// Array of user lexical models info list in UserDefaults static let userLexicalModelsList = "UserLexicalModelsList" + /// Dictionary of cached query results for a user's installed packages + static let userPackageQueryCacheDict = "UserQueryDistributionStateCache" + /// Currently/last selected keyboard info in UserDefaults static let userCurrentKeyboard = "UserCurrentKeyboard" @@ -69,7 +72,7 @@ public enum Defaults { name: "EuroLatin (SIL)", languageID: "en", languageName: "English", - version: "1.8.1", + version: "1.9.1", isRTL: false, font: font, oskFont: nil, @@ -121,3 +124,22 @@ public enum FileExtensions { public static let openTypeFont = "otf" public static let configurationProfile = "mobileconfig" } + +public enum KeymanError: Error, LocalizedError { + case unknown + // file that is missing, is the file critical? + case missingFile(String, Bool) + + var localizedDescription: String { + switch self { + case .unknown: + return engineBundle.localizedString(forKey: "error-unknown", value: nil, table: nil) + case .missingFile(_, let isCritical): + if isCritical { + return engineBundle.localizedString(forKey: "error-missing-file-critical", value: nil, table: nil) + } else { + return engineBundle.localizedString(forKey: "error-missing-file", value: nil, table: nil) + } + } + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Errors/SentryManager.swift b/ios/engine/KMEI/KeymanEngine/Classes/Errors/SentryManager.swift index f2595f598aa62ef7c3d96e11031ba971a9012415..a74109e78be9139d36206285e6a6bfc625e12363 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Errors/SentryManager.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Errors/SentryManager.swift @@ -30,16 +30,16 @@ public class SentryManager { log.debug("Sentry error logging enabled.") #endif - #if DEBUG - let environment = "DEVELOPMENT-\(Version.currentTagged.majorMinor.fullString)" - #else - let environment = "PRODUCTION-\(Version.currentTagged.majorMinor.fullString)" - #endif + let infoDict = Bundle.main.infoDictionary + let versionWithTag = infoDict?["KeymanVersionWithTag"] as? String ?? "" + let environment = infoDict?["KeymanVersionEnvironment"] as? String ?? "" + let release = "release-\(versionWithTag)" let options: [String: Any] = [ "dsn": "https://d14d2efb594e4345b8367dbb61ebceaf@sentry.keyman.com/8", "enabled": allowEnabled && sendingEnabled, - "environment": environment + "environment": environment, + "release": release ] Sentry.Client.shared = try Sentry.Client(options: options) try Sentry.Client.shared?.startCrashHandler() diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Extension/UserDefaults+Types.swift b/ios/engine/KMEI/KeymanEngine/Classes/Extension/UserDefaults+Types.swift index 2c5ee5c027725dc85e70eab649353df8740dc6c5..78063ec766a9898d9c54051c2293e3565cbb94eb 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Extension/UserDefaults+Types.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Extension/UserDefaults+Types.swift @@ -36,6 +36,21 @@ public extension UserDefaults { } } + internal func cachedPackageQueryMetadata(forKey key: String) -> [KeymanPackage.Key: KeymanPackage.DistributionStateMetadata]? { + guard let data = self.data(forKey: key) else { + log.error("Error decoding cached package query results") + return nil + } + + // Since we're dealing with dictionaries & Codable, it's probably better to use JSON here. + let decoder = JSONDecoder() + if let dict = try? decoder.decode([KeymanPackage.Key: KeymanPackage.DistributionStateMetadata].self, from: data) { + return dict + } else { + return nil + } + } + func set(_ keyboards: [InstallableKeyboard]?, forKey key: String) { guard let keyboards = keyboards else { removeObject(forKey: key) @@ -134,12 +149,35 @@ public extension UserDefaults { } } - var userResources: [LanguageResource]? { + internal var cachedPackageQueryMetadata: [KeymanPackage.Key: KeymanPackage.DistributionStateMetadata] { + get { + return cachedPackageQueryMetadata(forKey: Key.userPackageQueryCacheDict) ?? [:] + } + + set(metadata) { + let encoder = JSONEncoder() + if let data = try? encoder.encode(metadata) { + set(data, forKey: Key.userPackageQueryCacheDict) + } + } + } + + func userResources(ofType: Resource.Type) -> [Resource]? { + if ofType == InstallableKeyboard.self { + return (userKeyboards as? [Resource]) + } else if ofType == InstallableLexicalModel.self { + return (userLexicalModels as? [Resource]) + } else { + return nil + } + } + + var userResources: [AnyLanguageResource]? { get { let keyboards = userKeyboards ?? [] let lexicalModels = userLexicalModels ?? [] - let resources: [LanguageResource] = keyboards + lexicalModels + let resources: [AnyLanguageResource] = keyboards + lexicalModels if resources.count == 0 { return nil } else { @@ -212,6 +250,10 @@ public extension UserDefaults { }) ?? [] } + internal func cachedPackageQueryResult(forPackageKey packageKey: KeymanPackage.Key) -> KeymanPackage.DistributionStateMetadata? { + return cachedPackageQueryMetadata[packageKey] + } + var migrationLevel: Int { get { return integer(forKey: Key.migrationLevel) diff --git a/ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloadRequest.swift b/ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloadRequest.swift index 23ca0e08156b1676b115ad054c09251294f56072..d5b2a81fe0fadd3c02550d6a950f0fe9997305ff 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloadRequest.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloadRequest.swift @@ -8,7 +8,7 @@ import Foundation -enum DownloadType { +enum DownloadType: String { case downloadFile } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloader.swift b/ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloader.swift index 39d10c175adeb1fe64aa1fe3a637cc1e50345768..7a2f0053c0b7274f5cde7fa8f74d7d6b007b350c 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloader.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloader.swift @@ -11,29 +11,28 @@ import Foundation protocol HTTPDownloadDelegate: class { func downloadRequestStarted(_ request: HTTPDownloadRequest) func downloadRequestFinished(_ request: HTTPDownloadRequest) - func downloadRequestFailed(_ request: HTTPDownloadRequest) + func downloadRequestFailed(_ request: HTTPDownloadRequest, with: Error?) func downloadQueueFinished(_ queue: HTTPDownloader) func downloadQueueCancelled(_ queue: HTTPDownloader) } -class HTTPDownloader: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate, -URLSessionDataDelegate { +class HTTPDownloader: NSObject { var queue: [HTTPDownloadRequest] = [] // TODO: Make unowned weak var handler: HTTPDownloadDelegate? var currentRequest: HTTPDownloadRequest? var downloadSession: URLSession! public var userInfo: [String: Any] = [:] + var isCancelled: Bool = false - init(_ handler: HTTPDownloadDelegate?) { + init(_ handler: HTTPDownloadDelegate?, session: URLSession = .shared) { super.init() self.handler = handler - - let config = URLSessionConfiguration.default - downloadSession = URLSession(configuration: config, delegate: self, delegateQueue: nil) + downloadSession = session } func addRequest(_ request: HTTPDownloadRequest) { + isCancelled = false queue.append(request) } @@ -46,6 +45,7 @@ URLSessionDataDelegate { // Starts the queue. The queue is managed via event messages in order to process them sequentially. func run() { + isCancelled = false if !queue.isEmpty { runRequest() } @@ -59,23 +59,45 @@ URLSessionDataDelegate { currentRequest = req if req.typeCode == .downloadFile { - req.task = downloadSession.downloadTask(with: req.url) + req.task = downloadSession.downloadTask(with: req.url, completionHandler: self.downloadCompletionHandler) handler?.downloadRequestStarted(req) } req?.task?.resume() - } else { + } else if !isCancelled { handler?.downloadQueueFinished(self) } // The next step in the queue, should it exist, will be triggered by urlSession(_, task:, didCompleteWithError:) // which calls this method. Thus, this method may serve as the single source of the 'queue finished' message. } - // This is triggered before the 'didCompleteWithError' delegate method. - func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) { + func downloadCompletionHandler(location: URL?, response: URLResponse?, error: Error?) -> Void { guard let currentRequest = currentRequest else { return } + + // If it's an error case + guard let location = location else { + // If location is `nil`, we have an error. + // See docs at https://developer.apple.com/documentation/foundation/urlsession/1411511-downloadtask + // + // Force the callback onto the main thread. + DispatchQueue.main.async { + self.handler?.downloadRequestFailed(currentRequest, with: nil) + self.runRequest() + } + return + } + + guard error == nil else { + // The download process itself encountered an error. + DispatchQueue.main.async { + self.handler?.downloadRequestFailed(currentRequest, with: error) + self.runRequest() + } + return + } + + // Successful download. log.debug("Downloaded file \(currentRequest.url) as \(location), " + "to be copied to \(currentRequest.destinationFile ?? "nil")") @@ -95,31 +117,31 @@ URLSessionDataDelegate { log.error("Error saving the download: \(error)") } } - } - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) { - // We only evaluate one at a time, so the 'current request' holds the data task's original request data. - currentRequest?.rawResponseData = proposedResponse.data - completionHandler(proposedResponse) - // With current internal settings, this will cache the data as we desire. + DispatchQueue.main.async { + self.handler?.downloadRequestFinished(currentRequest) + self.runRequest() + } } - func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - let req = currentRequest - currentRequest = nil - if task.error != nil { - //Force the callback onto the main thread. - DispatchQueue.main.async { - self.handler?.downloadRequestFailed(req!) - } - } else { + func dataCompletionHandler(data: Data?, response: URLResponse?, error: Error?) -> Void { + guard let currentRequest = currentRequest else { + return + } + + guard let data = data else { DispatchQueue.main.async { - self.handler?.downloadRequestFinished(req!) + self.handler?.downloadRequestFailed(currentRequest, with: nil) + self.runRequest() } + return } + // We only evaluate one at a time, so the 'current request' holds the data task's original request data. + currentRequest.rawResponseData = data + // With current internal settings, this will cache the data as we desire. + DispatchQueue.main.async { + self.handler?.downloadRequestFinished(currentRequest) self.runRequest() } } @@ -135,6 +157,7 @@ URLSessionDataDelegate { } self.handler?.downloadQueueCancelled(self) + self.isCancelled = true } var requestsCount: Int { diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardKeymanPackage.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardKeymanPackage.swift new file mode 100644 index 0000000000000000000000000000000000000000..5d8a1a3e5b27bb993277864a7935de34706507dc --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardKeymanPackage.swift @@ -0,0 +1,46 @@ +// +// KeyboardKeymanPackage.swift +// KeymanEngine +// +// Created by Randy Boring on 3/14/19. +// Copyright © 2019 SIL International. All rights reserved. +// + +import Foundation + +public class KeyboardKeymanPackage : TypedKeymanPackage { + internal var keyboards: [KMPKeyboard]! + + override internal init(metadata: KMPMetadata, folder: URL) { + super.init(metadata: metadata, folder: folder) + self.keyboards = [] + + if let packagedKeyboards = metadata.keyboards { + for keyboard in packagedKeyboards { + keyboard.packageId = self.id + + if(keyboard.isValid && FileManager.default.fileExists(atPath: self.sourceFolder.appendingPathComponent("\(keyboard.keyboardId).js").path)) { + keyboards.append(keyboard) + } else { + log.debug("\(keyboard.name) not valid / corresponding file not found") + } + } + } + + self.setInstallableResourceSets(for: keyboards) + } + + public override func defaultInfoHtml() -> String { + let formatString = NSLocalizedString("package-default-found-keyboards", bundle: engineBundle, comment: "See Localized.stringsdict") + var str = String.localizedStringWithFormat(formatString, keyboards.count) + "
" + for keyboard in keyboards { + str += keyboard.keyboardId + "
" + } + return str + } + + override var resources: [AnyKMPResource] { + return keyboards + } +} + diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardMenuView.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardMenuView.swift index f5089a472b65c1a493c63b1db6c41c205183dfd0..94238dba5bea62543a47dd4b1b6e99bee9892e7b 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardMenuView.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardMenuView.swift @@ -45,7 +45,8 @@ class KeyboardMenuView: UIView, UITableViewDelegate, UITableViewDataSource, UIGe titleCloseButton = closeButtonTitle } else { let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? "Keyman" - titleCloseButton = "Close \(appName)" + let format = NSLocalizedString("keyboard-menu-exit", bundle: engineBundle, comment: "") + titleCloseButton = String.localizedStringWithFormat(format, appName) } if let keyboardList = keyboardList { diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/APIKeyboardRepository.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/APIKeyboardRepository.swift deleted file mode 100644 index 98c7fccb00011135bb90349b013bab65a9b689b6..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/APIKeyboardRepository.swift +++ /dev/null @@ -1,140 +0,0 @@ -// -// APIKeyboardRepository.swift -// KeymanEngine -// -// Created by Gabriel Wong on 2017-12-01. -// Copyright © 2017 SIL International. All rights reserved. -// - -import Foundation -import UIKit - -public enum APIKeyboardFetchError: Error { - case duplicateLanguageCodes - case networkError(Error) - case noData - case parsingError(Error) -} - -public class APIKeyboardRepository: KeyboardRepository { - private let languagesAPIURL = URLComponents(string: "https://api.keyman.com/cloud/4.0/languages")! - - public weak var delegate: KeyboardRepositoryDelegate? - public private(set) var languages: [String: Language]? - public private(set) var keyboards: [String: Keyboard]? - private(set) var options: Options? - - private func resultsToDictionary(for result: LanguagesAPICall, handler: (_ error: Error) -> Void) -> Dictionary? { - // Detect duplicate ids - this scenario indicates an infrastructure problem. - var dictionary = Dictionary() - var duplicates: [String] = [] - - result.languages.forEach { language in - // Does an entry for this ID already exist? Trouble if so. - if let _ = dictionary[language.id] { - if duplicates.firstIndex(of: language.id) != -1 { - duplicates.append(language.id) - } - } - - dictionary.updateValue(language, forKey: language.id) - } - - guard duplicates.count == 0 else { - // This indicates an issue in our keyboard API infrastructure. - // Don't let it crash the app, but definitely make note of it - // as something to be fixed. - log.error("Corrupt data detected in API returns - duplicate language codes: \(duplicates)") - handler(APIKeyboardFetchError.duplicateLanguageCodes) - return nil - } - - return dictionary - } - - public func fetch(completionHandler: CompletionHandler?) { - let deviceType = UIDevice.current.userInterfaceIdiom == .phone ? "iphone" : "ipad" - let keymanVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String - var urlComponents = languagesAPIURL - urlComponents.queryItems = [ - URLQueryItem(name: "dateformat", value: "seconds"), - URLQueryItem(name: "device", value: deviceType), - URLQueryItem(name: "version", value: keymanVersion), - URLQueryItem(name: "languageidtype", value: "bcp47") - ] - log.info("Connecting to Keyman cloud: \(urlComponents.url!).") - let task = URLSession.shared.dataTask(with: urlComponents.url!) { (data, response, error) in - self.apiCompletionHandler(data: data, response: response, error: error, - fetchCompletionHandler: completionHandler) - } - task.resume() - } - - private func apiCompletionHandler(data: Data?, - response: URLResponse?, - error: Error?, - fetchCompletionHandler: CompletionHandler?) { - let errorHandler = { (error: Error) -> Void in - DispatchQueue.main.async { - self.delegate?.keyboardRepository(self, didFailFetch: error) - fetchCompletionHandler?(error) - } - } - - if let error = error { - log.error("Network error fetching languages: \(error)") - errorHandler(APIKeyboardFetchError.networkError(error)) - return - } - guard let data = data else { - log.error("Language API did not return data") - errorHandler(APIKeyboardFetchError.noData) - return - } - - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - let result: LanguagesAPICall - do { - result = try decoder.decode(LanguagesAPICall.self, from: data) - } catch { - log.error("Failed parsing API languages: \(error)") - errorHandler(APIKeyboardFetchError.parsingError(error)) - return - } - - options = result.options - - // Detect duplicate ids - this scenario indicates an infrastructure problem. - guard let dictionary = resultsToDictionary(for: result, handler: errorHandler) else { - // The helper performs any relevant error handling on our behalf. - return - } - - // Now that we've successfully processed the API returns, assign - // the results to the proper field. - languages = dictionary - - let keyboardsWithID = result.languages.flatMap { language in - language.keyboards?.map { kb in (kb.id, kb) } ?? [] - } - keyboards = Dictionary(keyboardsWithID) { old, new in - var kb = old - if old.languages == nil { - kb.languages = new.languages - return kb - } - if let newLanguages = new.languages { - let oldLanguageIDs = Set(old.languages!.map { $0.id }) - kb.languages!.append(contentsOf: newLanguages.filter { !oldLanguageIDs.contains($0.id) }) - } - return kb - } - - log.info("Request completed -- \(result.languages.count) languages.") - DispatchQueue.main.async { - self.delegate?.keyboardRepositoryDidFetch(self) - fetchCompletionHandler?(nil) - } - } -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/APILexicalModelRepository.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/APILexicalModelRepository.swift deleted file mode 100644 index 7378d8766c7e61f744ef6a8b1d9c2a83b99f676e..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/APILexicalModelRepository.swift +++ /dev/null @@ -1,132 +0,0 @@ -// -// APILexicalModelRepository.swift -// KeymanEngine -// -// Created by Randy Boring on 3/19/19. -// Copyright © 2019 SIL International. All rights reserved. -// - -import Foundation -import UIKit // for UIDevice - -public enum APILexicalModelFetchError: Error { - case networkError(Error) - case noData - case parsingError(Error) -} - -public class APILexicalModelRepository: LexicalModelRepository { - private let modelsAPIURL = URLComponents(string: "https://api.keyman.com/model")! - - public weak var delegate: LexicalModelRepositoryDelegate? - public private(set) var languages: [String: Language]? - public private(set) var lexicalModels: [String: LexicalModel]? - - public func fetch(completionHandler: CompletionHandler?) { - var urlComponents = modelsAPIURL - urlComponents.queryItems = [ - URLQueryItem(name: "q", value: "") - ] - log.info("Connecting to Keyman cloud: \(urlComponents.url!).") - let task = URLSession.shared.dataTask(with: urlComponents.url!) { (data, response, error) in - self.apiCompletionHandler(data: data, response: response, error: error, - fetchCompletionHandler: completionHandler) - } - task.resume() - } - - - public func fetchList(languageID: String, completionHandler: @escaping ListCompletionHandler) { - var urlComponents = modelsAPIURL - let bcp47Value = "bcp47:" + languageID - urlComponents.queryItems = [ - URLQueryItem(name: "q", value: bcp47Value) - ] - log.info("Connecting to Keyman cloud: \(urlComponents.url!).") - let task = URLSession.shared.dataTask(with: urlComponents.url!) { (data, response, error) in - self.apiListCompletionHandler(data: data, response: response, error: error, - fetchCompletionHandler: completionHandler) - } - task.resume() - } - - private func commonErrorCheck(data: Data?, response: URLResponse?, error: Error?, errorForwarder: @escaping (_ error: Error) -> Void) -> LexicalModelAPICall? { - let errorHandler = { (error: Error) -> Void in - DispatchQueue.main.async { - self.delegate?.lexicalModelRepository(self, didFailFetch: error) - errorForwarder(error) - } - } - - if let error = error { - log.error("Network error fetching languages: \(error)") - errorHandler(APILexicalModelFetchError.networkError(error)) - return nil - } - guard let data = data else { - log.error("Language API did not return data") - errorHandler(APILexicalModelFetchError.noData) - return nil - } - - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - let result: LexicalModelAPICall - do { - result = try decoder.decode(LexicalModelAPICall.self, from: data) - } catch { - log.error("Failed parsing API lexical models: \(error)") - errorHandler(APILexicalModelFetchError.parsingError(error)) - return nil - } - - // No errors! - return result - } - - private func apiCompletionHandler(data: Data?, - response: URLResponse?, - error: Error?, - fetchCompletionHandler: CompletionHandler?) { - let errorHandler = { (error: Error) -> Void in - fetchCompletionHandler?(error) - } - - guard let result = commonErrorCheck(data: data, response: response, error: error, errorForwarder: errorHandler) else { - return - } - - let lexicalModels = result.lexicalModels // Simpler debugging this way. - self.lexicalModels = Dictionary(uniqueKeysWithValues: lexicalModels.map { ($0.id, $0) }) - - - log.info("Request list completed -- \(result.lexicalModels.count) lexical models.") - DispatchQueue.main.async { - self.delegate?.lexicalModelRepositoryDidFetchList(self) - fetchCompletionHandler?(nil) - } - } - - private func apiListCompletionHandler(data: Data?, - response: URLResponse?, - error: Error?, - fetchCompletionHandler: @escaping ListCompletionHandler) { - let errorHandler = { (error: Error) -> Void in - fetchCompletionHandler(nil, error) - } - - guard let result = commonErrorCheck(data: data, response: response, error: error, errorForwarder: errorHandler) else { - return - } - - let lexicalModels = result.lexicalModels - self.lexicalModels = Dictionary(uniqueKeysWithValues: result.lexicalModels.map { ($0.id, $0) }) - - - log.info("Request list completed -- \(result.lexicalModels.count) lexical models.") - DispatchQueue.main.async { - self.delegate?.lexicalModelRepositoryDidFetchList(self) - fetchCompletionHandler(lexicalModels, nil) - } - } -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/KeyboardRepository.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/KeyboardRepository.swift deleted file mode 100644 index 54b8f27a5a8851cc970365f299a53fe8ac5fad38..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/KeyboardRepository.swift +++ /dev/null @@ -1,44 +0,0 @@ -// -// KeyboardRepository.swift -// KeymanEngine -// -// Created by Gabriel Wong on 2017-12-01. -// Copyright © 2017 SIL International. All rights reserved. -// - -import Foundation - -public protocol KeyboardRepository: class { - typealias CompletionHandler = (Error?) -> Void - - var delegate: KeyboardRepositoryDelegate? { get set } - var languages: [String: Language]? { get } - var keyboards: [String: Keyboard]? { get } - - func installableKeyboard(withID keyboardID: String, languageID: String) -> InstallableKeyboard? - func fetch(completionHandler: CompletionHandler?) -} - -public extension KeyboardRepository { - func installableKeyboard(withID keyboardID: String, languageID: String) -> InstallableKeyboard? { - guard let keyboard = keyboards?.first(where: { $0.key == keyboardID })?.value else { - return nil - } - - // If the Keyboard (still) supports the requested language, use that one. - guard let language = keyboard.languages?.first(where: {$0.id == languageID}) ?? - // Otherwise, just use the first language listed for the keyboard. - keyboard.languages?.first ?? - // In cases where the keyboard fails to specify any language, use the requested one if it's in the collection. - languages?[languageID] - else { - return nil - } - - return InstallableKeyboard(keyboard: keyboard, language: language, isCustom: false) - } - - func fetch(completionHandler: CompletionHandler? = nil) { - fetch(completionHandler: completionHandler) - } -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/KeyboardRepositoryDelegate.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/KeyboardRepositoryDelegate.swift deleted file mode 100644 index f57b0aea81c5b160bc184a4b7889af2db3494834..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/KeyboardRepositoryDelegate.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// KeyboardRepositoryDelegate.swift -// KeymanEngine -// -// Created by Gabriel Wong on 2017-12-01. -// Copyright © 2017 SIL International. All rights reserved. -// - -import Foundation - -public protocol KeyboardRepositoryDelegate: class { - func keyboardRepositoryDidFetch(_ repository: KeyboardRepository) - func keyboardRepository(_ repository: KeyboardRepository, didFailFetch error: Error) -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/LexicalModelRepository.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/LexicalModelRepository.swift deleted file mode 100644 index 96b7d93a084f137132effdc19e0e74c062394d8b..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/LexicalModelRepository.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// LexicalModelRepository.swift -// KeymanEngine -// -// Created by Randy Boring on 3/19/19. -// Copyright © 2019 SIL International. All rights reserved. -// - -import Foundation - -public protocol LexicalModelRepository: class { - typealias CompletionHandler = (Error?) -> Void - typealias ListCompletionHandler = ([LexicalModel]?, Error?) -> Void // one of the arguments will be nil, depending on success - - var delegate: LexicalModelRepositoryDelegate? { get set } - var languages: [String: Language]? { get } - var lexicalModels: [String: LexicalModel]? { get } - - func installableLexicalModel(withID lexicalModelID: String, languageID: String) -> InstallableLexicalModel? - func fetch(completionHandler: CompletionHandler?) -} - -public extension LexicalModelRepository { - func installableLexicalModel(withID lexicalModelID: String, languageID: String) -> InstallableLexicalModel? { - guard let lexicalModel = lexicalModels?[lexicalModelID] else { - return nil - } - - // If the lexicalModel (still) supports the requested language, use that one. - guard let language = lexicalModel.languages.first(where: {$0 == languageID}) ?? - // Otherwise, just use the first language listed for the lexicalModel. - lexicalModel.languages.first - else { - return nil - } - - return InstallableLexicalModel(lexicalModel: lexicalModel, languageID: language, isCustom: false) - } - - func fetch(completionHandler: CompletionHandler? = nil) { - fetch(completionHandler: completionHandler) - } -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/LexicalModelRepositoryDelegate.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/LexicalModelRepositoryDelegate.swift deleted file mode 100644 index a78750f1826aa5dd93278872c753a3d5aa70c44b..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/KeyboardRepository/LexicalModelRepositoryDelegate.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// LexicalModelRepositoryDelegate.swift -// KeymanEngine -// -// Created by Randy Boring on 3/19/19. -// Copyright © 2019 SIL International. All rights reserved. -// - -import Foundation - -public protocol LexicalModelRepositoryDelegate: class { - func lexicalModelRepositoryDidFetchList(_ repository: LexicalModelRepository) - func lexicalModelRepository(_ repository: LexicalModelRepository, didFailFetch error: Error) -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeymanHosts.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeymanHosts.swift new file mode 100644 index 0000000000000000000000000000000000000000..cf312a8e0d41acc597a6ac7c592d436e16b65bc8 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/KeymanHosts.swift @@ -0,0 +1,94 @@ +// +// KeymanHosts.swift +// KeymanEngine +// +// Created by Joshua Horton on 7/20/20. +// Copyright © 2020 SIL International. All rights reserved. + +import Foundation + +/** + * Defines constant-like definitions for Keyman's websites dependent upon the compile-time version + * of the KeymanEngine framework. + * + * Note that as a result, 'alpha', 'beta', and 'stable' versions of KeymanEngine may point to different + * sites. + */ +public enum KeymanHosts { + /** + * Used to enable '.local' variants of the endpoints for use in local development testing. + */ + internal static let useLocal = false + + // This should never be used outside of the corresponding `static var`... + // save for use in automated testing. + internal static func getApiSiteURL(forTier: Version.Tier, useLocal: Bool) -> URL { + if useLocal { + return URL.init(string: "http://api.keyman.com.local")! + } else { + switch forTier { + case .alpha: + fallthrough + case .beta: + return URL.init(string: "https://api.keyman-staging.com")! + case .stable: + return URL.init(string: "https://api.keyman.com")! + } + } + } + + /** + * Used for package-version and model queries. + */ + public static var API_KEYMAN_COM: URL { + return getApiSiteURL(forTier: Version.currentTagged.tier ?? .stable, useLocal: useLocal) + } + + // This should never be used outside of the corresponding `static var`... + // save for use in automated testing. + internal static func getHelpSiteURL(forTier: Version.Tier, useLocal: Bool) -> URL { + if useLocal { + return URL.init(string: "http://help.keyman.com.local")! + } else { + switch forTier { + case .alpha: + fallthrough + case .beta: + return URL.init(string: "https://help.keyman-staging.com")! + case .stable: + return URL.init(string: "https://help.keyman.com")! + } + } + } + + /** + * Used for online help. + */ + public static var HELP_KEYMAN_COM: URL { + return getHelpSiteURL(forTier: Version.currentTagged.tier ?? .stable, useLocal: useLocal) + } + + // This should never be used outside of the corresponding `static var`... + // save for use in automated testing. + internal static func getMainSiteURL(forTier: Version.Tier, useLocal: Bool) -> URL { + if useLocal { + return URL.init(string: "http://keyman.com.local")! + } else { + switch forTier { + case .alpha: + fallthrough + case .beta: + return URL.init(string: "https://keyman-staging.com")! + case .stable: + return URL.init(string: "https://keyman.com")! + } + } + } + + /** + * Used for keyboard searches and resource sharing links. + */ + public static var KEYMAN_COM: URL { + return getMainSiteURL(forTier: Version.currentTagged.tier ?? .stable, useLocal: useLocal) + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeymanPackage.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeymanPackage.swift new file mode 100644 index 0000000000000000000000000000000000000000..84034bbeeb505abb73813e09a147e1f903854d65 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/KeymanPackage.swift @@ -0,0 +1,572 @@ +// +// KeymanPackage.swift +// KeymanEngine +// +// Created by Jacob Bullock on 2/16/18. +// Copyright © 2018 SIL International. All rights reserved. +// + +import Foundation +import Zip + +// KMPErrors may be passed to UIAlertControllers, so they need localization. +public enum KMPError : String, Error { + // The value: the translation-lookup key. + case noMetadata = "kmp-error-no-metadata" + case invalidPackage = "kmp-error-invalid" + case fileSystem = "kmp-error-file-system" + case copyFiles = "kmp-error-file-copying" + // TODO: Consider changing the parent type so that these may take arguments that may be used + // to provide better clarity. + case wrongPackageType = "kmp-error-wrong-type" + case resourceNotInPackage = "kmp-error-missing-resource" + + var localizedDescription: String { + return engineBundle.localizedString(forKey: self.rawValue, value: nil, table: nil) + } +} + +/** + * Common base class for the different KeymanPackage types. If Swift had abstract classes, this would be one. + * + * Provides type-agnostic common operations on behalf of TypedKeymanPackage while otherwise providing "type erasure" + * services for it. + */ +public class KeymanPackage { + /** + * Similar in role to LanguageResourceFullID, but for packages, rather than resource-languge pairings. + * + * Provides a unique, hashable key for use with package-oriented operations. + */ + public struct Key: Hashable, Codable { + var id: String + var type: LanguageResourceType + + internal init(for package: KeymanPackage) { + self.id = package.id + self.type = package.resourceType() + } + + internal init(forResource resource: AnyLanguageResource) { + self.id = resource.packageID ?? resource.id + self.type = resource.fullID.type + } + + internal init(id: String, type: LanguageResourceType) { + self.id = id + self.type = type + } + + public static func == (lhs: KeymanPackage.Key, rhs: KeymanPackage.Key) -> Bool { + return lhs.id == rhs.id && lhs.type == rhs.type + } + } + + /** + * Indicates the distribution level and state of the package. + */ + public enum DistributionMethod: String, Codable { + /** + * Indicates that the distribution method for the package is currently unknown. Generally occurs when a + * package is installed via file-sharing before KeymanEngine is able to perform a package-version check. + */ + case unknown + + /** + * Indicates that the package is publicly distributed via Keyman's cloud API is is no longer maintained. + * Other, better-maintained packages targetting the same language exist and are more favored. + */ + case cloudDeprecated = "cloud-deprecated" + + /** + * Indicates that this package is publicly distributed via Keyman's cloud API and is considered well-maintained. + */ + case cloud + + /** + * Indicates that this package is distributed outside the Keyman cloud API network. As a result, KeymanEngine + * cannot automatically validate or update this resource. + */ + case custom + } + + public enum VersionState: String, Codable { + /** + * KeymanEngine can't track up-to-date versions for custom packages, and we simply don't know before the first update-check for + * any models installed from local files. + */ + case unknown + + /** + * The installed version of this package matches the latest distributed version. + */ + case upToDate + + /** + * There is a publicly-distributed version of the package that is newer than the one currently installed within KeymanEngine. + */ + case needsUpdate + } + + public enum InstallationState: String, Codable { + /** + * Indicates that the package is neither installed nor being downloaded. + * + * While a `KeymanPackage` instance will never return it, external functions such as + * `ResourceFileManager.installState(for:)` that merely perform key-based lookups may.. + */ + case none + + /** + * Indicates that the package not yet installed or downloaded, but is currently _being_ downloaded via KeymanEngine. + * + * While a `KeymanPackage` instance will never return it, external functions such as + * `ResourceFileManager.installState(for:)` that merely perform key-based lookups may.. + */ + case downloading + + /** + * Indicates that this `KeymanPackage` instance has been temporarily extracted for installation from a KMP file, regardless + * of whether or not its contents have already been installed within KeymanEngine. + */ + case pending + + /** + * Indicates that this `KeymanPackage` instance corresponds has been fully installed and was loaded from its installed files, rather + * than its source KMP. + */ + case installed + } + + /** + * Cloud/query related metadata not tracked (or even trackable) within kmp.json regarding the distribution state of a package. + */ + public struct DistributionStateMetadata: Codable { + var latestVersion: String? + var downloadURL: URL? + + var timestampForLastQuery: TimeInterval? + + var distributionMethod: DistributionMethod + + init(from queryResult: Queries.PackageVersion.ResultComponent) { + if let entry = queryResult as? Queries.PackageVersion.ResultEntry { + self.latestVersion = entry.version + self.distributionMethod = .cloud + self.downloadURL = URL.init(string: entry.packageURL) + } else /* if queryResult is Queries.PackageVersion.ResultError */ { + self.latestVersion = nil + // The package-version query knows nothing about it - must be custom. + self.distributionMethod = .custom + self.downloadURL = nil + } + + self.timestampForLastQuery = NSDate().timeIntervalSince1970 + } + + init(downloadURL: URL?) { + latestVersion = nil + timestampForLastQuery = nil + + // Assumption: we cannot install a cloud-deprecated resource from + // in-app cloud-backed searches. + distributionMethod = downloadURL != nil ? .cloud : .unknown + self.downloadURL = downloadURL + } + } + + static private let kmpFile = "kmp.json" + public let sourceFolder: URL + public let id: String + internal let metadata: KMPMetadata + + // Used to denote Packages pending installation; referenced by ResourceFileManager. + internal let isTemp: Bool + + internal init(metadata: KMPMetadata, folder: URL) { + sourceFolder = folder + self.metadata = metadata + + let folderName = folder.lastPathComponent + let cacheDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + var nameComponents = folderName.components(separatedBy: ".") + + // Have we parsed a temporary extraction site? + // This case arises during package installation. + isTemp = folderName.lowercased().hasSuffix(".kmp.zip") && folder.path.contains(cacheDirectory.path) + if isTemp { + nameComponents.removeLast() // .zip + nameComponents.removeLast() // .kmp + } + + // Lexical model packages use .model.kmp, so we remove the final 'model' bit. + if nameComponents.last?.lowercased() == "model" { + nameComponents.removeLast() + } + + self.id = nameComponents.joined(separator: ".") + } + + deinit { + // Temporary packages should clean up after themselves when they go out of scope. + if isTemp { + do { + if FileManager.default.fileExists(atPath: self.sourceFolder.path) { + try FileManager.default.removeItem(at: self.sourceFolder) + } + } catch { + log.debug("Could not remove temporary extraction site on package deinit") + } + } + } + + internal static func baseFilename(for key: KeymanPackage.Key) -> String { + var ext: String + + switch(key.type) { + case .keyboard: + ext = "kmp" + case .lexicalModel: + ext = "model.kmp" + } + + return "\(key.id).\(ext)" + } + + public var key: Key { + return Key(for: self) + } + + public var name: String { + return self.metadata.info?.name?.description ?? id + } + + public func isKeyboard() -> Bool { + return metadata.packageType == .Keyboard + } + + public var distributionMethod: DistributionMethod { + let cachedQueryResult = Storage.active.userDefaults.cachedPackageQueryResult(forPackageKey: self.key) + return cachedQueryResult?.distributionMethod ?? .unknown + } + + public var installState: InstallationState { + // Other possible states are invalid for instantiated packages. + return isTemp ? .pending : .installed + } + + public var versionState: VersionState { + if distributionMethod == .unknown || distributionMethod == .custom { + return .unknown + } else { + let cachedVersion = Version(Storage.active.userDefaults.cachedPackageQueryResult(forPackageKey: self.key)!.latestVersion!)! + + if cachedVersion > self.version { + return .needsUpdate + } else { + return .upToDate + } + } + } + + internal var versionQueryCache: DistributionStateMetadata { + get { + return Storage.active.userDefaults.cachedPackageQueryMetadata[self.key] ?? DistributionStateMetadata(downloadURL: nil) + } + + set(value) { + Storage.active.userDefaults.cachedPackageQueryMetadata[self.key] = value + } + } + + /** + * Returns the type of LanguageResource contained within the parsed Package. + */ + public func resourceType() -> LanguageResourceType { + switch metadata.packageType { + case .Keyboard: + return .keyboard + case .LexicalModel: + return .lexicalModel + default: + // See KeymanPackage.parse below; an error is thrown there for case .Unsupported. + fatalError("KeymanPackage.parse failed to block construction of unsupported KeymanPackage instance") + } + } + + // to be overridden by subclasses + public func defaultInfoHtml() -> String { + return "base class!" + } + + public func infoHtml() -> String { + if let readmeURL = self.readmePageURL { + if let html = try? String(contentsOfFile: readmeURL.path, encoding: String.Encoding.utf8) { + return html + } + } + + return defaultInfoHtml() + } + + public var readmePageURL: URL? { + let readmeURL = self.sourceFolder.appendingPathComponent("readme.htm") + + if FileManager.default.fileExists(atPath: readmeURL.path) { + return readmeURL + } else { + return nil + } + } + + public var welcomePageURL: URL? { + let welcomeURL = self.sourceFolder.appendingPathComponent("welcome.htm") + + if FileManager.default.fileExists(atPath: welcomeURL.path) { + return welcomeURL + } else { + return nil + } + } + + public var version: Version { + if let versionString = metadata.version, let version = Version(versionString) { + return version + } else { + return Version.packageBasedFileReorg + } + } + + var resources: [AnyKMPResource] { + fatalError("abstract base method went uninplemented by derived class") + } + + var languages: [Language] { + fatalError("abstract base method went unimplemented by derived class") + } + + /** + * Returns an array of arrays corresponding to the available permutations of resource + language for each resource + * specified by the package. + * + * Example: nrc.en.mtnt supports three languages. A package containing only said lexical model would return an array + * with 1 entry: an array with three InstallableLexicalModel entries, one for each supported language of the model, identical + * aside from language-specific metadata. + */ + public var installableResourceSets: [[AnyLanguageResource]] { + fatalError("abstract base method went unimplemented by derived class") + } + + public func installableResources(forLanguage lgCode: String) -> [AnyLanguageResource] { + return installableResourceSets.flatMap { $0.filter { $0.languageID == lgCode }} + } + + /** + * Parses a decompressed KMP's metadata file, producing the typed KeymanPackage instance corresponding to it. + * + * Typecast the return value to either KeyboardKeymanPackage or LexicalModelKeymanPackage for richly-typed + * information about the package's contents. + */ + static public func parse(_ folder: URL) -> KeymanPackage? { + do { + var path = folder + path.appendPathComponent(kmpFile) + if FileManager.default.fileExists(atPath: path.path) { + let data = try Data(contentsOf: path, options: .mappedIfSafe) + let decoder = JSONDecoder() + + var metadata: KMPMetadata + + do { + metadata = try decoder.decode(KMPMetadata.self, from: data) + } catch { + throw KMPError.noMetadata + } + + switch metadata.packageType { + case .Keyboard: + return KeyboardKeymanPackage(metadata: metadata, folder: folder) + case .LexicalModel: + return LexicalModelKeymanPackage(metadata: metadata, folder: folder) + default: + throw KMPError.invalidPackage + } + } + } catch { + log.error("error parsing keyman package: \(error)") + } + + return nil + } + + @available(*, deprecated, message: "Use of the completion block is unnecessary; this method now returns synchronously.") + static public func extract(fileUrl: URL, destination: URL, complete: @escaping (KeymanPackage?) -> Void) throws { + try unzipFile(fileUrl: fileUrl, destination: destination) { + complete(KeymanPackage.parse(destination)) + } + } + + static public func extract(fileUrl: URL, destination: URL) throws -> KeymanPackage? { + try unzipFile(fileUrl: fileUrl, destination: destination) + return KeymanPackage.parse(destination) + } + + static public func unzipFile(fileUrl: URL, destination: URL, complete: @escaping () -> Void = {}) throws { + try Zip.unzipFile(fileUrl, destination: destination, overwrite: true, password: nil) + complete() + } + + internal static func forMigration>(of resource: Resource, at location: URL) -> Package? { + let metadata = KMPMetadata(from: resource, packageId: resource.id) + + if let _ = resource as? InstallableKeyboard { + return (KeyboardKeymanPackage(metadata: metadata, folder: location) as! Package) + } else if let _ = resource as? InstallableLexicalModel { + return (LexicalModelKeymanPackage(metadata: metadata, folder: location) as! Package) + } else { + return nil + } + } + + /** + * Runs the package-version query for the specified packages to determine their current support-state. + */ + public static func queryDistributionStates(for keys: [Key], withSession session: URLSession = URLSession.shared, completionBlock: (([Key : DistributionStateMetadata]?, Error?)-> Void)? = nil) { + Queries.PackageVersion.fetch(for: keys, withSession: session) { results, error in + guard error == nil, let results = results else { + completionBlock?(nil, error) + return + } + + var keyboardStates: [Key : DistributionStateMetadata] = [:] + keyboardStates.reserveCapacity(results.keyboards?.count ?? 0) + + // Sadly, Dictionaries do not support mapping to other dictionaries when considering the keys. + results.keyboards?.forEach { key, value in + keyboardStates[KeymanPackage.Key(id: key, type: .keyboard)] = KeymanPackage.DistributionStateMetadata(from: value) + } + + var lexicalModelStates: [Key : DistributionStateMetadata] = [:] + lexicalModelStates.reserveCapacity(results.models?.count ?? 0) + + results.models?.forEach { key, value in + lexicalModelStates[KeymanPackage.Key(id: key, type: .lexicalModel)] = KeymanPackage.DistributionStateMetadata(from: value) + } + + keyboardStates.forEach { result in + Storage.active.userDefaults.cachedPackageQueryMetadata[result.key] = result.value + } + + lexicalModelStates.forEach { result in + Storage.active.userDefaults.cachedPackageQueryMetadata[result.key] = result.value + } + + // There will be no 'merge' conflicts, so we ignore them by simply selecting the original before + // passing them off to the completion block. + if let completionBlock = completionBlock { + let stateSet = keyboardStates.merging(lexicalModelStates, uniquingKeysWith: { lhs, _ in return lhs }) + completionBlock(stateSet, nil) + } + } + } + + /** + * Runs the package-version query for the specified packages to determine if any updates are available. + */ + public static func queryCurrentVersions(for keys: [Key], withSession session: URLSession = URLSession.shared, completionBlock: (([Key : Version]?, Error?) -> Void)? = nil) { + queryDistributionStates(for: keys, withSession: session) { stateSet, error in + guard error == nil, let stateSet = stateSet else { + completionBlock?(nil, error) + return + } + + let versionSet: [Key: Version] = stateSet.compactMapValues { value in + if let versionString = value.latestVersion, let version = Version(versionString) { + return version + } else { + return nil + } + } + + completionBlock?(versionSet, nil) + } + } +} + +/** + * The actual base class for Keyman packages, which are only permitted to contain a single LanguageResource type at a time. + */ +public class TypedKeymanPackage: KeymanPackage { + public private(set) var installables: [[TypedLanguageResource]] = [] + typealias Resource = TypedLanguageResource + + internal func setInstallableResourceSets(for kmpResources: [Resource]) where + TypedLanguageResource: KMPInitializableLanguageResource { + self.installables = kmpResources.map { resource in + return resource.typedInstallableResources as! [TypedLanguageResource] + } as [[TypedLanguageResource]] + } + + // Cannot directly override base class's installableResourceSets with more specific type, + // despite covariance. So, we have to provide two separate properties. Joy. + // See https://forums.swift.org/t/confusing-limitations-on-covariant-overriding/16252 + public override var installableResourceSets: [[AnyLanguageResource]] { + return installables + } + + public func installables(forLanguage lgCode: String) -> [TypedLanguageResource] { + return super.installableResources(forLanguage: lgCode) as! [TypedLanguageResource] + } + + public func findResource(withID fullID: TypedLanguageResource.FullID) -> TypedLanguageResource? { + let matchesFound: [TypedLanguageResource] = self.installables.compactMap { set in + let setMatches: [TypedLanguageResource] = set.compactMap { other in + if fullID.id == other.id && fullID.languageID == other.languageID { + return other + } else { + return nil + } + } + + return setMatches.count > 0 ? setMatches[0] : nil + } + + return matchesFound.count > 0 ? matchesFound[0] : nil + } + + // Designed for use in cloud JS -> KMP migrations as needed for 13.0 -> 14.0 upgrades. + internal func findMetadataMatchFor(resource: TypedLanguageResource, ignoreLanguage: Bool, ignoreVersion: Bool) -> Metadata? + where TypedLanguageResource: KMPInitializableLanguageResource { + + var metadataList: [Metadata] + if self is KeyboardKeymanPackage { + metadataList = self.metadata.keyboards! as! [Metadata] + } else if self is LexicalModelKeymanPackage { + metadataList = self.metadata.lexicalModels! as! [Metadata] + } else { + return nil + } + + return metadataList.first(where: { kbdMetadata in + // For some reason, Swift just won't recognize that it's the same type in the line below. + kbdMetadata.hasMatchingMetadata(for: resource as! Metadata.LanguageResourceType, ignoreLanguage: ignoreLanguage, ignoreVersion: ignoreVersion) + }) + } + + public override var languages: [Language] { + let unfilteredLanguageList = self.resources.flatMap { $0.languages } + + var languages: [Language] = [] + var langCodeSet: Set = Set() + + unfilteredLanguageList.forEach { entry in + if !langCodeSet.contains(entry.languageId) { + langCodeSet.insert(entry.languageId) + languages.append(Language(from: entry)) + } + } + + languages.sort { $0.name < $1.name } + return languages + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/KeymanWebViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/KeymanWebViewController.swift index c7248680869831068c9abb39cb316594c958bef5..55326c6ab55863083e6b672f5c619057cebde4f4 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/KeymanWebViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/KeymanWebViewController.swift @@ -10,7 +10,7 @@ import UIKit import WebKit import AudioToolbox -private let keyboardChangeHelpText = "Tap here to change keyboard" +private let keyboardChangeHelpText = NSLocalizedString("keyboard-help-change", bundle: engineBundle, comment: "") private let subKeyColor = Colors.popupKey private let subKeyColorHighlighted = Colors.popupKeyHighlighted @@ -238,14 +238,14 @@ extension KeymanWebViewController { webView!.evaluateJavaScript("setDeviceType('\(type)');", completionHandler: nil) } - private func fontObject(from font: Font?, keyboardID: String, isOsk: Bool) -> [String: Any]? { + private func fontObject(from font: Font?, keyboard: InstallableKeyboard, isOsk: Bool) -> [String: Any]? { guard let font = font else { return nil } // family does not have to match the name in the font file. It only has to be unique. return [ - "family": "\(keyboardID)__\(isOsk ? "osk" : "display")", - "files": font.source.map { storage.fontURL(forKeyboardID: keyboardID, filename: $0).absoluteString } + "family": "\(keyboard.id)__\(isOsk ? "osk" : "display")", + "files": font.source.map { storage.fontURL(forResource: keyboard, filename: $0)!.absoluteString } ] } @@ -257,8 +257,13 @@ extension KeymanWebViewController { "KL": keyboard.languageName, "KF": storage.keyboardURL(for: keyboard).absoluteString ] - let displayFont = fontObject(from: keyboard.font, keyboardID: keyboard.id, isOsk: false) - let oskFont = fontObject(from: keyboard.oskFont, keyboardID: keyboard.id, isOsk: true) ?? displayFont + + if let packageID = keyboard.packageID { + stub["KP"] = packageID + } + + let displayFont = fontObject(from: keyboard.font, keyboard: keyboard, isOsk: false) + let oskFont = fontObject(from: keyboard.oskFont, keyboard: keyboard, isOsk: true) ?? displayFont if let displayFont = displayFont { stub["KFont"] = displayFont } @@ -565,7 +570,10 @@ extension KeymanWebViewController: KeymanWebDelegate { if let kb = Storage.active.userDefaults.userKeyboard(withFullID: id) { newKb = kb } - } else if let userKbs = Storage.active.userDefaults.userKeyboards, !userKbs.isEmpty { + } + + // Failsafe in case the previous lookup fails - at least load A keyboard. + if newKb == nil, let userKbs = Storage.active.userDefaults.userKeyboards, !userKbs.isEmpty { newKb = userKbs[0] } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/ResourceInfoView.xib b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/Base.lproj/ResourceInfoView.xib similarity index 100% rename from ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/ResourceInfoView.xib rename to ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/Base.lproj/ResourceInfoView.xib diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/KeyboardNameTableViewCell.swift b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/KeyboardNameTableViewCell.swift index f2a9babfeab0314db958d5de5bd3e7450a858161..0e5c56d3e68203d7d1517abf2ecfa8ca926a08e0 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/KeyboardNameTableViewCell.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/KeyboardNameTableViewCell.swift @@ -22,9 +22,9 @@ class KeyboardNameTableViewCell: UITableViewCell, UIAlertViewDelegate { fatalError("init(coder:) has not been implemented") } - func setKeyboardState(_ kbState: KeyboardState, selected isSelected: Bool, + func setInstallState(_ state: KeymanPackage.InstallationState, selected isSelected: Bool, defaultAccessoryType accessoryType: UITableViewCell.AccessoryType) { - if kbState != .downloading { + if state != .downloading { accessoryView = nil } self.accessoryType = accessoryType diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/KeyboardSwitcherViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/KeyboardSwitcherViewController.swift index 1f5526fe71775badc2f0de80a6ffd83f79fe2f23..5dd0d103cff2bedbba156886f7271f3d1ce6021f 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/KeyboardSwitcherViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/KeyboardSwitcherViewController.swift @@ -19,7 +19,7 @@ class KeyboardSwitcherViewController: UITableViewController, UIAlertViewDelegate override func viewDidLoad() { super.viewDidLoad() - title = "Keyboards" + title = NSLocalizedString("menu-picker-title", bundle: engineBundle, comment: "") self.accessoryType = .none diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageDetailViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageDetailViewController.swift index 2de117c835b6c9e274f0ad171eb16d78c2a08fd6..d26f94786778d1420f9a56f4b04583c3ef3f7edd 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageDetailViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageDetailViewController.swift @@ -5,252 +5,8 @@ // Created by Gabriel Wong on 2017-09-14. // Copyright © 2017 SIL International. All rights reserved. // +// Obsoleted by Joshua Horton on 2020-07-24. +// -import UIKit - -private let toolbarButtonTag = 100 -private let toolbarLabelTag = 101 -private let toolbarActivityIndicatorTag = 102 - -class LanguageDetailViewController: UITableViewController, UIAlertViewDelegate { - private let activityViewTag = -2 - - private var userKeyboards: [String: InstallableKeyboard] = [:] - private var isUpdate = false - private var language: Language - private var keyboardRepository: KeyboardRepository? - private var pendingFetch: Bool = false - - private var keyboardDownloadStartedObserver: NotificationObserver? - private var keyboardDownloadFailedObserver: NotificationObserver? - - convenience init(language: Language) { - self.init(nil, language: language) - } - - init(_ keyboardRepository: KeyboardRepository?, language: Language) { - self.language = language - super.init(nibName: nil, bundle: nil) - - self.keyboardRepository = keyboardRepository - keyboardRepository?.delegate = self - } - - required init?(coder aDecoder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override func loadView() { - super.loadView() - - if keyboardRepository != nil { - if let languageDict = keyboardRepository?.languages { - self.postLanguageLoad(languageDict: languageDict) - } else { - log.info("Fetching repository from API for keyboard download (LanguageDetailViewController)") - pendingFetch = true - keyboardRepository?.fetch() - } - } - - loadUserKeyboards() - } - - func postLanguageLoad(languageDict: [String: Language]) { - pendingFetch = false - - if let language = languageDict[self.language.id] { - self.language = language - - // Case 1 - called immediately during loadView() - UI is built after the load, so we're fine. - // Case 2 - called by keyboardRepositoryDidFetch() - UI updated by self.tableView.reloadData() - } - } - - override func viewDidLoad() { - super.viewDidLoad() - keyboardDownloadStartedObserver = NotificationCenter.default.addObserver( - forName: Notifications.keyboardDownloadStarted, - observer: self, - function: LanguageDetailViewController.keyboardDownloadStarted) - keyboardDownloadFailedObserver = NotificationCenter.default.addObserver( - forName: Notifications.keyboardDownloadFailed, - observer: self, - function: LanguageDetailViewController.keyboardDownloadFailed) - log.info("viewDidLoad: LanguageDetailViewController (registered for keyboardDownloadStarted)") - } - - override func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) - navigationController?.setToolbarHidden(true, animated: true) - // if no rows to show yet, show a loading indicator - if pendingFetch { - showActivityView() - log.info("didAppear: LanguageDetailViewController, but fetch is not yet complete") - } else { - log.info("didAppear: LanguageDetailViewController") - } - } - - // MARK: - Table view data source UITableViewDataSource - - override func numberOfSections(in tableView: UITableView) -> Int { - return language.keyboards!.count - } - - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return 1 - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cellIdentifier = "Cell" - if let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) { - return cell - } - - let cell = KeyboardNameTableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) - let selectionColor = UIView() - selectionColor.backgroundColor = Colors.selectionPrimary - cell.selectedBackgroundView = selectionColor - return cell - } - - override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { - let keyboard = language.keyboards![indexPath.section] - let cell = cell as! KeyboardNameTableViewCell - cell.indexPath = indexPath - cell.textLabel?.text = keyboard.name - if isAdded(languageID: language.id, keyboardID: keyboard.id) { - cell.accessoryType = .checkmark - cell.isUserInteractionEnabled = false - cell.textLabel?.isEnabled = false - cell.detailTextLabel?.isEnabled = false - } else { - cell.accessoryType = .none - cell.isUserInteractionEnabled = true - cell.textLabel?.isEnabled = true - cell.detailTextLabel?.isEnabled = true - } - - let kbState = ResourceDownloadManager.shared.stateForKeyboard(withID: keyboard.id) - cell.setKeyboardState(kbState, selected: false, defaultAccessoryType: cell.accessoryType) - } - - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - tableView.cellForRow(at: indexPath)?.isSelected = false - let keyboardIndex = indexPath.section - let keyboard = language.keyboards![keyboardIndex] - - let state = ResourceDownloadManager.shared.stateForKeyboard(withID: keyboard.id) - if state != .downloading { - if state == .needsDownload { - isUpdate = false - } else { - isUpdate = true - } - - let alertController = UIAlertController(title: "\(language.name): \(keyboard.name)", - message: "Would you like to download this keyboard?", - preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "Cancel", - style: UIAlertAction.Style.cancel, - handler: nil)) - alertController.addAction(UIAlertAction(title: "Download", - style: UIAlertAction.Style.default, - handler: {_ in self.downloadHandler(keyboardIndex)} )) - - self.present(alertController, animated: true, completion: nil) - } - } - - func downloadHandler(_ keyboardIndex: Int) { - ResourceDownloadManager.shared.downloadKeyboard(withID: language.keyboards![keyboardIndex].id, - languageID: language.id, isUpdate: isUpdate) - } - - func showActivityView() { - view.isUserInteractionEnabled = false - let indicatorView = UIActivityIndicatorView(style: .whiteLarge) - let activityView = UIView(frame: indicatorView.bounds.insetBy(dx: -10.0, dy: -10.0)) - activityView.backgroundColor = Colors.spinnerBackground - activityView.layer.cornerRadius = 6.0 - activityView.center = view.center - activityView.tag = activityViewTag - activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, - .flexibleBottomMargin] - - indicatorView.center = CGPoint(x: activityView.bounds.size.width * 0.5, y: activityView.bounds.size.height * 0.5) - indicatorView.startAnimating() - activityView.addSubview(indicatorView) - view.addSubview(activityView) - } - - func dismissActivityView() { - let activityView = view.viewWithTag(activityViewTag) - activityView?.removeFromSuperview() - view.isUserInteractionEnabled = true - } - - private func showConnectionErrorAlert() { - Alerts.showConnectionErrorAlert(in: self, handler: Alerts.popToNavigationRootHandler(for: self)) - } - - private func keyboardDownloadStarted() { - log.info("keyboardDownloadStarted: LanguageDetailViewController") - view.isUserInteractionEnabled = false - navigationItem.setHidesBackButton(true, animated: true) - } - - private func keyboardDownloadFailed() { - log.info("keyboardDownloadFailed: LanguageDetailViewController") - Alerts.showDownloadErrorAlert(in: self, handler: Alerts.popToNavigationRootHandler(for: self)) - - view.isUserInteractionEnabled = true - navigationItem.setHidesBackButton(false, animated: true) - } - - private func loadUserKeyboards() { - guard let userKbList = Storage.active.userDefaults.userKeyboards, !userKbList.isEmpty else { - userKeyboards = [:] - return - } - - userKeyboards = [:] - for kb in userKbList { - let dictKey = "\(kb.languageID)_\(kb.id)" - userKeyboards[dictKey] = kb - } - } - - private func isAdded(languageID: String?, keyboardID: String?) -> Bool { - guard let languageID = languageID, let keyboardID = keyboardID else { - return false - } - return userKeyboards["\(languageID)_\(keyboardID)"] != nil - } -} - -// MARK: - KeyboardRepositoryDelegate -extension LanguageDetailViewController: KeyboardRepositoryDelegate { - func keyboardRepositoryDidFetch(_ repository: KeyboardRepository) { - if let languageDict = repository.languages { - self.postLanguageLoad(languageDict: languageDict) - } - self.dismissActivityView() - self.tableView.reloadData() - if self.numberOfSections(in: self.tableView) == 0 { - self.showConnectionErrorAlert() - } - } - - func keyboardRepository(_ repository: KeyboardRepository, didFailFetch error: Error) { - dismissActivityView() - showConnectionErrorAlert() - } - - private func languageList(_ languageDict: [String: Language]) -> [Language] { - return languageDict.values.sorted { a, b -> Bool in - a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending - } - } -} +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "The old list-based keyboard search is no longer supported. Please use `KeyboardSearchViewController` instead.") +class LanguageDetailViewController { } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageLMDetailViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageLMDetailViewController.swift index b2594e02752b1e467652f553e4abac535a60ea0f..6c03696a45afc46d2fee7e0a51ed2bed4ba9f674 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageLMDetailViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageLMDetailViewController.swift @@ -17,15 +17,19 @@ class LanguageLMDetailViewController: UITableViewController, UIAlertViewDelegate private var userLexicalModels: [String: InstallableLexicalModel] = [:] private var isUpdate = false // unused currently, may be used when we switch to HTTPDownloader private let language: Language - public var lexicalModels: [LexicalModel]? = nil + public var packages: [(InstallableLexicalModel, URL)] private var lexicalModelDownloadStartedObserver: NotificationObserver? //NOTE: there is no need for a CompletedObserver, as our parent LexicalModelPickerViewController // is registered for that and deals with it by popping us out to root. private var lexicalModelDownloadFailedObserver: NotificationObserver? + + private var onSuccessClosure: ((InstallableLexicalModel) -> Void)? - init(language: Language) { + init(language: Language, packages: [(InstallableLexicalModel, URL)], onSuccess: ((InstallableLexicalModel) -> Void)?) { self.language = language + self.packages = packages + self.onSuccessClosure = onSuccess super.init(nibName: nil, bundle: nil) } @@ -42,11 +46,11 @@ class LanguageLMDetailViewController: UITableViewController, UIAlertViewDelegate override func viewDidLoad() { super.viewDidLoad() lexicalModelDownloadStartedObserver = NotificationCenter.default.addObserver( - forName: Notifications.lexicalModelDownloadStarted, + forName: Notifications.packageDownloadStarted, observer: self, function: LanguageLMDetailViewController.lexicalModelDownloadStarted) lexicalModelDownloadFailedObserver = NotificationCenter.default.addObserver( - forName: Notifications.lexicalModelDownloadFailed, + forName: Notifications.packageDownloadFailed, observer: self, function: LanguageLMDetailViewController.lexicalModelDownloadFailed) log.info("viewDidLoad: LanguageLMDetailViewController (registered for lexicalModelDownloadStarted)") @@ -68,7 +72,7 @@ class LanguageLMDetailViewController: UITableViewController, UIAlertViewDelegate // MARK: - Table view data source UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { - return lexicalModels!.count + return packages.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -89,7 +93,7 @@ class LanguageLMDetailViewController: UITableViewController, UIAlertViewDelegate } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { - let lexicalModel = lexicalModels![indexPath.section] + let lexicalModel = packages[indexPath.section].0 let cell = cell as! KeyboardNameTableViewCell cell.indexPath = indexPath cell.textLabel?.text = lexicalModel.name @@ -104,31 +108,32 @@ class LanguageLMDetailViewController: UITableViewController, UIAlertViewDelegate cell.textLabel?.isEnabled = true cell.detailTextLabel?.isEnabled = true } - - let kbState = ResourceDownloadManager.shared.stateForLexicalModel(withID: lexicalModel.id) - cell.setKeyboardState(kbState, selected: false, defaultAccessoryType: cell.accessoryType) + + let state = ResourceFileManager.shared.installState(forPackage: KeymanPackage.Key(id: lexicalModel.id, type: .lexicalModel)) + cell.setInstallState(state, selected: false, defaultAccessoryType: cell.accessoryType) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.cellForRow(at: indexPath)?.isSelected = false let lexicalModelIndex = indexPath.section - let lexicalModel = lexicalModels![lexicalModelIndex] - - let state = ResourceDownloadManager.shared.stateForLexicalModel(withID: lexicalModel.id) + let lexicalModel = packages[lexicalModelIndex].0 + + let state = ResourceFileManager.shared.installState(forPackage: KeymanPackage.Key(id: lexicalModel.id, type: .lexicalModel)) if state != .downloading { - if state == .needsDownload { + if state == .none { isUpdate = false } else { isUpdate = true } - - let alertController = UIAlertController(title: "\(language.name): \(lexicalModel.name)", - message: "Would you like to download this dictionary?", + + let format = NSLocalizedString("menu-lexical-model-install-title", bundle: engineBundle, comment: "") + let alertController = UIAlertController(title: String.localizedStringWithFormat(format, language.name, lexicalModel.name), + message: NSLocalizedString("menu-lexical-model-install-message", bundle: engineBundle, comment: ""), preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "Cancel", + alertController.addAction(UIAlertAction(title: NSLocalizedString("command-cancel", bundle: engineBundle, comment: ""), style: UIAlertAction.Style.cancel, handler: nil)) - alertController.addAction(UIAlertAction(title: "Download", + alertController.addAction(UIAlertAction(title: NSLocalizedString("command-install", bundle: engineBundle, comment: ""), style: UIAlertAction.Style.default, handler: {_ in self.downloadHandler(lexicalModelIndex)} )) @@ -137,8 +142,17 @@ class LanguageLMDetailViewController: UITableViewController, UIAlertViewDelegate } func downloadHandler(_ lexicalModelIndex: Int) { - let lexicalModel = lexicalModels![lexicalModelIndex] - ResourceDownloadManager.shared.downloadLexicalModel(withID: lexicalModel.id, languageID: language.id, isUpdate: false) + let package = packages[lexicalModelIndex] + let lmFullID = package.0.fullID + let completionClosure: ResourceDownloadManager.CompletionHandler = { package, error in + try? ResourceDownloadManager.shared.standardLexicalModelInstallCompletionBlock(forFullID: lmFullID)(package, error) + + if let lm = package?.findResource(withID: lmFullID) { + self.onSuccessClosure?(lm) + } + } + + ResourceDownloadManager.shared.downloadPackage(withKey: package.0.packageKey, from: package.1, withNotifications: true, completionBlock: completionClosure) } private func lexicalModelDownloadStarted() { diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageViewController.swift index 383ce0817e701cf1e7e6ffd4b23ab5e6b2a93b5f..4125cf077f75eb747d8186493904cd05a29d9c01 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LanguageViewController.swift @@ -5,352 +5,8 @@ // Created by Gabriel Wong on 2017-09-15. // Copyright © 2017 SIL International. All rights reserved. // -import QuartzCore -import UIKit - -private let activityViewTag = -2 -private let toolbarButtonTag = 100 -private let toolbarLabelTag = 101 -private let toolbarActivityIndicatorTag = 102 - -class LanguageViewController: UITableViewController, UIAlertViewDelegate { - private var userKeyboards: [String: InstallableKeyboard] = [:] - private var userLexicalModels: [String: InstallableLexicalModel] = [:] - private var sectionIndexTitles: [String] = [] - private var indices: [Int] = [] - private var selectedSection = 0 - private var isUpdate = false - private var languages: [Language] = [] - private let keyboardRepository: KeyboardRepository? - private let lexicalModelRepository: LexicalModelRepository? - - private var keyboardDownloadStartedObserver: NotificationObserver? - private var keyboardDownloadFailedObserver: NotificationObserver? - - init(_ keyboardRepository: KeyboardRepository) { - self.keyboardRepository = keyboardRepository - self.lexicalModelRepository = nil - super.init(nibName: nil, bundle: nil) - keyboardRepository.delegate = self - } - - init(_ lexicalModelRepository: LexicalModelRepository) { - self.lexicalModelRepository = lexicalModelRepository - self.keyboardRepository = nil - super.init(nibName: nil, bundle: nil) - lexicalModelRepository.delegate = self - } - - init(keyboardRep keyboardRepository: KeyboardRepository, modelRep lexicalModelRepository: LexicalModelRepository) { - self.keyboardRepository = keyboardRepository - self.lexicalModelRepository = lexicalModelRepository - super.init(nibName: nil, bundle: nil) - keyboardRepository.delegate = self - lexicalModelRepository.delegate = self - } - - required init?(coder aDecoder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - func postLanguageLoad(languageDict: [String: Language]) { - languages = languageList(languageDict) - } - - func idxOfLanguage(languageID: String) -> Int { - let langIdx = self.languages.firstIndex(where: { - $0.id == languageID - }) ?? 0 - return langIdx - } - - override func loadView() { - super.loadView() - if let languageDict = keyboardRepository?.languages { - self.postLanguageLoad(languageDict: languageDict) - } else { - log.info("Fetching repository from API for keyboard download (LanguageViewController)") - keyboardRepository?.fetch() - } - - loadUserKeyboards() - loadUserLexicalModels() - } - - override func viewDidLoad() { - super.viewDidLoad() - title = "Add New Keyboard" - selectedSection = NSNotFound - keyboardDownloadStartedObserver = NotificationCenter.default.addObserver( - forName: Notifications.keyboardDownloadStarted, - observer: self, - function: LanguageViewController.keyboardDownloadStarted) - keyboardDownloadFailedObserver = NotificationCenter.default.addObserver( - forName: Notifications.keyboardDownloadFailed, - observer: self, - function: LanguageViewController.keyboardDownloadFailed) - } - - override func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) - navigationController?.setToolbarHidden(true, animated: true) - // if no rows to show yet, show a loading indicator - if numberOfSections(in: tableView) == 0 { - showActivityView() - log.info("didAppear: LanguageViewController, but no rows to show") - } else { - log.info("didAppear: LanguageViewController") - } - } - - // MARK: - Table view data source UITableViewDataSource - - override func numberOfSections(in tableView: UITableView) -> Int { - return languages.count - } - - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return 1 - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cellIdentifierType1 = "CellType1" - let cellIdentifierType2 = "CellType2" - let keyboards = languages[indexPath.section].keyboards! - let cellIdentifier = (keyboards.count < 2) ? cellIdentifierType1 : cellIdentifierType2 - let cell: UITableViewCell - if let reusedCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) { - cell = reusedCell - } else { - if keyboards.count < 2 { - cell = KeyboardNameTableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) - let selectionColor = UIView() - selectionColor.backgroundColor = Colors.selectionPrimary - cell.selectedBackgroundView = selectionColor - } else { - cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier) - cell.accessoryType = .disclosureIndicator - let selectionColor = UIView() - selectionColor.backgroundColor = Colors.selectionPrimary - cell.selectedBackgroundView = selectionColor - } - } - cell.detailTextLabel?.text = keyboards.count < 2 ? (keyboards.first?.name ?? "") : "" - return cell - } - - // Create sections by first letter - override func sectionIndexTitles(for tableView: UITableView) -> [String] { - if !sectionIndexTitles.isEmpty { - return sectionIndexTitles - } - - sectionIndexTitles = [] - indices = [] - for (index, language) in languages.enumerated() { - let firstLetter = String(language.name.prefix(1)).uppercased() - if !sectionIndexTitles.contains(firstLetter) { - sectionIndexTitles.append(firstLetter) - indices.append(index) - } - } - return sectionIndexTitles - } - - override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { - return indices[index] - } - - override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { - guard let language = languages[safe: indexPath.section] else { - return - } - - cell.textLabel?.text = language.name - - if cell.accessoryType == .disclosureIndicator { - return - } - guard let cell = cell as? KeyboardNameTableViewCell else { - return - } - - let languageID = language.id - let keyboardID = language.keyboards![0].id - - if isAdded(languageID: languageID, keyboardID: keyboardID) { - cell.accessoryType = .checkmark - cell.isUserInteractionEnabled = false - cell.textLabel?.isEnabled = false - cell.detailTextLabel?.isEnabled = false - } else { - cell.accessoryType = .none - cell.isUserInteractionEnabled = true - cell.textLabel?.isEnabled = true - cell.detailTextLabel?.isEnabled = true - } - let kbState = ResourceDownloadManager.shared.stateForKeyboard(withID: keyboardID) - cell.setKeyboardState(kbState, selected: false, defaultAccessoryType: cell.accessoryType) - } - - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - selectedSection = indexPath.section - tableView.cellForRow(at: indexPath)?.isSelected = false - if tableView.cellForRow(at: indexPath)?.accessoryType == .disclosureIndicator { - let title = tableView.cellForRow(at: indexPath)?.textLabel?.text ?? "" - showLanguageDetailView(title: title, languageIndex: indexPath.section) - return - } - - let language = languages[indexPath.section] - let keyboardIndex = 0; - let keyboard = language.keyboards![keyboardIndex] - - let state = ResourceDownloadManager.shared.stateForKeyboard(withID: keyboard.id) - if state != .downloading { - isUpdate = state != .needsDownload - let alertController = UIAlertController(title: "\(language.name): \(keyboard.name)", - message: "Would you like to download this keyboard?", - preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "Cancel", - style: UIAlertAction.Style.cancel, - handler: nil)) - alertController.addAction(UIAlertAction(title: "Download", - style: UIAlertAction.Style.default, - handler: {_ in self.downloadHandler(keyboardIndex)} )) - self.present(alertController, animated: true, completion: nil) - } - } - - override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { - let title = tableView.cellForRow(at: indexPath)?.textLabel?.text ?? "" - showLanguageDetailView(title: title, languageIndex: indexPath.section) - } - - func showLanguageDetailView(title: String, languageIndex: Int) { - let langDetailView = LanguageDetailViewController(language: languages[languageIndex]) - langDetailView.title = title - navigationController?.pushViewController(langDetailView, animated: true) - } - - func downloadHandler(_ keyboardIndex: Int) { - let language = languages[selectedSection] - let keyboard = language.keyboards![keyboardIndex] - ResourceDownloadManager.shared.downloadKeyboard(withID: keyboard.id, languageID: language.id, isUpdate: isUpdate) - } - - private func keyboardDownloadStarted() { - view.isUserInteractionEnabled = false - navigationItem.setHidesBackButton(true, animated: true) - } - - private func keyboardDownloadFailed() { - Alerts.showDownloadErrorAlert(in: self, handler: Alerts.popToNavigationRootHandler(for: self)) - - view.isUserInteractionEnabled = true - navigationItem.setHidesBackButton(false, animated: true) - } - - func showActivityView() { - view.isUserInteractionEnabled = false - let indicatorView = UIActivityIndicatorView(style: .whiteLarge) - let activityView = UIView(frame: indicatorView.bounds.insetBy(dx: -10.0, dy: -10.0)) - activityView.backgroundColor = Colors.spinnerBackground - activityView.layer.cornerRadius = 6.0 - activityView.center = view.center - activityView.tag = activityViewTag - activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, - .flexibleBottomMargin] - - indicatorView.center = CGPoint(x: activityView.bounds.size.width * 0.5, y: activityView.bounds.size.height * 0.5) - indicatorView.startAnimating() - activityView.addSubview(indicatorView) - view.addSubview(activityView) - } - - func dismissActivityView() { - let activityView = view.viewWithTag(activityViewTag) - activityView?.removeFromSuperview() - view.isUserInteractionEnabled = true - } - - func loadUserKeyboards() { - userKeyboards = [:] - guard let userKbList = Storage.active.userDefaults.userKeyboards else { - return - } - - for kb in userKbList { - let dictKey = "\(kb.languageID)_\(kb.id)" - userKeyboards[dictKey] = kb - } - } - - func loadUserLexicalModels() { - userLexicalModels = [:] - guard let userLmList = Storage.active.userDefaults.userLexicalModels else { - return - } - - for lm in userLmList { - let dictKey = "\(lm.languageID)_\(lm.id)" - userLexicalModels[dictKey] = lm - } - } - - private func isAdded(languageID: String?, keyboardID: String?) -> Bool { - guard let languageID = languageID, let keyboardID = keyboardID else { - return false - } - return userKeyboards["\(languageID)_\(keyboardID)"] != nil - } - - private func showConnectionErrorAlert() { - Alerts.showConnectionErrorAlert(in: self, handler: Alerts.popToNavigationRootHandler(for: self)) - } -} - -// MARK: - KeyboardRepositoryDelegate -extension LanguageViewController: KeyboardRepositoryDelegate { - func keyboardRepositoryDidFetch(_ repository: KeyboardRepository) { - if let languageDict = repository.languages { - self.postLanguageLoad(languageDict: languageDict) - } - self.dismissActivityView() - self.tableView.reloadData() - if self.numberOfSections(in: self.tableView) == 0 { - self.showConnectionErrorAlert() - } - } - - func keyboardRepository(_ repository: KeyboardRepository, didFailFetch error: Error) { - dismissActivityView() - showConnectionErrorAlert() - } - - private func languageList(_ languageDict: [String: Language]) -> [Language] { - return languageDict.values.sorted { a, b -> Bool in - a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending - } - } -} - -// MARK: - LexicalModelRepositoryDelegate +// Obsoleted by Joshua Horton on 2020-07-24. +// -extension LanguageViewController: LexicalModelRepositoryDelegate { - func lexicalModelRepositoryDidFetchList(_ repository: LexicalModelRepository) { - if let languageDict = repository.languages { - self.postLanguageLoad(languageDict: languageDict) - } - self.dismissActivityView() - self.tableView.reloadData() - if self.numberOfSections(in: self.tableView) == 0 { - self.showConnectionErrorAlert() - } - } - - func lexicalModelRepository(_ repository: LexicalModelRepository, didFailFetch error: Error) { - dismissActivityView() - showConnectionErrorAlert() - } -} +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "The old list-based keyboard search is no longer supported. Please use `KeyboardSearchViewController` instead.") +class LanguageViewController { } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LexicalModelInfoViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LexicalModelInfoViewController.swift deleted file mode 100644 index 0bc6312c0ef453dff8c437917742cf71b8d88d0e..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LexicalModelInfoViewController.swift +++ /dev/null @@ -1,132 +0,0 @@ -// -// LexicalModelInfoViewController.swift -// KeymanEngine -// -// Created by Randy Boring on 3/19/19. -// Copyright © 2019 SIL International. All rights reserved. -// -import UIKit -import Foundation - -class LexicalModelInfoViewController: UITableViewController, UIAlertViewDelegate { - var lexicalModelCount: Int = 0 - var lexicalModelIndex: Int = 0 - var lexicalModelID: String = "" - var languageID: String = "" - var lexicalModelVersion: String = "" - var lexicalModelCopyright: String = "" - var isCustomLexicalModel: Bool = false - - private var infoArray = [[String: String]]() - - override func viewDidLoad() { - super.viewDidLoad() - - infoArray = [[String: String]]() - infoArray.append([ - "title": "Dictionary version", - "subtitle": lexicalModelVersion - ]) - - if !isCustomLexicalModel { - infoArray.append([ - "title": "Help link", - "subtitle": "" - ]) - } - infoArray.append([ - "title": "Uninstall dictionary", - "subtitle": "" - ]) - } - - override func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) - navigationController?.setToolbarHidden(true, animated: true) - log.info("didAppear: LexicalModelInfoViewController") - } - - override func numberOfSections(in tableView: UITableView) -> Int { - return 1 - } - - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - if isCustomLexicalModel { - return 2 - } else { - return 3 - } - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cellIdentifier = "Cell" - if let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) { - return cell - } - return UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) - } - - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - if !isCustomLexicalModel { - if indexPath.row == 1 { - let url = URL(string: "http://help.keyman.com/lexicalModel/\(lexicalModelID)/\(lexicalModelVersion)/")! - if let openURL = Manager.shared.openURL { - _ = openURL(url) - } else { - log.error("openURL not set in Manager. Failed to open \(url)") - } - } else if indexPath.row == 2 { - showDeleteLexicalModel() - } - } else if indexPath.row == 1 { - showDeleteLexicalModel() - } - } - - private func fetchedLexicalModelData(_ data: Data) { - guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [AnyHashable: Any] else { - return - } - let lexicalModels = json[Key.language] as? [Any] - let kbDict = lexicalModels?[0] as? [AnyHashable: Any] - var info = infoArray[1] - let copyright = kbDict?[Key.lexicalModelCopyright] as? String ?? "Unknown" - - info["subtitle"] = copyright - infoArray[1] = info - tableView.reloadData() - } - - override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { - cell.selectionStyle = .none - cell.accessoryType = .none - cell.textLabel?.text = infoArray[indexPath.row]["title"] - cell.detailTextLabel?.text = infoArray[indexPath.row]["subtitle"] - cell.tag = indexPath.row - - if !isCustomLexicalModel { - if indexPath.row == 1 { - cell.accessoryType = .disclosureIndicator - } - } - } - - private func showDeleteLexicalModel() { - let alertController = UIAlertController(title: title ?? "", message: "Would you like to delete this dictionary?", - preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "Cancel", - style: UIAlertAction.Style.cancel, - handler: nil)) - alertController.addAction(UIAlertAction(title: "Delete", - style: UIAlertAction.Style.default, - handler: deleteHandler)) - - self.present(alertController, animated: true, completion: nil) - } - - func deleteHandler(withAction action: UIAlertAction) { - if Manager.shared.removeLexicalModel(at: lexicalModelIndex) { - navigationController?.popToRootViewController(animated: true) - } - } -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LexicalModelPickerViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LexicalModelPickerViewController.swift index cc91406699803ed99331487dfd36b4cf239c48aa..af92ff267912175b85c26077dae0eb9af5f137a9 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LexicalModelPickerViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/LexicalModelPickerViewController.swift @@ -33,8 +33,9 @@ class LexicalModelPickerViewController: UITableViewController, UIAlertViewDelega override func viewDidLoad() { super.viewDidLoad() - - title = "\(language.name) Dictionaries" + + let format = NSLocalizedString("menu-lexical-model-title", bundle: engineBundle, comment: "") + title = String.localizedStringWithFormat(format, language.name) if Manager.shared.canAddNewLexicalModels { let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.addClicked)) @@ -44,15 +45,15 @@ class LexicalModelPickerViewController: UITableViewController, UIAlertViewDelega navigationController?.toolbar?.barTintColor = Colors.statusToolbar lexicalModelDownloadStartedObserver = NotificationCenter.default.addObserver( - forName: Notifications.lexicalModelDownloadStarted, + forName: Notifications.packageDownloadStarted, observer: self, function: LexicalModelPickerViewController.lexicalModelDownloadStarted) lexicalModelDownloadCompletedObserver = NotificationCenter.default.addObserver( - forName: Notifications.lexicalModelDownloadCompleted, + forName: Notifications.packageDownloadCompleted, observer: self, function: LexicalModelPickerViewController.lexicalModelDownloadCompleted) lexicalModelDownloadFailedObserver = NotificationCenter.default.addObserver( - forName: Notifications.lexicalModelDownloadFailed, + forName: Notifications.packageDownloadFailed, observer: self, function: LexicalModelPickerViewController.lexicalModelDownloadFailed) @@ -95,8 +96,7 @@ class LexicalModelPickerViewController: UITableViewController, UIAlertViewDelega cell.selectedBackgroundView = selectionColor return cell } - - // TODO: Refactor. Duplicated in LexicalModelInfoViewController + override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if !Manager.shared.canRemoveLexicalModels { return false @@ -124,16 +124,8 @@ class LexicalModelPickerViewController: UITableViewController, UIAlertViewDelega func showLexicalModelInfoView(with index: Int) { let lm = userLexicalModels[index] - let version = lm.version - - let infoView = LexicalModelInfoViewController() - infoView.title = lm.name - infoView.lexicalModelCount = userLexicalModels.count - infoView.lexicalModelIndex = local2globalIndex(index) - infoView.lexicalModelID = lm.id - infoView.languageID = lm.languageID - infoView.lexicalModelVersion = version - infoView.isCustomLexicalModel = lm.isCustom + + let infoView = ResourceInfoViewController(for: lm, mayDelete: Manager.shared.canRemoveLexicalModels) navigationController?.pushViewController(infoView, animated: true) } @@ -177,13 +169,13 @@ class LexicalModelPickerViewController: UITableViewController, UIAlertViewDelega return globalIndex } - private func lexicalModelDownloadStarted(_ lexicalModels: [InstallableLexicalModel]) { + private func lexicalModelDownloadStarted() { view.isUserInteractionEnabled = false navigationItem.leftBarButtonItem?.isEnabled = false navigationItem.rightBarButtonItem?.isEnabled = false } - private func lexicalModelDownloadCompleted(_ lexicalModels: [InstallableLexicalModel]) { + private func lexicalModelDownloadCompleted() { log.info("lexicalModelDownloadCompleted LexicalModelPicker") // Actually used now. @@ -193,30 +185,22 @@ class LexicalModelPickerViewController: UITableViewController, UIAlertViewDelega navigationItem.rightBarButtonItem?.isEnabled = true } - // Add lexicalModel. - for lexicalModel in lexicalModels { - if lexicalModel.languageID == language?.id { - Manager.addLexicalModel(lexicalModel) - switchLexicalModel(lexicalModel) - } - } - navigationController?.popToRootViewController(animated: true) } - private func lexicalModelDownloadFailed(_ notification: LexicalModelDownloadFailedNotification) { + private func lexicalModelDownloadFailed(_ notification: PackageDownloadFailedNotification) { view.isUserInteractionEnabled = true navigationItem.leftBarButtonItem?.isEnabled = true if let item = navigationItem.rightBarButtonItem { item.isEnabled = true } - let title: String = "Dictionary Download Error" + let title: String = NSLocalizedString("notification-download-failure-lexical-model", bundle: engineBundle, comment: "") navigationController?.setToolbarHidden(true, animated: true) let alertController = UIAlertController(title: title, message: notification.error.localizedDescription, preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "OK", + alertController.addAction(UIAlertAction(title: NSLocalizedString("command-ok", bundle: engineBundle, comment: ""), style: UIAlertAction.Style.cancel, handler: { _ in self.navigationController?.popToRootViewController(animated: true) @@ -284,7 +268,7 @@ class LexicalModelPickerViewController: UITableViewController, UIAlertViewDelega private func setIsDoneButtonEnabled(_ value: Bool) { _isDoneButtonEnabled = value if _isDoneButtonEnabled { - let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, + let doneButton = UIBarButtonItem(title: NSLocalizedString("command-done", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(self.doneClicked)) navigationItem.leftBarButtonItem = doneButton } else { @@ -300,40 +284,46 @@ class LexicalModelPickerViewController: UITableViewController, UIAlertViewDelega func showAddLexicalModel() { //get list of lexical models for this languageID and show it - func listCompletionHandler(lexicalModels: [LexicalModel]?, error: Error?) -> Void { + Queries.LexicalModel.fetch(forLanguageCode: language.id) { result, error in if let error = error { - log.info("Failed to fetch lexical model list for "+language.id+". error: "+(error.localizedDescription)) + log.info("Failed to fetch lexical model list for "+self.language.id+". error: "+error.localizedDescription) DispatchQueue.main.async { - self.lexicalModelDownloadFailed(LexicalModelDownloadFailedNotification(lmOrLanguageID: self.language.id, error: error)) + self.lexicalModelDownloadFailed(PackageDownloadFailedNotification(packageKey: nil, error: error)) } - } else if nil == lexicalModels { - noModelsAvailable(cause: "nil") - } else if 0 == lexicalModels?.count { - noModelsAvailable(cause: "empty") + return + } + + guard let result = result else { + self.noModelsAvailable(cause: "nil") + return + } + + if result.count == 0 { + self.noModelsAvailable(cause: "empty") } else { - log.info("Fetched lexical model list for "+language.id+".") + log.info("Fetched lexical model list for "+self.language.id+".") + let packages: [(InstallableLexicalModel, URL)] = result.map { ($0.modelFor(languageID: self.language.id)!, URL.init(string: $0.packageFilename)!) } // show the list of lexical models (on the main thread) DispatchQueue.main.async { let button: UIButton? = (self.navigationController?.toolbar?.viewWithTag(toolbarButtonTag) as? UIButton) button?.isEnabled = false - let vc = LanguageLMDetailViewController(language: self.language) - vc.lexicalModels = lexicalModels! + let vc = LanguageLMDetailViewController(language: self.language, packages: packages, onSuccess: { lm in + self.switchLexicalModel(lm) + }) self.navigationController?.pushViewController(vc, animated: true) } } } - - Manager.shared.apiLexicalModelRepository.fetchList(languageID: language.id, completionHandler: listCompletionHandler) } func noModelsAvailable(cause: String = "nil") { - let msg = "No dictionaries available" - let logMsg = "No lexical models available for language \(language.id) (\(cause))" + let msg = NSLocalizedString("menu-lexical-model-none-message", bundle: engineBundle, comment: "") + let logMsg = "No lexical models available for language \(language.id): (\(cause))" log.info(logMsg) let alertController = UIAlertController(title: title, message: msg, preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "OK", + alertController.addAction(UIAlertAction(title: NSLocalizedString("command-ok", bundle: engineBundle, comment: ""), style: UIAlertAction.Style.default, handler: { _ in self.navigationController?.popViewController(animated: true) diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/ResourceInfoViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/ResourceInfoViewController.swift index ba6a0134cb08f1671e018fd925370a89cf57fedd..8f32bda7d3caaaf5fb00022210dd47e0625282a0 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/ResourceInfoViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/ResourceInfoViewController.swift @@ -9,22 +9,15 @@ import Foundation import UIKit -/** - * At present, this class only supports keyboard resources. The base design is partially refactored to - * eventually support lexical model resources as well, but additional work is needed before this class - * will be ready... possibly as a common base class. - */ -class ResourceInfoViewController: UIViewController, UIAlertViewDelegate, UITableViewDelegate, UITableViewDataSource { - // Collectively used to determine if a keyboard may be deleted. - var keyboardCount: Int = 0 - var keyboardIndex: Int = 0 - var isCustomKeyboard: Bool = false // also used to toggle QR code gen + display - - var keyboardCopyright: String = "" +class ResourceInfoViewController: UIViewController, UIAlertViewDelegate, UITableViewDelegate, UITableViewDataSource { + var isCustomKeyboard: Bool = false // legacy; was also used to toggle QR code gen + display + // The data backing our UI text in the UITableView. private var infoArray = [[String: String]]() - let resource: LanguageResource + let resource: Resource + let package: Resource.Package? + let mayDelete: Bool @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var contentView: UIView! @@ -35,8 +28,10 @@ class ResourceInfoViewController: UIViewController, UIAlertViewDelegate, UITable @IBOutlet weak var tableHeightConstraint: NSLayoutConstraint! @IBOutlet weak var labelHeightConstraint: NSLayoutConstraint! - init(for resource: LanguageResource) { + init(for resource: Resource, mayDelete: Bool = false) { self.resource = resource + self.package = ResourceFileManager.shared.getInstalledPackage(for: resource) + self.mayDelete = mayDelete super.init(nibName: "ResourceInfoView", bundle: Bundle.init(for: ResourceInfoViewController.self)) } @@ -48,20 +43,31 @@ class ResourceInfoViewController: UIViewController, UIAlertViewDelegate, UITable override func viewDidLoad() { super.viewDidLoad() + var versionLabelKey: String + var uninstallLabelKey: String + + if Resource.self == InstallableLexicalModel.self { + versionLabelKey = "info-label-version-lexical-model" + uninstallLabelKey = "command-uninstall-lexical-model" + } else { + versionLabelKey = "info-label-version-keyboard" + uninstallLabelKey = "command-uninstall-keyboard" + } + infoArray = [[String: String]]() infoArray.append([ - "title": "Keyboard version", + "title": NSLocalizedString(versionLabelKey, bundle: engineBundle, comment: ""), "subtitle": resource.version ]) if !isCustomKeyboard { infoArray.append([ - "title": "Help link", + "title": NSLocalizedString("info-command-help", bundle: engineBundle, comment: ""), "subtitle": "" ]) } infoArray.append([ - "title": "Uninstall keyboard", + "title": NSLocalizedString(uninstallLabelKey, bundle: engineBundle, comment: ""), "subtitle": "" ]) @@ -71,16 +77,22 @@ class ResourceInfoViewController: UIViewController, UIAlertViewDelegate, UITable tableView.reloadData() // Generate & display the QR code! - if let resourceURL = resource.sharableURL { - if let qrImg = generateQRCode(from: resourceURL) { - qrImageView.image = qrImg + if package?.distributionMethod ?? .unknown == .cloud { + if let resourceURL = resource.sharableURL { + if let qrImg = generateQRCode(from: resourceURL) { + qrImageView.image = qrImg + } else { + log.info("Unable to generate QR code for URL: \(resourceURL)") + } } else { - log.info("Unable to generate QR code for URL: \(resourceURL)") + // No resource-sharing link available. Hide the text label! + shareLabel.isHidden = true } } else { - // No resource-sharing link available. Hide the text label! shareLabel.isHidden = true } + + self.title = resource.name } // Should be supported in iOS 7+. We only support 9+, so we should be fine here. @@ -129,32 +141,19 @@ class ResourceInfoViewController: UIViewController, UIAlertViewDelegate, UITable func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if !isCustomKeyboard { if indexPath.row == 1 { - let url = URL(string: "http://help.keyman.com/keyboard/\(resource.id)/\(resource.version)/")! + let typeString = resource.fullID.type == .keyboard ? "keyboard" : "lexicalModel" + let url = URL(string: "\(KeymanHosts.HELP_KEYMAN_COM)/\(typeString)/\(resource.id)/\(resource.version)/")! if let openURL = Manager.shared.openURL { _ = openURL(url) } else { log.error("openURL not set in Manager. Failed to open \(url)") } } else if indexPath.row == 2 { - showDeleteKeyboard() + showDeleteResource() } } else if indexPath.row == 1 { - showDeleteKeyboard() - } - } - - private func fetchedKeyboardData(_ data: Data) { - guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [AnyHashable: Any] else { - return + showDeleteResource() } - let keyboards = json[Key.language] as? [Any] - let kbDict = keyboards?[0] as? [AnyHashable: Any] - var info = infoArray[1] - let copyright = kbDict?[Key.keyboardCopyright] as? String ?? "Unknown" - - info["subtitle"] = copyright - infoArray[1] = info - tableView.reloadData() } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { @@ -167,40 +166,34 @@ class ResourceInfoViewController: UIViewController, UIAlertViewDelegate, UITable if !isCustomKeyboard { if indexPath.row == 1 { cell.accessoryType = .disclosureIndicator - } else if indexPath.row == 2 && !canDeleteKeyboard { + } else if indexPath.row == 2 && !mayDelete { cell.isUserInteractionEnabled = false cell.textLabel?.isEnabled = false cell.detailTextLabel?.isEnabled = false } - } else if indexPath.row == 1 && !canDeleteKeyboard { + } else if indexPath.row == 1 && !mayDelete { cell.isUserInteractionEnabled = false cell.textLabel?.isEnabled = false cell.detailTextLabel?.isEnabled = false } } - private var canDeleteKeyboard: Bool { - if !Manager.shared.canRemoveKeyboards { - return false - } - - if !Manager.shared.canRemoveDefaultKeyboard { - return keyboardIndex != 0 - } + private func showDeleteResource() { + var uninstallLabelKey: String - if keyboardIndex > 0 { - return true + if Resource.self == InstallableLexicalModel.self { + uninstallLabelKey = "command-uninstall-lexical-model-confirm" + } else { + uninstallLabelKey = "command-uninstall-keyboard-confirm" } - return keyboardCount > 1 - } - private func showDeleteKeyboard() { - let alertController = UIAlertController(title: title ?? "", message: "Would you like to delete this keyboard?", + let uninstallHelp = NSLocalizedString(uninstallLabelKey, bundle: engineBundle, comment: "") + let alertController = UIAlertController(title: title ?? "", message: uninstallHelp, preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "Cancel", + alertController.addAction(UIAlertAction(title: NSLocalizedString("command-cancel", bundle: engineBundle, comment: ""), style: UIAlertAction.Style.cancel, handler: nil)) - alertController.addAction(UIAlertAction(title: "Delete", + alertController.addAction(UIAlertAction(title: NSLocalizedString("command-uninstall", bundle: engineBundle, comment: ""), style: UIAlertAction.Style.default, handler: deleteHandler)) @@ -208,8 +201,14 @@ class ResourceInfoViewController: UIViewController, UIAlertViewDelegate, UITable } func deleteHandler(withAction action: UIAlertAction) { - if Manager.shared.removeKeyboard(at: keyboardIndex) { + if let lexicalModel = resource as? InstallableLexicalModel { + if Manager.shared.removeLexicalModel(withFullID: lexicalModel.typedFullID) { navigationController?.popToRootViewController(animated: true) + } + } else if let keyboard = resource as? InstallableKeyboard { + if Manager.shared.removeKeyboard(withFullID: keyboard.typedFullID) { + navigationController?.popToRootViewController(animated: true) + } } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/en.lproj/ResourceInfoView.strings b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/en.lproj/ResourceInfoView.strings new file mode 100644 index 0000000000000000000000000000000000000000..aa12fd1fb3b2ff18b455cb1dfc3c5e4c97380cb0 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/en.lproj/ResourceInfoView.strings @@ -0,0 +1,3 @@ + +/* Class = "UILabel"; text = "Scan this code to load this keyboard on another device"; ObjectID = "z2O-MT-IoV"; */ +"z2O-MT-IoV.text" = "Scan this code to load this keyboard on another device"; diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/km.lproj/ResourceInfoView.strings b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/km.lproj/ResourceInfoView.strings new file mode 100644 index 0000000000000000000000000000000000000000..aa12fd1fb3b2ff18b455cb1dfc3c5e4c97380cb0 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/LanguagePicker/km.lproj/ResourceInfoView.strings @@ -0,0 +1,3 @@ + +/* Class = "UILabel"; text = "Scan this code to load this keyboard on another device"; ObjectID = "z2O-MT-IoV"; */ +"z2O-MT-IoV.text" = "Scan this code to load this keyboard on another device"; diff --git a/ios/engine/KMEI/KeymanEngine/Classes/LexicalModelKeymanPackage.swift b/ios/engine/KMEI/KeymanEngine/Classes/LexicalModelKeymanPackage.swift new file mode 100644 index 0000000000000000000000000000000000000000..6161e1e6ac0c32b3e51ed0996c179b5faab7e1da --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/LexicalModelKeymanPackage.swift @@ -0,0 +1,48 @@ +// +// LexicalModelKeymanPackage.swift +// KeymanEngine +// +// Created by Randy Boring on 3/4/19. +// Copyright © 2019 SIL International. All rights reserved. +// + +import Foundation + +public class LexicalModelKeymanPackage : TypedKeymanPackage { + internal var models : [KMPLexicalModel]! + + override internal init(metadata: KMPMetadata, folder: URL) { + super.init(metadata: metadata, folder: folder) + self.models = [] + + if let packagedModels = metadata.lexicalModels { + for model in packagedModels { + model.packageId = self.id + + // If completely missing, we set the version to 1.0. Legacy decision from 2005. + model.setNilVersion(to: metadata.info?.version?.description ?? "1.0") + if(model.isValid && FileManager.default.fileExists(atPath: self.sourceFolder.appendingPathComponent("\(model.lexicalModelId).model.js").path)) { + models.append(model) + } else { + log.debug("\(model.name) not valid / corresponding file not found") + } + } + } + + self.setInstallableResourceSets(for: models) + } + + public override func defaultInfoHtml() -> String { + let formatString = NSLocalizedString("package-default-found-lexical-models", bundle: engineBundle, comment: "See Localized.stringsdict") + var str = String.localizedStringWithFormat(formatString, models.count) + "
" + for model in models { + str += model.lexicalModelId + "
" + } + return str + } + + override var resources: [AnyKMPResource] { + return models + } +} + diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Manager.swift b/ios/engine/KMEI/KeymanEngine/Classes/Manager.swift index fd66191987164abe565f91cafd29a48fb8c9ebdb..d453ef1a82af90278ba8ee853c3b384af92055f0 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Manager.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Manager.swift @@ -17,6 +17,7 @@ typealias FetchKeyboardsBlock = ([String: Any]?) -> Void // MARK: - Constants // Possible states that a keyboard or lexical model can be in +@available(*, deprecated, message: "Version checks against keyboards and models are now based on their package. Use `KeymanPackage.InstallationState` and `KeymanPackage.VersionState` instead.") public enum KeyboardState { case needsDownload case needsUpdate @@ -32,11 +33,10 @@ public enum VibrationSupport { case taptic // Has the Taptic engine, allowing use of UIImpactFeedbackGenerator for customizable vibrations } -// Strings -private let keyboardChangeHelpText = "Tap here to change keyboard" - -// URLs - used for reachability test -private let keymanHostName = "api.keyman.com" +/** + * Obtains the bundle for KeymanEngine.framework. + */ +internal let engineBundle: Bundle = Bundle(for: Manager.self) public class Manager: NSObject, UIGestureRecognizerDelegate { /// Application group identifier for shared container. Set this before accessing the shared manager. @@ -86,9 +86,6 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { /// The default value is false. public var canRemoveDefaultKeyboard = false - public let apiKeyboardRepository: APIKeyboardRepository - - // TODO: Change API to not disable removing as well /// Allow users to add new lexical models in the lexical model picker. /// - Default value is true. @@ -116,8 +113,6 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { /// The last lexical model CAN be removed, as this is an optional feature /// The default value is true. public var canRemoveDefaultLexicalModel = true - - public let apiLexicalModelRepository: APILexicalModelRepository /// In keyboard extensions (system keyboard), `UIApplication.openURL(_:)` is unavailable. The API is not called in /// the system keyboard since `KeyboardInfoViewController` is never used. `openURL(:_)` is only used in applications, @@ -169,15 +164,10 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { //private var downloadQueue: HTTPDownloader? private var reachability: Reachability! var didSynchronize = false - - - private var keyboardDownloadCompletedObserver: NotificationObserver? // MARK: - Object Admin private override init() { - apiKeyboardRepository = APIKeyboardRepository() - apiLexicalModelRepository = APILexicalModelRepository() super.init() URLProtocol.registerClass(KeymanURLProtocol.self) @@ -210,7 +200,7 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { updateUserKeyboards(with: Defaults.keyboard) do { - try reachability = Reachability(hostname: keymanHostName) + try reachability = Reachability(hostname: KeymanHosts.API_KEYMAN_COM.host!) } catch { log.error("Could not start Reachability object: \(error)") } @@ -224,11 +214,6 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { log.error("failed to start Reachability notifier: \(error)") } } - - keyboardDownloadCompletedObserver = NotificationCenter.default.addObserver( - forName: Notifications.keyboardDownloadCompleted, - observer: self, - function: Manager.keyboardDownloadCompleted) // We used to preload the old KeymanWebViewController, but now that it's embedded within the // InputViewController, that's not exactly viable. @@ -302,10 +287,10 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { currentKeyboardID = kb.fullID if let fontFilename = kb.font?.source.first(where: { $0.hasFontExtension }) { - _ = FontManager.shared.registerFont(at: Storage.active.fontURL(forKeyboardID: kb.id, filename: fontFilename)) + _ = FontManager.shared.registerFont(at: Storage.active.fontURL(forResource: kb, filename: fontFilename)!) } if let oskFontFilename = kb.oskFont?.source.first(where: { $0.hasFontExtension }) { - _ = FontManager.shared.registerFont(at: Storage.active.fontURL(forKeyboardID: kb.id, filename: oskFontFilename)) + _ = FontManager.shared.registerFont(at: Storage.active.fontURL(forResource: kb, filename: oskFontFilename)!) } inputViewController.setKeyboard(kb) @@ -342,27 +327,26 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { /// Adds a new keyboard to the list in the keyboard picker if it doesn't already exist. /// The keyboard must be downloaded (see `downloadKeyboard()`) or preloaded (see `preloadLanguageFile()`) + @available(*, deprecated, message: "Deprecated in favor of ResourceFileManager.install(resourceWithID:from:)") public func addKeyboard(_ keyboard: InstallableKeyboard) { - let keyboardPath = Storage.active.keyboardURL(for: keyboard).path - if !FileManager.default.fileExists(atPath: keyboardPath) { - log.error("Could not add keyboard with ID: \(keyboard.id) because the keyboard file does not exist") - return - } + var kbdToInstall = keyboard - // Get keyboards list if it exists in user defaults, otherwise create a new one - let userDefaults = Storage.active.userDefaults - var userKeyboards = userDefaults.userKeyboards ?? [] - - // Update keyboard if it exists - if let index = userKeyboards.firstIndex(where: { $0.fullID == keyboard.fullID }) { - userKeyboards[index] = keyboard + // 3rd party installation of keyboards (13.0 and before): + // - Manager.shared.preloadFiles was called first to import the file resources + // - Then Manager.shared.addKeyboard installs the keyboard. + // + // Since 3rd-party uses never provided kmp.json files, we need to instant-migrate + // them here. + if !Migrations.resourceHasPackageMetadata(keyboard) { + let wrappedKbds = Migrations.migrateToKMPFormat([keyboard]) + guard wrappedKbds.count == 1 else { + log.error("Could not properly import keyboard") + return + } + kbdToInstall = wrappedKbds[0] } else { - userKeyboards.append(keyboard) + ResourceFileManager.shared.addResource(kbdToInstall) } - - userDefaults.userKeyboards = userKeyboards - userDefaults.set([Date()], forKey: Key.synchronizeSWKeyboard) - userDefaults.synchronize() } @@ -407,29 +391,27 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { * The lexical model must be downloaded (see `downloadLexicalModel()`) or preloaded (see `preloadLanguageFile()`) * I believe this is background-thread-safe (no UI done) */ + @available(*, deprecated, message: "Deprecated in favor of ResourceFileManager.install(resourceWithID:from:)") static public func addLexicalModel(_ lexicalModel: InstallableLexicalModel) { - let lexicalModelPath = Storage.active.lexicalModelURL(for: lexicalModel).path - if !FileManager.default.fileExists(atPath: lexicalModelPath) { - log.error("Could not add lexical model with ID: \(lexicalModel.id) because the lexical model file does not exist") - return - } - - // Get lexical models list if it exists in user defaults, otherwise create a new one - let userDefaults = Storage.active.userDefaults - var userLexicalModels = userDefaults.userLexicalModels ?? [] - - // Update lexical model if it exists - if let index = userLexicalModels.firstIndex(where: { $0.fullID == lexicalModel.fullID }) { - userLexicalModels[index] = lexicalModel + var modelToInstall = lexicalModel + + // Potential 3rd party installation of lexical models (12.0, 13.0): + // - Manager.shared.preloadFiles was called first to import the file resources + // - Then Manager.addLexicalModel installs the lexical model. + // + // Since 3rd-party uses never provided kmp.json files, we need to instant-migrate + // them here. + if !Migrations.resourceHasPackageMetadata(lexicalModel) { + let wrappedModels = Migrations.migrateToKMPFormat([lexicalModel]) + guard wrappedModels.count == 1 else { + log.error("Could not properly import lexical model") + return + } + modelToInstall = wrappedModels[0] } else { - userLexicalModels.append(lexicalModel) + ResourceFileManager.shared.addResource(modelToInstall) } - - userDefaults.userLexicalModels = userLexicalModels - userDefaults.set([Date()], forKey: Key.synchronizeSWLexicalModel) - userDefaults.synchronize() - log.info("Added lexical model ID: \(lexicalModel.id) name: \(lexicalModel.name)") -} + } /// Removes a keyboard from the list in the keyboard picker if it exists. /// - Returns: The keyboard exists and was removed @@ -470,7 +452,9 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { } if !userKeyboards.contains(where: { $0.id == kb.id }) { - let keyboardDir = Storage.active.keyboardDir(forID: kb.id) + // TODO: should make sure that there are no resources in the package, + // rather than just 'no matching keyboards'. + let keyboardDir = Storage.active.resourceDir(for: kb)! FontManager.shared.unregisterFonts(in: keyboardDir, fromSystemOnly: false) log.info("Deleting directory \(keyboardDir)") if (try? FileManager.default.removeItem(at: keyboardDir)) == nil { @@ -552,7 +536,7 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { } if !userLexicalModels.contains(where: { $0.id == lm.id }) { - let lexicalModelDir = Storage.active.lexicalModelDir(forID: lm.id) + let lexicalModelDir = Storage.active.resourceDir(for: lm)! FontManager.shared.unregisterFonts(in: lexicalModelDir, fromSystemOnly: false) log.info("Deleting directory \(lexicalModelDir)") if (try? FileManager.default.removeItem(at: lexicalModelDir)) == nil { @@ -591,9 +575,9 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { /// - The keyboard doesn't have a font /// - The keyboard info is not available in the user keyboards list public func fontNameForKeyboard(withFullID fullID: FullKeyboardID) -> String? { - let kb = Storage.active.userDefaults.userKeyboard(withFullID: fullID) - if let filename = kb?.font?.source.first(where: { $0.hasFontExtension }) { - let fontURL = Storage.active.fontURL(forKeyboardID: fullID.keyboardID, filename: filename) + if let kb = Storage.active.userDefaults.userKeyboard(withFullID: fullID), + let filename = kb.font?.source.first(where: { $0.hasFontExtension }) { + let fontURL = Storage.active.fontURL(forResource: kb, filename: filename)! return FontManager.shared.fontName(at: fontURL) } return nil @@ -603,9 +587,9 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { /// - The keyboard doesn't have an OSK font /// - The keyboard info is not available in the user keyboards list func oskFontNameForKeyboard(withFullID fullID: FullKeyboardID) -> String? { - let kb = Storage.active.userDefaults.userKeyboard(withFullID: fullID) - if let filename = kb?.oskFont?.source.first(where: { $0.hasFontExtension }) { - let fontURL = Storage.active.fontURL(forKeyboardID: fullID.keyboardID, filename: filename) + if let kb = Storage.active.userDefaults.userKeyboard(withFullID: fullID), + let filename = kb.oskFont?.source.first(where: { $0.hasFontExtension }) { + let fontURL = Storage.active.fontURL(forResource: kb, filename: filename)! return FontManager.shared.fontName(at: fontURL) } return nil @@ -613,191 +597,29 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { // MARK: - Adhoc keyboards public func parseKbdKMP(_ folder: URL, isCustom: Bool) throws -> Void { - do { - var path = folder - path.appendPathComponent("kmp.json") - let data = try Data(contentsOf: path, options: .mappedIfSafe) - let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) - if let jsonResult = jsonResult as? [String:AnyObject] { - if let keyboards = jsonResult["keyboards"] as? [[String:AnyObject]] { - for k in keyboards { - let name = k["name"] as! String - let keyboardID = k["id"] as! String - let version = k["version"] as! String - //true if the keyboard targets a right-to-left script. false if absent. - let isrtl: Bool = k["rtl"] as? Bool ?? false - - var oskFont: Font? - let osk = k["oskFont"] as? String - if let _ = osk { - oskFont = Font(filename: osk!) - } - var displayFont: Font? - let font = k["displayFont"] as? String - if let _ = font { - displayFont = Font(filename: font!) - } - - //TODO: handle errors if languages do not exist - var languageName = "" - var languageId = "" - - var installableKeyboards : [InstallableKeyboard] = [] - if let langs = k["languages"] as? [[String:String]] { - for l in langs { - languageName = l["name"]! - languageId = l["id"]! - - installableKeyboards.append( InstallableKeyboard( - id: keyboardID, - name: name, - languageID: languageId, - languageName: languageName, - version: version, - isRTL: isrtl, - font: displayFont, - oskFont: oskFont, - isCustom: isCustom)) - } - } - - do { - try FileManager.default.createDirectory(at: Storage.active.keyboardDir(forID: keyboardID), - withIntermediateDirectories: true) - } catch { - log.error("Could not create dir for download: \(error)") - throw KMPError.fileSystem - } - - var haveInstalledOne = false - for keyboard in installableKeyboards { - let storedPath = Storage.active.keyboardURL(for: keyboard) - - var installableFiles: [[Any]] = [["\(keyboardID).js", storedPath]] - if let osk = osk { - let oskPath = Storage.active.fontURL(forKeyboardID: keyboardID, filename: osk) - installableFiles.append([osk, oskPath]) - } - - if let font = font { - let displayPath = Storage.active.fontURL(forKeyboardID: keyboardID, filename: font) - installableFiles.append([font, displayPath]) - } - do { - for item in installableFiles { - var filePath = folder - if(FileManager.default.fileExists(atPath: (item[1] as! URL).path)) { - try FileManager.default.removeItem(at: item[1] as! URL) - } - filePath.appendPathComponent(item[0] as! String) - try FileManager.default.copyItem(at: filePath, - to: item[1] as! URL) - - } - } catch { - log.error("Error saving the download: \(error)") - throw KMPError.copyFiles - } - if !haveInstalledOne { - Manager.shared.addKeyboard(keyboard) - haveInstalledOne = true - } - } - } - } + guard let kmp = KeymanPackage.parse(folder) as? KeyboardKeymanPackage else { + throw KMPError.wrongPackageType + } + + for resourceSet in kmp.installables { + for resource in resourceSet { + try ResourceFileManager.shared.install(resourceWithID: resource.fullID, from: kmp) + // Install the keyboard for only the first language pairing defined in the package. + break } - } catch { - log.error("error parsing keyboard kmp: \(error)") - throw KMPError.invalidPackage } } // MARK: - Adhoc lexical models static public func parseLMKMP(_ folder: URL, isCustom: Bool) throws -> Void { - do { - var path = folder - path.appendPathComponent("kmp.json") - let data = try Data(contentsOf: path, options: .mappedIfSafe) - let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) - if let jsonResult = jsonResult as? [String:AnyObject] { - var version: String = "1.0" - - if let info = jsonResult["info"] as? [String:AnyObject] { - if let versionEntry = info["version"] as? [String:AnyObject] { - if let description = versionEntry["description"] as? String { - version = description; - } - } - } - - // Version uses a 'conditional initializer'. If it fails, the version info is invalid. - if let _ = Version(version) { - // No problem - } else { - // Lazy-handle the error and replace version with 1.0. Legacy decision from 2005. - version = "1.0" - } + guard let kmp = KeymanPackage.parse(folder) as? LexicalModelKeymanPackage else { + throw KMPError.wrongPackageType + } - if let lexicalModels = jsonResult["lexicalModels"] as? [[String:AnyObject]] { - for k in lexicalModels { - let name = k["name"] as! String - let lexicalModelID = k["id"] as! String - - //TODO: handle errors if languages do not exist - //var languageName = "" - var languageId = "" - - var installableLexicalModels : [InstallableLexicalModel] = [] - if let langs = k["languages"] as? [[String:String]] { - for l in langs { - //languageName = l["name"]! - languageId = l["id"]! - - installableLexicalModels.append( InstallableLexicalModel( - id: lexicalModelID, - name: name, - languageID: languageId, -// languageName: languageName, - version: version, - isCustom: isCustom)) - } - } - - do { - try FileManager.default.createDirectory(at: Storage.active.lexicalModelDir(forID: lexicalModelID), - withIntermediateDirectories: true) - } catch { - log.error("Could not create dir for download: \(error)") - throw KMPError.fileSystem - } - - for lexicalModel in installableLexicalModels { - let storedPath = Storage.active.lexicalModelURL(for: lexicalModel) - - let installableFiles: [[Any]] = [["\(lexicalModelID).model.js", storedPath]] - do { - for item in installableFiles { - var filePath = folder - if(FileManager.default.fileExists(atPath: (item[1] as! URL).path)) { - try FileManager.default.removeItem(at: item[1] as! URL) - } - filePath.appendPathComponent(item[0] as! String) - try FileManager.default.copyItem(at: filePath, - to: item[1] as! URL) - - } - } catch { - log.error("Error saving the lexical model download: \(error)") - throw KMPError.copyFiles - } - Manager.addLexicalModel(lexicalModel) - } - } - } + try kmp.installables.forEach { resourceSet in + try resourceSet.forEach { resource in + try ResourceFileManager.shared.install(resourceWithID: resource.fullID, from: kmp) } - } catch { - log.error("error parsing lexical model kmp: \(error)") - throw KMPError.invalidPackage } } @@ -818,8 +640,9 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { // MARK: - Loading custom keyboards /// Preloads the JS and font files required for a keyboard. + @available(*, deprecated, message: "Use ResourceFileManager's methods to install resources from KMPs.") public func preloadFiles(forKeyboardID keyboardID: String, at urls: [URL], shouldOverwrite: Bool) throws { - let keyboardDir = Storage.active.keyboardDir(forID: keyboardID) + let keyboardDir = Storage.active.legacyKeyboardDir(forID: keyboardID) try FileManager.default.createDirectory(at: keyboardDir, withIntermediateDirectories: true) for url in urls { try Storage.copy(at: url, @@ -997,16 +820,6 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { return .none } } - - // Keyboard download notification observers - private func keyboardDownloadCompleted(_ keyboards: [InstallableKeyboard]) { - // There's little harm in reloading the keyboard (and thus, KMW) for a clean reset - // after resource downloads or updates. That said, we should avoid *directly* - // triggering an immediate reset, as an extra reset will occur once we leave the - // settings menu. The delay also helps any chained downloads (keyboard > lexical model) - // to fully complete first. - shouldReloadKeyboard = true - } /*----------------------------- * Legacy API endpoints - @@ -1017,35 +830,34 @@ public class Manager: NSObject, UIGestureRecognizerDelegate { * the data for apps built on older versions of KMEI, though. */ - public func downloadKeyboard(from url: URL) { - ResourceDownloadManager.shared.downloadKeyboard(from: url) - } - public func downloadKeyboard(withID: String, languageID: String, isUpdate: Bool, fetchRepositoryIfNeeded: Bool = true) { + let kbdFullID = FullKeyboardID(keyboardID: withID, languageID: languageID) + let completionBlock = ResourceDownloadManager.shared.standardKeyboardInstallCompletionBlock(forFullID: kbdFullID, withModel: true) ResourceDownloadManager.shared.downloadKeyboard(withID: withID, languageID: languageID, isUpdate: isUpdate, - fetchRepositoryIfNeeded: fetchRepositoryIfNeeded) - } - - // A new API, but it so closely parallels downloadKeyboard that we should add a 'helper' handler here. - public func downloadLexicalModel(from url: URL) { - ResourceDownloadManager.shared.downloadLexicalModel(from: url) + fetchRepositoryIfNeeded: fetchRepositoryIfNeeded, + completionBlock: completionBlock) } // A new API, but it so closely parallels downloadKeyboard that we should add a 'helper' handler here. public func downloadLexicalModel(withID: String, languageID: String, isUpdate: Bool, fetchRepositoryIfNeeded: Bool = true) { + let lmFullID = FullLexicalModelID(lexicalModelID: withID, languageID: languageID) + let completionBlock = ResourceDownloadManager.shared.standardLexicalModelInstallCompletionBlock(forFullID: lmFullID) ResourceDownloadManager.shared.downloadLexicalModel(withID: withID, languageID: languageID, isUpdate: isUpdate, - fetchRepositoryIfNeeded: fetchRepositoryIfNeeded) + fetchRepositoryIfNeeded: fetchRepositoryIfNeeded, + completionBlock: completionBlock) } + @available(*, deprecated, message: "") // TODO: Write method on KeymanPackage for this. public func stateForKeyboard(withID keyboardID: String) -> KeyboardState { return ResourceDownloadManager.shared.stateForKeyboard(withID: keyboardID) } // Technically new, but it does closely parallel an old API point. + @available(*, deprecated, message: "") // TODO: Write method on KeymanPackage for this. public func stateForLexicalModel(withID modelID: String) -> KeyboardState { return ResourceDownloadManager.shared.stateForLexicalModel(withID: modelID) } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Migrations.swift b/ios/engine/KMEI/KeymanEngine/Classes/Migrations.swift index 6bd695f2b3e2670efdaa73557a35e2e9506424d4..02516f6267af7df0a36af9b252f1b52c60522677 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Migrations.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Migrations.swift @@ -16,10 +16,10 @@ private enum MigrationLevel { struct VersionResourceSet { var version: Version - var resources: [LanguageResource] + var resources: [AnyLanguageResource] // but how to handle deprecation? - init(version: Version, resources: [LanguageResource]) { + init(version: Version, resources: [AnyLanguageResource]) { self.version = version self.resources = resources } @@ -50,32 +50,53 @@ public enum Migrations { oskFont: nil, isCustom: false) + let sil_euro_latin_1_8_1 = InstallableKeyboard(id: "sil_euro_latin", + name: "EuroLatin (SIL)", + languageID: "en", + languageName: "English", + version: "1.8.1", + isRTL: false, + font: font, + oskFont: nil, + isCustom: false) + + let sil_euro_latin_1_9_1 = InstallableKeyboard(id: "sil_euro_latin", + name: "EuroLatin (SIL)", + languageID: "en", + languageName: "English", + version: "1.9.1", + isRTL: false, + font: font, + oskFont: nil, + isCustom: false) + let nrc_en_mtnt_0_1_2 = InstallableLexicalModel(id: "nrc.en.mtnt", name: "English dictionary (MTNT)", languageID: "en", version: "0.1.2", isCustom: false) - let sil_euro_latin = Defaults.keyboard // We're already storing the exact metadata needed. let nrc_en_mtnt = Defaults.lexicalModel // Unknown transition point: european // Before v11: european2 - // Before v12: sil_euro_latin - // At v12: sil_euro_latin + nrc.en.mtnt (lex model) + // Before v12: sil_euro_latin 1.8.1 + // At v12: sil_euro_latin 1.8.1 + nrc.en.mtnt (lex model) var timeline: [VersionResourceSet] = [] let legacy_resources = VersionResourceSet(version: Version.fallback, resources: [european]) let v10_resources = VersionResourceSet(version: Version("10.0")!, resources: [european2]) - let v11_resources = VersionResourceSet(version: Version("11.0")!, resources: [sil_euro_latin]) - let v12_resources = VersionResourceSet(version: Version("12.0")!, resources: [sil_euro_latin, nrc_en_mtnt_0_1_2]) - let v13_resources = VersionResourceSet(version: Version("13.0.65")!, resources: [sil_euro_latin, nrc_en_mtnt]) + let v11_resources = VersionResourceSet(version: Version("11.0")!, resources: [sil_euro_latin_1_8_1]) + let v12_resources = VersionResourceSet(version: Version("12.0")!, resources: [sil_euro_latin_1_8_1, nrc_en_mtnt_0_1_2]) + let v13_resources = VersionResourceSet(version: Version("13.0.65")!, resources: [sil_euro_latin_1_8_1, nrc_en_mtnt]) + let v14_resources = VersionResourceSet(version: Version("14.0.0")!, resources: [sil_euro_latin_1_9_1, nrc_en_mtnt]) timeline.append(legacy_resources) timeline.append(v10_resources) timeline.append(v11_resources) timeline.append(v12_resources) timeline.append(v13_resources) + timeline.append(v14_resources) return timeline }() @@ -105,6 +126,16 @@ public enum Migrations { } else { log.info("Documents directory structure compatible with \(Version.fileBrowserImplemented)") } + + if version < Version.packageBasedFileReorg { + do { + try migrateCloudResourcesToKMPFormat() + } catch { + log.error("Could not migrate pre-existing resources to KMP-style file organization") + } + } else { + log.info("Resource directories already migrated to package-based format; kmp.jsons already exist.") + } } storage.userDefaults.synchronize() @@ -364,6 +395,7 @@ public enum Migrations { return Font(family: family, source: files) } + // OLD legacy migration. static func migrateForKMP(storage: Storage) { let languageDir = storage.baseDir.appendingPathComponent("languages") let fontDir = storage.baseDir.appendingPathComponent("fonts") @@ -406,7 +438,7 @@ public enum Migrations { // Copy files for (keyboardID, urls) in urlsForKeyboard { - let keyboardDir = storage.keyboardDir(forID: keyboardID) + let keyboardDir = storage.legacyKeyboardDir(forID: keyboardID) do { try FileManager.default.createDirectory(at: keyboardDir, withIntermediateDirectories: true, @@ -490,4 +522,186 @@ public enum Migrations { } } } + + static func migrateCloudResourcesToKMPFormat() throws { + let userDefaults = Storage.active.userDefaults + + if var userKeyboards = userDefaults.userKeyboards { + userKeyboards = migrateToKMPFormat(userKeyboards) + userDefaults.userKeyboards = userKeyboards + } + + if var userLexicalModels = userDefaults.userLexicalModels { + userLexicalModels = migrateToKMPFormat(userLexicalModels) + userDefaults.userLexicalModels = userLexicalModels + } + } + + static func migrateToKMPFormat( + _ resources: [Resource]) -> [Resource] + where Resource.Package: TypedKeymanPackage { + // Step 1 - drop version numbers from all filenames. KMP installations don't include them, and + // the version numbered filenames will actually interfere with migration. + resources.forEach { resource in + let srcLocation = Storage.active.legacyResourceURL(for: resource)! + let dstLocation = Storage.active.resourceURL(for: resource)! + + do { + if FileManager.default.fileExists(atPath: srcLocation.path) { + try FileManager.default.moveItem(at: srcLocation, to: dstLocation) + } + } catch { + log.error("Could not remove version number from filename for resource \(resource.packageID ?? "").\(resource.id)") + log.error("Source: \(srcLocation)") + } + } + + // Step 2 - analyze all locally-cached KMPs for possible resource sources. + var allLocalPackages: [(KeymanPackage, URL)] = [] + do { + let cachedKMPsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let files = try FileManager.default.contentsOfDirectory(atPath: cachedKMPsDirectory.path) + let kmpFiles = files.filter { $0.suffix(4).lowercased() == ".kmp" } + + allLocalPackages = kmpFiles.compactMap { file in + let filePath = cachedKMPsDirectory.appendingPathComponent(file) + do { + let tuple = try (ResourceFileManager.shared.prepareKMPInstall(from: filePath), filePath) + return tuple + } catch { + log.error("Could not load kmp.info for \(filePath)") + return nil + } + } + } catch { + log.error("Could not check contents of Documents directory for resource-migration assist") + } + + // Filters out Packages that don't contain the matching resource type. + let localPackages: [(Resource.Package, URL)] = allLocalPackages.compactMap { tuple in + if let package = tuple.0 as? Resource.Package { + return (package, tuple.1) + } else { + return nil + } + } + + // Step 3 - determine which resources were installed from our locally-available KMPs, + // then migrate by reinstalling the KMP. + var matched: [Resource] = [] + + localPackages.forEach { (package, kmpFile) in + let packageMatches: [Resource] = resources.compactMap { resource in + if let possibleMatch = package.findResource(withID: resource.typedFullID) { + if possibleMatch.version == resource.version { + return resource + } + } + // else, for either if-condition. + return nil + } + + // All resources within packageMatches were sourced from the current package. + // Time to set migrate these. Overwrites any obstructing files with the + // the decompressed KMP's contents. + do { + // We've already parsed the metadata, but now we need to have the files ready for install. + try packageMatches.forEach { resource in + try ResourceFileManager.shared.install(resourceWithID: resource.typedFullID, from: package) + matched.append(package.findResource(withID: resource.typedFullID)!) + } + } catch { + log.error("Could not install resource from locally-cached package: \(String(describing: error))") + } + } + + // Step 4 - anything unmatched is a cloud resource. Autogenerate a kmp.json for it + // so that it becomes its own package. (Is already installed in own subdir.) + let unmatched: [Resource] = resources.compactMap { resource in + // Return the resource only if it isn't in the 'matched' array, + return matched.contains(where: { $0.typedFullID == resource.typedFullID }) ? nil : resource + } + + var wrapperPackages: [Resource.Package] = [] + + // The following block loads any already-migrated local resources; there's a chance we may + // need to merge new resources into an autogenerated kmp.json. (Cloud JS workaround - data + // loss prevention) + // + // In a manner, this re-migrates them harmlessly. Safe to eliminate the block below + // once Cloud JS downloads are removed in favor of KMP downloads, at which point this + // method will only ever be called a single time. + wrapperPackages = ResourceFileManager.shared.installedPackages.compactMap { package in + // We only consider appending resources to existing kmp.jsons if the kmp.jsons were + // produced during resource migration. We don't alter Developer-compiled kmp.jsons. + if package.metadata.isAutogeneratedWrapper { + return package as? Resource.Package // also ensures it's the right package type. + } else { + return nil + } + } + + for resource in unmatched { + // Did we already build a matching wrapper package? + let packageMatches: [Resource.Package] = wrapperPackages.compactMap { package in + let metadata: Resource.Metadata? = package.findMetadataMatchFor(resource: resource, ignoreLanguage: true, ignoreVersion: true) + return (metadata != nil) ? package : nil + } + + if packageMatches.count > 0 { + // We did! Add this resource to the existing metadata object. + var resourceMetadata: Resource.Metadata = packageMatches[0].findMetadataMatchFor(resource: resource, ignoreLanguage: true, ignoreVersion: true)! + // Ensure we don't accidentally make a duplicate entry. + // Of particular interest while the Cloud-download stop-gap measure is in place. + if !resourceMetadata.languages.contains(where: { + return $0.languageId == resource.languageID + }) { + resourceMetadata.languages.append(KMPLanguage(from: resource)!) + // Update the installable resources listing! + packageMatches[0].setInstallableResourceSets(for: [resourceMetadata]) + } + } else { + // Time for a new wrapper package! + let location = Storage.active.resourceDir(for: resource)! + let migrationPackage = KeymanPackage.forMigration(of: resource, at: location)! + wrapperPackages.append(migrationPackage as! Resource.Package) + } + } + + // Step 5 - write out the finalized metadata for the new 'wrapper' Packages + for package in wrapperPackages { + let folderURL = Storage.active.packageDir(for: package) + let metadataFile = folderURL!.appendingPathComponent("kmp.json") + let encoder = JSONEncoder() + do { + let metadataJSON = try encoder.encode(package.metadata) + FileManager.default.createFile(atPath: metadataFile.path, contents: metadataJSON, attributes: .none) + // write to location. + } catch { + log.error("Could not generate kmp.json for legacy resource!") + } + } + + // Step 6 - return the Resources that map to the original argument. + + // Each wrapper package contains only a single resource. .installables[0] returns all + // LanguageResource pairings for that script resource. + let wrappedResources: [Resource] = wrapperPackages.flatMap { $0.installables[0] } + + let mappedResources: [Resource] = wrappedResources.compactMap { resource in + if resources.contains(where: { $0.typedFullID == resource.typedFullID}) { + return resource + } else { + return nil + } + } + + return matched + mappedResources + } + + internal static func resourceHasPackageMetadata(_ resource: Resource) -> Bool { + var resourceDir = Storage.active.resourceDir(for: resource)! + resourceDir.appendPathComponent("kmp.json") + return FileManager.default.fileExists(atPath: resourceDir.path) + } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/FullKeyboardID.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/FullKeyboardID.swift index a243a1af111f723834ea89c9a9de1d7d2d1c4d09..67f98e7c544f8eaf1139a25f3bf65f4a6b809f71 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/FullKeyboardID.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Model/FullKeyboardID.swift @@ -9,15 +9,23 @@ import Foundation /// A complete identifier for an `InstallableKeyboard`. Keyboards must have unique `FullKeyboardID`s. -public struct FullKeyboardID: Codable { +public struct FullKeyboardID: Codable, LanguageResourceFullID, Equatable { + public typealias Resource = InstallableKeyboard + public var keyboardID: String public var languageID: String -} -// MARK: - Equatable -extension FullKeyboardID: Equatable { - public static func ==(lhs: FullKeyboardID, rhs: FullKeyboardID) -> Bool { - return lhs.keyboardID == rhs.keyboardID && lhs.languageID == rhs.languageID + public var id: String { + return keyboardID + } + + public var type: LanguageResourceType { + return .keyboard + } + + public init(keyboardID: String, languageID: String) { + self.keyboardID = keyboardID + self.languageID = languageID } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/FullLexicalModelID.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/FullLexicalModelID.swift index b86d03c8363a565b276b60dc3df7740b4cffb352..060b119978926ed4fabcfddd4cfcbab00d5d6490 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/FullLexicalModelID.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Model/FullLexicalModelID.swift @@ -9,15 +9,18 @@ import Foundation /// A complete identifier for an `InstallableLexicalModel`. LexicalModels must have unique `FullLexicalModelID`s. -public struct FullLexicalModelID: Codable { +public struct FullLexicalModelID: Codable, LanguageResourceFullID, Equatable { + public typealias Resource = InstallableLexicalModel + public var lexicalModelID: String public var languageID: String -} -// MARK: - Equatable -extension FullLexicalModelID: Equatable { - public static func ==(lhs: FullLexicalModelID, rhs: FullLexicalModelID) -> Bool { - return lhs.lexicalModelID == rhs.lexicalModelID && lhs.languageID == rhs.languageID + public var id: String { + return lexicalModelID + } + + public var type: LanguageResourceType { + return .lexicalModel } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/InstallableKeyboard.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/InstallableKeyboard.swift index 00c6e41241599ac239c937065f5f50f47a9b832a..aaa3f890bb0051abf1f5ff73e8bdb7a4972845a3 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/InstallableKeyboard.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Model/InstallableKeyboard.swift @@ -9,10 +9,15 @@ import Foundation /// Mainly differs from the API `Keyboard` by having an associated language. -public struct InstallableKeyboard: Codable, LanguageResource { +public struct InstallableKeyboard: Codable, KMPInitializableLanguageResource { + public typealias FullID = FullKeyboardID + internal typealias Metadata = KMPKeyboard + public typealias Package = KeyboardKeymanPackage + // Details what properties are coded and decoded re: serialization. enum CodingKeys: String, CodingKey { case id + case packageID case name case lgCode = "languageID" // The original name of the property, which we maintain for serialization. case languageName @@ -24,6 +29,7 @@ public struct InstallableKeyboard: Codable, LanguageResource { } public private(set) var id: String + public private(set) var packageID: String? = nil public var name: String public private(set) var lgCode: String public var languageName: String @@ -33,7 +39,7 @@ public struct InstallableKeyboard: Codable, LanguageResource { public var oskFont: Font? public var isCustom: Bool - public static let sharingLink = "https://keyman.com/go/keyboard/%@/share" + public static let sharingLink = "\(KeymanHosts.KEYMAN_COM)/go/keyboard/%@/share" public var sharableURL: String? { get { @@ -51,10 +57,15 @@ public struct InstallableKeyboard: Codable, LanguageResource { return lgCode.lowercased() } - public var fullID: FullKeyboardID { + // Weird scheme due to https://stackoverflow.com/a/58774558. + public var typedFullID: FullKeyboardID { return FullKeyboardID(keyboardID: id, languageID: languageID) } + public var fullID: FullKeyboardID { + return typedFullID + } + public init(id: String, name: String, languageID: String, @@ -86,4 +97,41 @@ public struct InstallableKeyboard: Codable, LanguageResource { self.oskFont = keyboard.oskFont self.isCustom = isCustom } + + internal init?(from metadata: KMPKeyboard, packageID: String, lgCode: String) { + self.id = metadata.id + self.name = metadata.name + self.lgCode = lgCode + + let languageMatches = metadata.languages.compactMap { return $0.languageId == lgCode ? $0.name : nil } + guard languageMatches.count == 1 else { + return nil + } + + self.languageName = languageMatches[0] + self.version = metadata.version + self.isRTL = metadata.isRTL + self.font = metadata.displayFont + self.oskFont = metadata.oskFont + self.packageID = packageID + self.isCustom = false + } + + public var fonts: [Font] { + var fonts: [Font] = [] + + if let displayFont = self.font { + fonts.append(displayFont) + } + + if let oskFont = self.oskFont { + fonts.append(oskFont) + } + + return fonts + } + + public var sourceFilename: String { + return "\(id).js" + } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/InstallableLexicalModel.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/InstallableLexicalModel.swift index 92615c763510ba464eb15c046dd2f6f7560fadf7..cd6f3736367a85b98abb6992bb5dcb55878f8952 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/InstallableLexicalModel.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Model/InstallableLexicalModel.swift @@ -13,10 +13,14 @@ struct InstallableConstants { } /// Mainly differs from the API `LexicalModel` by having an associated language. -public struct InstallableLexicalModel: Codable, LanguageResource { +public struct InstallableLexicalModel: Codable, KMPInitializableLanguageResource { + typealias Metadata = KMPLexicalModel + public typealias Package = LexicalModelKeymanPackage + // Details what properties are coded and decoded re: serialization. enum CodingKeys: String, CodingKey { case id + case packageID case name case lgCode = "languageID" // Redirects the old plain-property to something we can wrap with accessors. case version @@ -24,6 +28,7 @@ public struct InstallableLexicalModel: Codable, LanguageResource { } public private(set) var id: String + public internal(set) var packageID: String? = nil public var name: String private var lgCode: String public var version: String @@ -39,10 +44,15 @@ public struct InstallableLexicalModel: Codable, LanguageResource { return nil } } - - public var fullID: FullLexicalModelID { + + // Weird scheme due to https://stackoverflow.com/a/58774558 + public var typedFullID: FullLexicalModelID { return FullLexicalModelID(lexicalModelID: id, languageID: languageID) } + + public var fullID: FullLexicalModelID { + return typedFullID + } public init(id: String, name: String, @@ -63,5 +73,23 @@ public struct InstallableLexicalModel: Codable, LanguageResource { self.version = lexicalModel.version ?? InstallableConstants.defaultVersion self.isCustom = isCustom } + + internal init?(from metadata: KMPLexicalModel, packageID: String, lgCode: String) { + self.id = metadata.id + self.name = metadata.name + self.lgCode = lgCode + self.version = metadata.version! + self.isCustom = false + self.packageID = packageID + } + + // Lexical models don't bundle fonts. At least, not yet? + public var fonts: [Font] { + return [] + } + + public var sourceFilename: String { + return "\(id).model.js" + } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/KMPKeyboard.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/KMPKeyboard.swift deleted file mode 100644 index 4894e31210dbc04e4b665a3dc495c06d885b8316..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/KMPKeyboard.swift +++ /dev/null @@ -1,149 +0,0 @@ -// -// KMPKeyboard.swift -// KeymanEngine -// -// Created by Jacob Bullock on 2/16/18. -// Copyright © 2018 SIL International. All rights reserved. -// - -import Foundation - -public struct KMPLanguage { - public var name: String! - public var languageId: String! -} - -public class KMPKeyboard -{ - public var kmp: KeyboardKeymanPackage - - public var name: String? - public var keyboardId: String? - public var version: String! = "" - public var osk: String? - public var font: String? - public var languages: [KMPLanguage]! = [] - public var installableKeyboards: [InstallableKeyboard]! = [] - - init(kmp: KeyboardKeymanPackage) { - self.kmp = kmp - } - - public var displayFont: Font? { - if let f = font { - return Font(filename: f) - } - return nil - } - - public var oskFont: Font? { - if let f = osk { - return Font(filename: f) - } - return nil - } - - public var isValid: Bool { - return self.name != nil - && self.keyboardId != nil - && installableKeyboards.count > 0 - && self.languages.count > 0 - && FileManager.default.fileExists(atPath: kmp.sourceFolder.appendingPathComponent("\(keyboardId!).js").path) - } - - public func parse(json: [String:AnyObject], version: String) { - if let name = json["name"] as? String { - self.name = name - } - if let keyboardId = json["id"] as? String { - self.keyboardId = keyboardId - } - if let _version = json["version"] as? String { - self.version = _version - } else { - self.version = version - } - - if let languagesJson = json["languages"] as? [[String:String]] { - for languageJson in languagesJson { - if let languageName = languageJson["name"], - let languageId = languageJson["id"] { - self.languages.append(KMPLanguage(name: languageName, languageId: languageId)) - } - } - } - - self.osk = json["oskFont"] as? String - self.font = json["displayFont"] as? String - //true if the keyboard targets a right-to-left script. false if absent. - let isrtl: Bool = json["rtl"] as? Bool ?? false - - if(self.keyboardId != nil && self.name != nil) - { - var installableKeyboards : [InstallableKeyboard] = [] - - for language in self.languages { - let keyboard = InstallableKeyboard(id: keyboardId!, name: name!, - languageID: language.languageId, - languageName: language.name, - version: version, - isRTL: isrtl, - font: displayFont, - oskFont: oskFont, - isCustom: true) //update this based on adhoc vs api - - installableKeyboards.append( keyboard ) - } - - self.installableKeyboards = installableKeyboards - } - } - - public func install() throws -> Void { - if !isValid { - log.error("can't install invalid keyboard") - throw KMPError.invalidPackage - } - - do { - try FileManager.default.createDirectory(at: Storage.active.keyboardDir(forID: keyboardId!), - withIntermediateDirectories: true) - } catch { - log.error("Could not create dir for download: \(error)") - throw KMPError.fileSystem - } - - for keyboard in installableKeyboards { - var installableFiles: [[Any]] = [] - - let storedPath = Storage.active.keyboardURL(for: keyboard) - installableFiles.append( ["\(keyboardId!).js", storedPath] ) - - if let osk = self.osk { - let oskPath = Storage.active.fontURL(forKeyboardID: keyboardId!, filename: osk) - installableFiles.append( [osk, oskPath] ) - } - - if let font = self.font { - let displayPath = Storage.active.fontURL(forKeyboardID: keyboardId!, filename: font) - installableFiles.append( [font, displayPath] ) - } - - for item in installableFiles { - var filePath = self.kmp.sourceFolder - filePath.appendPathComponent(item[0] as! String) - do { - if(FileManager.default.fileExists(atPath: (item[1] as! URL).path)) { - try FileManager.default.removeItem(at: item[1] as! URL) - } - try FileManager.default.copyItem(at: filePath, - to: item[1] as! URL) - } catch { - log.error("Error saving the download: \(error)") - throw KMPError.copyFiles - } - } - Manager.shared.addKeyboard(keyboard) - } - } -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/KMPLexicalModel.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/KMPLexicalModel.swift deleted file mode 100644 index bc9a50d96ad00a99f13c93d611532361ab4c3688..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/KMPLexicalModel.swift +++ /dev/null @@ -1,112 +0,0 @@ -// -// KMPLexicalModel.swift -// KeymanEngine -// -// Created by Randy Boring on 3/12/19. -// Copyright © 2019 SIL International. All rights reserved. -// - -import Foundation - -//KMPLanguage in KMPKeyboard.swift - -public class KMPLexicalModel -{ - public var kmp: LexicalModelKeymanPackage - - public var name: String? - public var lexicalModelId: String? - public var version: String! = "" - public var languages: [KMPLanguage]! = [] - public var installableLexicalModels: [InstallableLexicalModel]! = [] - - init(kmp: LexicalModelKeymanPackage) { - self.kmp = kmp - } - - public var isValid: Bool { - return self.name != nil - && self.lexicalModelId != nil - && installableLexicalModels.count > 0 - && self.languages.count > 0 - && FileManager.default.fileExists(atPath: kmp.sourceFolder.appendingPathComponent("\(lexicalModelId!).model.js").path) - } - - public func parse(json: [String:AnyObject], version: String) { - if let name = json["name"] as? String { - self.name = name - } - if let lexicalModelId = json["id"] as? String { - self.lexicalModelId = lexicalModelId - } - if let _version = json["version"] as? String { - self.version = _version - } else { - self.version = version - } - - if let languagesJson = json["languages"] as? [[String:String]] { - for languageJson in languagesJson { - if let languageName = languageJson["name"], - let languageId = languageJson["id"] { - self.languages.append(KMPLanguage(name: languageName, languageId: languageId)) - } - } - } - - if(self.lexicalModelId != nil && self.name != nil) - { - var installableLexicalModels : [InstallableLexicalModel] = [] - - for language in self.languages { - let lexicalModel = InstallableLexicalModel(id: lexicalModelId!, name: name!, - languageID: language.languageId, -// languageName: language.name, - version: version, - isCustom: true) //update this based on adhoc vs api - - installableLexicalModels.append( lexicalModel ) - } - - self.installableLexicalModels = installableLexicalModels - } - } - - public func install() throws -> Void { - if !isValid { - log.error("can't install invalid lexical model") - throw KMPError.invalidPackage - } - - do { - try FileManager.default.createDirectory(at: Storage.active.lexicalModelDir(forID: lexicalModelId!), withIntermediateDirectories: true) - } catch { - log.error("Could not create dir for download: \(error)") - throw KMPError.fileSystem - } - - for lexicalModel in installableLexicalModels { - var installableFiles: [[Any]] = [] - - let storedPath = Storage.active.lexicalModelURL(for: lexicalModel) - installableFiles.append( ["\(lexicalModelId!).js", storedPath] ) - - for item in installableFiles { - var filePath = self.kmp.sourceFolder - filePath.appendPathComponent(item[0] as! String) - do { - if(FileManager.default.fileExists(atPath: (item[1] as! URL).path)) { - try FileManager.default.removeItem(at: item[1] as! URL) - } - try FileManager.default.copyItem(at: filePath, - to: item[1] as! URL) - } catch { - log.error("Error saving the download: \(error)") - throw KMPError.copyFiles - } - } - Manager.addLexicalModel(lexicalModel) - } - } -} - diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/KeyboardAPICall.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/KeyboardAPICall.swift deleted file mode 100644 index 9dc5eefcd5bb542b7cc6aa88d42d4adfe38475ca..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/KeyboardAPICall.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// KeyboardAPICall.swift -// KeymanEngine -// -// Created by Gabriel Wong on 2017-11-16. -// Copyright © 2017 SIL International. All rights reserved. -// - -import Foundation - -struct KeyboardAPICall: Codable { - let options: Options - let keyboard: Keyboard -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/KeyboardKeymanPackage.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/KeyboardKeymanPackage.swift deleted file mode 100644 index b608a4e153c7234193670335f9ac30782a41e9ab..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/KeyboardKeymanPackage.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// KeyboardKeymanPackage.swift -// KeymanEngine -// -// Created by Randy Boring on 3/14/19. -// Copyright © 2019 SIL International. All rights reserved. -// - -import Foundation - -public class KeyboardKeymanPackage : KeymanPackage -{ - private var keyboards: [KMPKeyboard]! - - public override func parse(json: [String:AnyObject], version: String) { - self.keyboards = [] - - if let packagedKeyboards = json["keyboards"] as? [[String:AnyObject]] { - for keyboardJson in packagedKeyboards { - let keyboard = KMPKeyboard.init(kmp: self) - keyboard.parse(json: keyboardJson, version: version) - - if(keyboard.isValid) { - keyboards.append(keyboard) - } - } - } - } - - public override func defaultInfoHtml() -> String { - var str = "Found Keyboards in package:
" - for keyboard in keyboards { - str += keyboard.keyboardId! + "
" - } - return str - } - - public override func isKeyboard() -> Bool { - return true - } - -} - diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/KeymanPackage.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/KeymanPackage.swift deleted file mode 100644 index 723506467494ddf0c52661270b7b55cc15440940..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/KeymanPackage.swift +++ /dev/null @@ -1,111 +0,0 @@ -// -// KeymanPackage.swift -// KeymanEngine -// -// Created by Jacob Bullock on 2/16/18. -// Copyright © 2018 SIL International. All rights reserved. -// - -import Foundation -import Zip - -public enum KMPError : String, Error { - case invalidPackage = "Invalid Keyman Package." - case fileSystem = "Unable to create directory structure in file system." - case copyFiles = "Unable to copy keyboard files to file system." -} - -public class KeymanPackage -{ - static private let kmpFile = "kmp.json" - public var sourceFolder: URL - - init(folder: URL) { - sourceFolder = folder - } - - // to be overridden by subclasses - public func isKeyboard() -> Bool { - return false - } - - // to be overridden by subclasses - public func parse(json: [String:AnyObject], version: String) { - return - } - - // to be overridden by subclasses - public func defaultInfoHtml() -> String { - return "base class!" - } - - public func infoHtml() -> String { - let welcomePath = self.sourceFolder.appendingPathComponent("welcome.htm") - - if FileManager.default.fileExists(atPath: welcomePath.path) { - if let html = try? String(contentsOfFile: welcomePath.path, encoding: String.Encoding.utf8) { - return html - } - } - - return defaultInfoHtml() - } - - static public func parse(_ folder: URL) -> KeymanPackage? { - do { - var path = folder - path.appendPathComponent(kmpFile) - if FileManager.default.fileExists(atPath: path.path) { - let data = try Data(contentsOf: path, options: .mappedIfSafe) - let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) - if let jsonResult = jsonResult as? [String:AnyObject] { - // The 'version' info has moved, and is no longer available in the original - // location for lexical models. Still present for keyboards, though! - var version: String = "" - if let info = jsonResult["info"] as? [String:AnyObject] { - if let versionBlock = info["version"] as? [String:AnyObject] { - version = versionBlock["description"] as? String ?? "" - } - } - - if let _ = jsonResult["keyboards"] as? [[String:AnyObject]] { - if let _ = jsonResult["lexicalModels"] as? [[String:AnyObject]] { - //TODO: rrb show error to user, for now, just log - log.error("error parsing keyman package: packages MUST NOT have both keyboards and lexical models") - return nil - } - let kmp = KeyboardKeymanPackage.init(folder: folder) - kmp.parse(json: jsonResult, version: version) - return kmp - } - else if let _ = jsonResult["lexicalModels"] as? [[String:AnyObject]] { - let kmm = LexicalModelKeymanPackage.init(folder: folder) - kmm.parse(json: jsonResult, version: version) - return kmm - } - } - } - } catch { - log.error("error parsing keyman package: \(error)") - } - - return nil - } - - static public func extract(fileUrl: URL, destination: URL, complete: @escaping (KeymanPackage?) -> Void) throws { - try unzipFile(fileUrl: fileUrl, destination: destination) { - complete(KeymanPackage.parse(destination)) - } - } - - static public func unzipFile(fileUrl: URL, destination: URL, complete: @escaping () -> Void) throws { - try Zip.unzipFile(fileUrl, destination: destination, overwrite: true, - password: nil, - progress: { (progress) -> () in - //TODO: add timeout - if(progress == 1.0) { - complete() - } - }) - } -} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/Language.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/Language.swift index d4b9c07446cf27db25977c651a0132c9831a53a0..0758bb2d5f4ceec464e025b4a4f47391bcf5ea97 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/Language.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Model/Language.swift @@ -27,4 +27,23 @@ public struct Language: Codable { /// Font for the OSK. public let oskFont: Font? + + init(from kmpLanguage: KMPLanguage) { + self.name = kmpLanguage.name + self.id = kmpLanguage.languageId + + keyboards = nil + lexicalModels = nil + font = nil + oskFont = nil + } + + init(name: String, id: String, keyboards: [Keyboard]?, lexicalModels: [LexicalModel]?, font: Font?, oskFont: Font?) { + self.name = name + self.id = id + self.keyboards = keyboards + self.lexicalModels = lexicalModels + self.font = font + self.oskFont = oskFont + } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/LanguageResource.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/LanguageResource.swift index b0748da0dfd8348156331ecf750a2bcd3cfc0b1f..9df571eb0a6a8f2246e570b7c101471a32465c82 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/LanguageResource.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Model/LanguageResource.swift @@ -8,15 +8,93 @@ import Foundation -public enum LanguageResourceType { - case keyboard, lexicalModel +public enum LanguageResourceType: String, Codable { + case keyboard + case lexicalModel } -public protocol LanguageResource { +// Subclasses must implement Equatable; Swift doesn't like it directly on the root protocol. +public protocol AnyLanguageResourceFullID { var id: String { get } var languageID: String { get } + var type: LanguageResourceType { get } + + func matches(_ other: AnyLanguageResourceFullID, requireLanguageMatch: Bool) -> Bool +} + +extension AnyLanguageResourceFullID { + // For matching when we're not sure if the underlying types actually match. + public func matches(_ other: AnyLanguageResourceFullID, requireLanguageMatch: Bool = true) -> Bool { + if requireLanguageMatch { + return id == other.id && type == other.type && languageID == other.languageID + } else { + return id == other.id && type == other.type + } + } +} + +// Equatable only really makes sense when the types are identical. +extension AnyLanguageResourceFullID where Self: Equatable { + public static func ==(lhs: Self, rhs: Self) -> Bool { + return lhs.id == rhs.id && lhs.languageID == rhs.languageID && lhs.type == rhs.type + } +} + +extension AnyLanguageResourceFullID { + var description: String { + return "{\(type): {id = \(id), languageID=\(languageID)}}" + } +} + +public protocol LanguageResourceFullID: AnyLanguageResourceFullID { + associatedtype Resource: LanguageResource where Resource.FullID == Self +} + +// Alas, 'associatedtype' stuff isn't exactly generic, and it's impossible to wildcard. +// So, this supports Swift's "type erasure" pattern, acting as a "wildcarded" +// LanguageResource that doesn't care about the specific associatedtype(s) that +// specific LanguageResources use. +public protocol AnyLanguageResource { + var id: String { get } + var name: String { get } + var languageID: String { get } + // Was not always tracked within KeymanEngine - is optional for legacy reasons. + var packageID: String? { get } + var packageKey: KeymanPackage.Key { get } + var fullID: AnyLanguageResourceFullID { get } var version: String { get } // Used for generating QR codes. var sharableURL: String? { get } + + // Used during resource installation + var fonts: [Font] { get } + var sourceFilename: String { get } +} + +extension AnyLanguageResource { + public var packageKey: KeymanPackage.Key { + return KeymanPackage.Key(forResource: self) + } +} + +// Necessary due to Swift details 'documented' at +// https://stackoverflow.com/questions/42561685/why-cant-a-get-only-property-requirement-in-a-protocol-be-satisfied-by-a-proper +public protocol LanguageResource: AnyLanguageResource { + associatedtype FullID: LanguageResourceFullID where FullID: Equatable, FullID.Resource == Self + associatedtype Package: KeymanPackage + var typedFullID: FullID { get } +} + +extension LanguageResource { + // Thanks to https://stackoverflow.com/a/58774558 (on same thread mentioned above) + // for this approach. + public var fullID: AnyLanguageResourceFullID { + return typedFullID as AnyLanguageResourceFullID + } +} + +internal protocol KMPInitializableLanguageResource: LanguageResource { + associatedtype Metadata: KMPResource where Metadata.LanguageResourceType == Self + init?(from metadata: Metadata, packageID: String, lgCode: String) } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/LexicalModelKeymanPackage.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/LexicalModelKeymanPackage.swift deleted file mode 100644 index 97ed0887e6c2a5650b84b214dad529d53c3298f0..0000000000000000000000000000000000000000 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/LexicalModelKeymanPackage.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// LexicalModelKeymanPackage.swift -// KeymanEngine -// -// Created by Randy Boring on 3/4/19. -// Copyright © 2019 SIL International. All rights reserved. -// - -import Foundation - -public class LexicalModelKeymanPackage : KeymanPackage { - public var models : [KMPLexicalModel]! - - public override func defaultInfoHtml() -> String { - let count = models.count - var str = "Found "+(count > 1 ? "\(count) dictionaries" : "dictionary")+" in package:
" - for model in models { - str += model.lexicalModelId! + "
" - } - return str - } - - // may be called parse() - // returns a dictionary mapping language ID to lexical model ID - override public func parse(json: [String:AnyObject], version: String) { - self.models = [] - - if let packagedModels = json["lexicalModels"] as? [[String:AnyObject]] { - for modelJson in packagedModels { - let model = KMPLexicalModel.init(kmp: self) - model.parse(json: modelJson, version: version) - - if(model.isValid) { - models.append(model) - } - } - } - } - -} - diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Model/Version.swift b/ios/engine/KMEI/KeymanEngine/Classes/Model/Version.swift index 982cefd5ea12913c3539cfef20f19f5ee1ad8625..31ceeb77c72ac4e3332b27378ebb2b067c3a0461 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Model/Version.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Model/Version.swift @@ -10,8 +10,14 @@ import Foundation /// Dotted-decimal version. public class Version: NSObject, Comparable { + public enum Tier: String { + case alpha + case beta + case stable + } + public static let fallback = Version("1.0")! - public static let latestFeature = Version("13.0.65")! + public static let latestFeature = packageBasedFileReorg public static var current: Version { let engineInfo = Bundle(for: Manager.self).infoDictionary @@ -33,10 +39,14 @@ public class Version: NSObject, Comparable { public static let fileBrowserImplemented = Version("13.0")! public static let defaultsNeedBackup = Version("13.0.65")! + // A major shift in where resources are installed occurred during + // the 14.0 alpha. + public static let packageBasedFileReorg = Version("14.0")! + private let components: [Int] public let plainString: String public let fullString: String - public let tier: String? + public let tier: Tier? public init?(_ string: String) { let tagComponents = string.components(separatedBy: "-") @@ -55,11 +65,11 @@ public class Version: NSObject, Comparable { if tagComponents.count > 1 { switch tagComponents[1] { case "alpha": - fallthrough + tier = .alpha case "beta": - fallthrough + tier = .beta case "stable": - tier = tagComponents[1] + tier = .stable default: tier = nil } @@ -71,7 +81,7 @@ public class Version: NSObject, Comparable { self.components = components } - public init?(_ components: [Int], tier: String? = nil) { + public init?(_ components: [Int], tier: Tier? = nil) { if components.count == 0 { return nil } @@ -120,7 +130,25 @@ public class Version: NSObject, Comparable { * (For example, 12.3.45 beta is considered equal to 12.3.45 stable.) */ public static func ==(lhs: Version, rhs: Version) -> Bool { - return lhs.components == rhs.components + var left = lhs.components + while(left.last == 0 && left.count > 0) { + left.removeLast() + } + + var right = rhs.components + while(right.last == 0 && right.count > 0) { + right.removeLast() + } + + return left.elementsEqual(right) + } + + public override func isEqual(_ object: Any?) -> Bool { + if let object = object as? Version { + return self == object + } else { + return false + } } // For nice logging output & debugger visibility. diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Notification/Notifications.swift b/ios/engine/KMEI/KeymanEngine/Classes/Notification/Notifications.swift index fd07cc19495c360f203324ea00f11a6b69232c07..b1076d3e2d574f1163a7b58501ba1f9ffcb4b45d 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Notification/Notifications.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Notification/Notifications.swift @@ -8,24 +8,38 @@ import Foundation +@available(*, deprecated, message: "Download notifications are now package-based. Use `PackageDownloadStartedNotification` instead.") public typealias KeyboardDownloadStartedNotification = [InstallableKeyboard] +@available(*, deprecated, message: "Download notifications are now package-based. Use `PackageDownloadCompletedNotification` instead.") public typealias KeyboardDownloadCompletedNotification = [InstallableKeyboard] +@available(*, deprecated, message: "Download notifications are now package-based. Use `PackageDownloadFailedNotification` instead.") public struct KeyboardDownloadFailedNotification { public let keyboards: [InstallableKeyboard] public let error: Error } + +@available(*, deprecated, message: "Download notifications are now package-based. Use `PackageDownloadStartedNotification` instead.") public typealias LexicalModelDownloadStartedNotification = [InstallableLexicalModel] +@available(*, deprecated, message: "Download notifications are now package-based. Use `PackageDownloadCompletedNotification` instead.") public typealias LexicalModelDownloadCompletedNotification = [InstallableLexicalModel] +@available(*, deprecated, message: "Download notifications are now package-based. Use `PackageDownloadFailedNotification` instead.") public struct LexicalModelDownloadFailedNotification { public let lmOrLanguageID: String public let error: Error } -public typealias BatchUpdateStartedNotification = [LanguageResource] + +public typealias PackageDownloadStartedNotification = KeymanPackage.Key +public typealias PackageDownloadCompletedNotification = KeymanPackage +public struct PackageDownloadFailedNotification { + public let packageKey: KeymanPackage.Key? + public let error: Error +} + +public typealias BatchUpdateStartedNotification = [AnyLanguageResource] public struct BatchUpdateCompletedNotification { - public let successes: [[LanguageResource]] - public let failures: [[LanguageResource]] - public let errors: [Error] + public let successes: [KeymanPackage.Key] + public let failures: [(KeymanPackage.Key, Error)] } public typealias KeyboardLoadedNotification = InstallableKeyboard @@ -41,10 +55,17 @@ public typealias LexicalModelRemovedNotification = InstallableLexicalModel public typealias LexicalModelPickerDismissedNotification = Void public struct Notifications { + public static let packageDownloadStarted = NotificationName("KeymanPackageDownloadStarted") + public static let packageDownloadCompleted = NotificationName("KeymanPackageDownloadCompleted") + public static let packageDownloadFailed = NotificationName("KeymanPackageDownloadFailed") + + @available(swift, deprecated: 0.1, obsoleted: 0.1, message: "Download notifications are now package-based. Use `packageDownloadStarted` instead.", renamed: "packageDownloadStarted") public static let keyboardDownloadStarted = NotificationName("KeymanKeyboardDownloadStarted") + @available(swift, deprecated: 0.1, obsoleted: 0.1, message: "Download notifications are now package-based. Use `packageDownloadCompleted` instead.", renamed: "packageDownloadCompleted") public static let keyboardDownloadCompleted = NotificationName("KeymanKeyboardDownloadCompleted") + @available(swift, deprecated: 0.1, obsoleted: 0.1, message: "Download notifications are now package-based. Use `packageDownloadFailed` instead.", renamed: "packageDownloadFailed") public static let keyboardDownloadFailed = NotificationName("KeymanKeyboardDownloadFailed") @@ -58,10 +79,13 @@ public struct Notifications { public static let keyboardPickerDismissed = NotificationName("KeymanKeyboardPickerDismissed") + @available(swift, deprecated: 0.1, obsoleted: 0.1, message: "Download notifications are now package-based. Use `packageDownloadStarted` instead.", renamed: "packageDownloadStarted") public static let lexicalModelDownloadStarted = NotificationName("KeymanLexicalModelDownloadStarted") + @available(swift, deprecated: 0.1, obsoleted: 0.1, message: "Download notifications are now package-based. Use `packageDownloadCompleted` instead.", renamed: "packageDownloadCompleted") public static let lexicalModelDownloadCompleted = NotificationName("KeymanLexicalModelDownloadCompleted") + @available(swift, deprecated: 0.1, obsoleted: 0.1, message: "Download notifications are now package-based. Use `packageDownloadFailed` instead.", renamed: "packageDownloadFailed") public static let lexicalModelDownloadFailed = NotificationName("KeymanLexicalModelDownloadFailed") diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Obsoletions.swift b/ios/engine/KMEI/KeymanEngine/Classes/Obsoletions.swift new file mode 100644 index 0000000000000000000000000000000000000000..658e96938ed1a7b0f8ed5acf2e04e8021c772505 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Obsoletions.swift @@ -0,0 +1,36 @@ +// +// Obsoletions.swift +// KeymanEngine +// +// Created by Joshua Horton on 7/24/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +// Obsoleted during development of Keyman 14.0 alpha. + +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "APIKeyboardRepository and associated types have been obsoleted in favor of keyboard search and package-oriented queries.") +public enum APIKeyboardFetchError: Error { } + +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "APIKeyboardRepository and associated types have been obsoleted in favor of keyboard search and package-oriented queries. If necessary, queries may be built against our api.keyman.com/search endpoint as documented at https://help.keyman.com/developer/cloud/search/1.0/") +public class APIKeyboardRepository { } + +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "APIKeyboardRepository and associated types have been obsoleted in favor of keyboard search and package-oriented queries.") +public protocol KeyboardRepository: class { } + +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "APIKeyboardRepository and associated types have been obsoleted in favor of keyboard search and package-oriented queries.") +public protocol KeyboardRepositoryDelegate: class { } + +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "APILexicalModelRepository and associated types have been obsoleted by `Queries.LexicalModel` and its `fetch` variants.") +public protocol LexicalModelRepository { } + +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "APILexicalModelRepository and associated types have been obsoleted by `Queries.LexicalModel` and its `fetch` variants.") +public enum APILexicalModelFetchError: Error { } + +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "APILexicalModelRepository and associated types have been obsoleted by `Queries.LexicalModel` and its `fetch` variants.") +public class APILexicalModelRepository { } + +@available(swift, deprecated: 0.1, obsoleted: 0.1, message: "APILexicalModelRepository and associated types have been obsoleted by `Queries.LexicalModel` and its `fetch` variants.") +public protocol LexicalModelRepositoryDelegate: class { } + diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries+LexicalModel.swift b/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries+LexicalModel.swift new file mode 100644 index 0000000000000000000000000000000000000000..df9ae64f59628035d6e5eb6621667db6bf75903c --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries+LexicalModel.swift @@ -0,0 +1,96 @@ +// +// Queries+LexicalModel.swift +// KeymanEngine +// +// Created by Joshua Horton on 7/8/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +extension Queries { + public class LexicalModel { + public struct Result: Decodable { + let id: String + let name: String + let version: String + let languages: [String] + let packageFilename: String + let description: String + let minKeymanVersion: String + + enum CodingKeys: String, CodingKey { + case id + case name + case version + case languages + case packageFilename + case minKeymanVersion + case description + } + + var models: [InstallableLexicalModel] { + return languages.map { modelFor(languageID: $0)! } + } + + func modelFor(languageID: String) -> InstallableLexicalModel? { + if languages.contains(languageID) { + return InstallableLexicalModel(id: id, name: name, languageID: languageID, version: version, isCustom: false) + } else { + return nil + } + } + } + + private static let MODEL_ENDPOINT = URLComponents(string: "\(KeymanHosts.API_KEYMAN_COM)/model")! + + public static func fetch(forLanguageCode bcp47: String, + fetchCompletion: @escaping JSONQueryCompletionBlock<[Result]>) { + fetch(forLanguageCode: bcp47, withSession: URLSession.shared, fetchCompletion: fetchCompletion) + } + + internal static func fetch(forLanguageCode bcp47: String, + withSession session: URLSession, + fetchCompletion: @escaping JSONQueryCompletionBlock<[Result]>) { + // Step 1: build the query + var urlComponents = MODEL_ENDPOINT + + urlComponents.queryItems = [URLQueryItem(name: "q", value: "bcp47:\(bcp47)")] + log.info("Querying package versions through API endpoint: \(urlComponents.url!)") + + // Step 2: configure the completion closure. + let completionClosure = Queries.jsonDataTaskCompletionAdapter(resultType: [Result].self, completionBlock: fetchCompletion) + + // Step 3: run the actual query, letting the prepared completion closure take care of the rest. + let task = session.dataTask(with: urlComponents.url!, completionHandler: completionClosure) + task.resume() + } + + /** + * Returns an array of package keys containing models that support the specified language. + */ + public static func fetchModels(forLanguageCode bcp47: String, + fetchCompletion: @escaping ([(InstallableLexicalModel, URL)]?, Error?) -> Void) { + fetchModels(forLanguageCode: bcp47, withSession: URLSession.shared, fetchCompletion: fetchCompletion) + } + + internal static func fetchModels(forLanguageCode bcp47: String, + withSession session: URLSession, + fetchCompletion: @escaping ([(InstallableLexicalModel, URL)]?, Error?) -> Void) { + Queries.LexicalModel.fetch(forLanguageCode: bcp47, withSession: session) { result, error in + if let error = error { + fetchCompletion(nil, error) + return + } + + guard let result = result, result.count > 0 else { + fetchCompletion([], nil) + return + } + + // There are valid packages for the language code - send off the report! + fetchCompletion(result.map { ($0.modelFor(languageID: bcp47)!, URL.init(string: $0.packageFilename)!) }, nil) + } + } + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries+PackageVersion.swift b/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries+PackageVersion.swift new file mode 100644 index 0000000000000000000000000000000000000000..f8d65c74b89763888da280a882894ca48ca2e33b --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries+PackageVersion.swift @@ -0,0 +1,129 @@ +// +// Queries+PackageVersion.swift +// KeymanEngine +// +// Created by Joshua Horton on 6/25/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +extension Queries { + // Kept internal; the query is 'publicly exposed' through KeymanPackage and ResourceFileManager. + class PackageVersion { + class ResultComponent {} + + class ResultEntry: ResultComponent, Decodable { + let version: String + let packageURL: String + + enum CodingKeys: String, CodingKey { + case version + case packageURL = "kmp" + } + } + + class ResultError: ResultComponent, Decodable { + let error: String + + enum CodingKeys: String, CodingKey { + case error + } + } + + enum Entry { + case success(ResultEntry) + case failure(ResultError?) + } + + struct Result: Decodable { + let keyboards: [String : ResultComponent]? + let models: [String : ResultComponent]? + + enum CodingKeys: String, CodingKey { + case keyboards + case models + } + + init(from decoder: Decoder) throws { + let rootValues = try decoder.container(keyedBy: CodingKeys.self) + + func dictionaryReducer(container: KeyedDecodingContainer, category: String) -> ([String: ResultComponent], Queries.IDCodingKey) throws -> [String: ResultComponent] { + return { (dict, id) -> [String: ResultComponent] in + var dict = dict + if let entry = try? container.decode(ResultEntry.self, forKey: id) { + dict[id.stringValue] = entry + } else if let error = try? container.decode(ResultError.self, forKey: id) { + dict[id.stringValue] = error + } else { + throw FetchError.decodingError(category, id.stringValue) + } + return dict + } + } + + if rootValues.contains(.keyboards) { + let keyboardValueSet = try rootValues.nestedContainer(keyedBy: IDCodingKey.self, forKey: .keyboards) + keyboards = try keyboardValueSet.allKeys.reduce([String: ResultComponent](), dictionaryReducer(container: keyboardValueSet, category: "keyboard")) + } else { + keyboards = nil + } + + if rootValues.contains(.models) { + let modelValueSet = try rootValues.nestedContainer(keyedBy: IDCodingKey.self, forKey: .models) + models = try modelValueSet.allKeys.reduce([String: ResultComponent](), dictionaryReducer(container: modelValueSet, category: "lexical model")) + } else { + models = nil + } + } + + func entryFor(_ key: KeymanPackage.Key) -> Entry { + var result: ResultComponent? + + switch(key.type) { + case .keyboard: + result = keyboards?[key.id] + case .lexicalModel: + result = models?[key.id] + } + + if let entry = result as? ResultEntry { + return .success(entry) + } else { + return .failure(result as? ResultError) + } + } + } + + private static let PACKAGE_VERSION_ENDPOINT = URLComponents(string: "\(KeymanHosts.API_KEYMAN_COM)/package-version")! + + public static func fetch(for packageKeys: [KeymanPackage.Key], + withSession session: URLSession = .shared, + fetchCompletion: @escaping JSONQueryCompletionBlock) { + // Step 1: build the query + var urlComponents = PACKAGE_VERSION_ENDPOINT + + let queryItems: [URLQueryItem] = packageKeys.map { key in + var resourceField: String + switch(key.type) { + case .keyboard: + resourceField = "keyboard" + case .lexicalModel: + resourceField = "model" + } + + return URLQueryItem(name: resourceField, value: key.id) + } + + urlComponents.queryItems = queryItems + [URLQueryItem(name: "platform", value: "ios")] + log.info("Querying package versions through API endpoint: \(urlComponents.url!)") + + // Step 2: configure the completion closure. + let completionClosure = Queries.jsonDataTaskCompletionAdapter(resultType: Result.self, completionBlock: fetchCompletion) + + // Step 3: run the actual query, letting the prepared completion closure take care of the rest. + let task = session.dataTask(with: urlComponents.url!, completionHandler: completionClosure) + task.resume() + } + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries.swift b/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries.swift new file mode 100644 index 0000000000000000000000000000000000000000..e48bc551f384e173124b64814bf54fc8f8ea5b9a --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries.swift @@ -0,0 +1,101 @@ +// +// Queries.swift +// KeymanEngine +// +// Created by Joshua Horton on 6/25/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +// The core `Queries` definition provides common utility methods, handlers, etc across our API queries. +public class Queries { + public enum FetchError: LocalizedError { + case networkError(Error) + case noData + case parsingError(Error) + case decodingError(String, String) + + var localizedDescription: String { + switch self { + case .noData: + return engineBundle.localizedString(forKey: "error-query-no-data", value: nil, table: nil) + case .networkError(_): + return engineBundle.localizedString(forKey: "error-query-general", value: nil, table: nil) + case .parsingError(_): + return engineBundle.localizedString(forKey: "error-query-decoding", value: nil, table: nil) + case .decodingError(_, _): + return engineBundle.localizedString(forKey: "error-query-decoding", value: nil, table: nil) + } + } + } + + public enum ResultError: LocalizedError { + case unqueried + + var localizedDescription: String { + switch self { + case .unqueried: + return "Query was not run against specified parameter" + } + } + } + + struct IDCodingKey: CodingKey { + /* Required by CodingKey, though we don't particularly need these */ + public var intValue: Int? + + public init?(intValue: Int) { + self.init(stringValue: "\(intValue)") + self.intValue = intValue + } + /* End section */ + + var stringValue: String + + init?(stringValue: String) { + self.stringValue = stringValue + } + } + + public typealias JSONQueryCompletionBlock = (_: T?, _: Queries.FetchError?) -> Void + typealias DataTaskCompletionBlock = (_: Data?, _: URLResponse?, _: Error?) -> Void + + /** + * Returns a closure that wraps closures expecting a decodable type, + * performing standard error checking and decoding the query's results + * on behalf of the wrapped closure. + * + * Returns either the decoded result when successful or the error that + * occurred when attempting to run the query. + */ + internal static func jsonDataTaskCompletionAdapter(resultType: T.Type, completionBlock: @escaping JSONQueryCompletionBlock) -> DataTaskCompletionBlock { + return { data, response, baseError in + guard baseError == nil else { + DispatchQueue.main.async { completionBlock(nil, .networkError(baseError!)) } + return + } + + guard let data = data else { + DispatchQueue.main.async { completionBlock(nil, .noData) } + return + } + + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + + do { + let result = try decoder.decode(resultType, from: data) + DispatchQueue.main.async { completionBlock(result, nil) } + } catch { + DispatchQueue.main.async { + if let error = error as? FetchError { + completionBlock(nil, error) + } else { + completionBlock(nil, .parsingError(error)) + } + } + } + } + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/AssociatingPackageInstaller.swift b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/AssociatingPackageInstaller.swift new file mode 100644 index 0000000000000000000000000000000000000000..117c8e403bd1294e9f340da954cd2a7e3179b987 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/AssociatingPackageInstaller.swift @@ -0,0 +1,417 @@ +// +// AssociatingPackageInstaller.swift +// KeymanEngine +// +// Created by Joshua Horton on 8/5/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +/** + * Given a `KeymanPackage` that KeymanEngine knows how to install, this class facilitates language selection as part of the + * package installation process. + * + * "Associations" may also be specified to look up 'associated' resources for the selected language codes and have them install alongside + * the base package. For example, installing the `sil_euro_latin` keyboard for `en` (English) with the `.lexicalModels` association + * will query for `en` models and install them as well as the `sil_euro_latin` package. + * + * At the time of writing, this will return the `nrc.en.mtnt` model and will install it for use with `en` + * before indicating that overall package installation is complete. + */ +public class AssociatingPackageInstaller> where Resource.Package == Package { + + // The second parameter should be used to report on installation success on a per-package basis. + public typealias AssociationInstaller = (LanguagePickAssociator.AssociationMap, + @escaping (KeymanPackage.Key, PackageInstallResult) -> Void) + -> Void + + public typealias AssociatorBuilder = (AssociatingPackageInstaller, + LanguagePickAssociator.AssociationReceiver) + -> LanguagePickAssociator + + /** + * Defines behaviors for finding and installing resources associated with the set of languages selected for installation. + */ + public enum Associator { + /** + * Facilitates installing lexical models for the languages being installed. + */ + case lexicalModels + + /** + * Designed to allow framework users to specify their own associations if desired. + */ + case custom(AssociatorBuilder, AssociationInstaller) + + internal func instance(for installer: AssociatingPackageInstaller, + withSession session: URLSession, + withReceiver receiver: @escaping LanguagePickAssociator.AssociationReceiver) + -> LanguagePickAssociator { + switch self { + case .lexicalModels: + return LanguagePickAssociator(searchWith: LanguagePickAssociator.constructLexicalModelSearcher(session: session), + progressClosure: receiver) + case .custom(let constructor, _): + return constructor(installer, receiver) + } + } + + internal func installer(downloadManager: ResourceDownloadManager) -> AssociationInstaller { + switch self { + case .lexicalModels: + return { associatedLexicalModelMap, completionClosure in + associatedLexicalModelMap.forEach { packageKey, association in + let url = association.url + let lgCodes = association.languageCodes + + downloadManager.downloadPackage(withKey: packageKey, from: url) { + (package: LexicalModelKeymanPackage?, error: Error?) in + guard error == nil, let package = package else { + completionClosure(packageKey, .error(error ?? KeymanError.unknown)) + return + } + + let associatedResources = lgCodes.flatMap { package.installableResources(forLanguage: $0) } as! [InstallableLexicalModel] + let associatedResourceIDs = associatedResources.map { $0.typedFullID } + + do { + try ResourceFileManager.shared.install(resourcesWithIDs: associatedResourceIDs, from: package) + completionClosure(packageKey, .complete) + } catch { + completionClosure(packageKey, .error(error)) + } + } + } + } + case .custom(_, let closure): + return closure + } + } + } + + public enum PackageInstallResult { + case error(Error) + case complete + } + + public enum Progress { + case cancelled + case starting // signals that language picks are finalized, so progress reports will now begin. + case inProgress + case complete + } + + public typealias ProgressReceiver = (Progress) -> Void + + typealias AssociationInstallMap = [KeymanPackage.Key: PackageInstallResult] + + private class ClosureShared { + // Synchronization + let queryGroup = DispatchGroup() + let installGroup = DispatchGroup() + let progressQueue = DispatchQueue(label: "com.keyman.associatingPackageInstaller") + + // Specifications needed across multiple threads. + let associationSpecs: [Associator] + var associationInstallers: [Int: AssociationInstaller] = [:] + + // Holds data needed for progress tracking. + var pickingCompleted: Bool = false + var associationQueryProgress: [Int: LanguagePickAssociator.Progress] = [:] + var installProgressMap: [KeymanPackage.Key: PackageInstallResult?] = [:] + + let progressCallback: ProgressReceiver + let downloadManager: ResourceDownloadManager + + var isCancelled = false + + init(with associationSpecs: [Associator], downloadManager: ResourceDownloadManager, receiver: @escaping ProgressReceiver) { + self.associationSpecs = associationSpecs + self.downloadManager = downloadManager + self.progressCallback = receiver + } + + // Since progress info is stored here, it makes the most sense to track progress-related + // methods here too. + + internal var reportsProgress: Bool { + return !isCancelled && pickingCompleted + } + + /** + * Computes the initial level of progress made toward the overall installation at the time that language selections were + * finalized. + */ + internal func initializeProgress() { + self.progressCallback(.starting) + } + + /** + * Generates data useful for reporting about the installation's overall progress. + */ + internal func reportProgress(complete: Bool = false) { + if reportsProgress { + if complete { + progressCallback(.complete) + } else { + //progressCallback(.inProgress) + } + } + } + + internal func reportCancelled() { + progressCallback(.cancelled) + } + } + + private let closureShared: ClosureShared + + let package: Package + let defaultLgCode: String? + var associationQueriers: [LanguagePickAssociator]? + + /** + * Constructs an instance for installing the specified package alongside any detected packages containing specified types + * of associated resources for the languages that are selected for installation. + * + * - parameters: + * - package: An already-download package to install. Any language selection must choose languages supported by this package. + * - defaultLanguageCode: The BCP-47 code for the default language to select when prompting the user for languages. + * - withAssociators: A set of desired "language associations" to install alongside the package if they exist. + * Currently supports the following options: + * - `.lexicalModels`: intended for use with keyboard packages. Will query for and install lexical models for any + * picked languages as part of the installation process. + * - `.custom`: allows specifying custom language associations. + * - progressReceiver: This will _always_ be called, even should picking never start before the class is deinitialized. + * It will either receive `.cancelled` (exactly once) or a sequence like the following: + * - `.starting` (exactly once) + * - `.complete` (exactly once) + * + * In the future, `.inProgress` may be implemented; at that time, it will provide data for reporting installation progress and + * may be called multiple times between `.starting` and `.complete`. + */ + public convenience init(for package: Package, + defaultLanguageCode: String? = nil, + withAssociators associators: [Associator] = [], + progressReceiver: @escaping ProgressReceiver) { + self.init(for: package, + defaultLanguageCode: defaultLanguageCode, + downloadManager: ResourceDownloadManager.shared, + withAssociators: associators, + progressReceiver: progressReceiver) + } + + internal init(for package: Package, + defaultLanguageCode: String? = nil, + downloadManager: ResourceDownloadManager = ResourceDownloadManager.shared, + withAssociators associators: [Associator] = [], + progressReceiver: @escaping ProgressReceiver) { + self.package = package + self.defaultLgCode = defaultLanguageCode + + self.closureShared = ClosureShared(with: associators, downloadManager: downloadManager, receiver: progressReceiver) + } + + deinit { + // Ensure we send a 'cancel' signal IF this is a 'constructive cancellation'. + // That is, if no installs were triggered... even if picking never even started. + if !closureShared.pickingCompleted, self.associationQueriers != nil, !closureShared.isCancelled { + // Auto-dismiss any association queriers that might still be executing. + // Necessary for their closures to exit their DispatchGroups cleanly. + self.associationQueriers = nil + + // Now we may safely send an artificial 'cancel'. + let installClosure = coreInstallationClosure() + installClosure(nil) + } else if self.associationQueriers == nil { + // We never started the associators or a picker, so bypass all of that and directly + // report cancellation. + closureShared.reportCancelled() + } + } + + internal func constructAssociationPickers() { + // We instantiate this now, indicating that language selection has begun. + associationQueriers = [] + + // So, the for-loop below throws an error for this case. Yay, Swift weirdnesses. + if closureShared.associationSpecs.count == 0 { + return + } + + // Using a classical for-loop allows us to 'map' receivers (within their closures) to their associators. + for i in 0 ... closureShared.associationSpecs.count-1 { + let associationSpec = closureShared.associationSpecs[i] + + closureShared.queryGroup.enter() + let receiver: LanguagePickAssociator.AssociationReceiver = constructAssociationReceiver(specIndex: i) + + associationQueriers!.append(associationSpec.instance(for: self, + withSession: closureShared.downloadManager.session, + withReceiver: receiver)) + } + } + + private func constructAssociationReceiver(specIndex: Int) -> LanguagePickAssociator.AssociationReceiver { + let closureShared = self.closureShared + + return { status in + switch status { + case .cancelled: + // Do not trigger installation or even _start_ attempting installation. + // Do a simple, graceful exit. + closureShared.queryGroup.leave() + // TODO: + // case .inProgress(let queryCount, let associationsFound): + // break + case .complete(_, let associationMap): + // Assumption: .complete will only occur if 'picking' was not cancelled. + // We know this holds true for the current LanguagePickAssociation implementation. + let installer = closureShared.associationSpecs[specIndex].installer(downloadManager: closureShared.downloadManager) + closureShared.associationInstallers[specIndex] = installer + + // Since completions will be signaled once per package, + // we enter the install group once per package. + associationMap.forEach { _, _ in closureShared.installGroup.enter() } + closureShared.queryGroup.leave() + + installer(associationMap) { packageKey, result in + closureShared.progressQueue.async { + closureShared.installProgressMap[packageKey] = result + closureShared.reportProgress() + + // Last thing in this closure. + closureShared.installGroup.leave() + } + } + // Since we aren't yet directly handling case .inProgress. + default: + break + } + + closureShared.progressQueue.async { + closureShared.associationQueryProgress[specIndex] = status + + if case let .complete(_, associationMap) = status { + associationMap.forEach { (key, _) in + // Allows tracking install-completion progress. + closureShared.installProgressMap[key] = nil // indicates 'downloading'. + } + } + + closureShared.reportProgress() + } + } + } + + internal func initializeSynchronizationGroups() { + let closureShared = self.closureShared + closureShared.queryGroup.enter() + closureShared.installGroup.enter() + + // All queries must have returned in order for us to be sure all + // needed installations have occurrred. + closureShared.queryGroup.notify(queue: closureShared.progressQueue) { + closureShared.installGroup.leave() // ? + } + + closureShared.installGroup.notify(queue: DispatchQueue.main) { + // The final 'progress report' / completion signaller. + closureShared.reportProgress(complete: true) + } + } + + internal func coreInstallationClosure() -> ([Resource.FullID]?) -> Void { + // For use in closures called by other DispatchGroups. + let packageKey = self.package.key + let closureShared = self.closureShared + + // This closure should be triggered from UI, thus from the standard, main UI thread / DispatchGroup. + return { fullIDs in + guard let fullIDs = fullIDs else { + closureShared.isCancelled = true + closureShared.queryGroup.leave() + closureShared.reportCancelled() + + return + } + + closureShared.progressQueue.sync { + // Indicates a transition to 'installing' state. + closureShared.pickingCompleted = true + closureShared.installProgressMap[packageKey] = nil + closureShared.initializeProgress() + } + closureShared.installGroup.enter() // Enter the 'install' group before exiting the 'query' group, to be safe. + closureShared.queryGroup.leave() + + var result: PackageInstallResult + do { + try ResourceFileManager.shared.install(resourcesWithIDs: fullIDs, from: self.package) + result = .complete + } catch { + result = .error(error) + } + + closureShared.progressQueue.async { + closureShared.installProgressMap[packageKey] = result + closureShared.reportProgress() + } + + closureShared.installGroup.leave() + } + } + + /** + * Summons UI that allows the user to interactively select which languages are installed for this package, + * searching for specified associations in the background and adding them to the installation set. + * + * May only be called once during the lifetime of its instance and is mutually exclusive with `pickLanguages`, + * the programmatic alternative. + */ + public func promptForLanguages(inNavigationVC navVC: UINavigationController) { + guard self.associationQueriers == nil, !closureShared.pickingCompleted else { + fatalError("Invalid state - language picking has already been triggered.") + } + + initializeSynchronizationGroups() + constructAssociationPickers() + + let pickerPrompt = PackageInstallViewController(for: self.package, + defaultLanguageCode: defaultLgCode, + languageAssociators: associationQueriers!, + completionHandler: coreInstallationClosure()) + + navVC.pushViewController(pickerPrompt, animated: true) + } + + /** + * Allows programmatically selecting which languages are installed for this package. + * The specified associations will be used to find related packages and add them to the installation set. + * + * May only be called once during the lifetime of its instance and is mutually exclusive with `promptForLanguages`, + * the user-interactive alternative. + */ + public func pickLanguages(withCodes languageIDs: Set) { + guard self.associationQueriers == nil, !closureShared.pickingCompleted else { + fatalError("Invalid state - language picking has already been triggered.") + } + + initializeSynchronizationGroups() + constructAssociationPickers() + + let baseResources: [Resource] = languageIDs.flatMap { package.installables(forLanguage: $0) } + let baseFullIDs: [Resource.FullID] = baseResources.map { $0.typedFullID } + + self.associationQueriers?.forEach { associator in + associator.pickerInitialized() + associator.selectLanguages(languageIDs) + } + + let installClosure = coreInstallationClosure() + installClosure(baseFullIDs) + + self.associationQueriers?.forEach { $0.pickerFinalized() } + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/KeyboardSearchViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/KeyboardSearchViewController.swift new file mode 100644 index 0000000000000000000000000000000000000000..e5051721944ccf5598552223ef652062c686e95d --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/KeyboardSearchViewController.swift @@ -0,0 +1,196 @@ +// +// KeyboardSearchViewController.swift +// KeymanEngine +// +// Created by Joshua Horton on 7/21/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import UIKit +import WebKit + +/* + * Minor design notes: + * + * This class is designed for use as a 'library component' of KeymanEngine that apps may choose + * whether or not to utilize. It simply returns the specifications of any packages/resources + * to download, leaving control of their actual installation up to KeymanEngine's host app. + */ + +/** + * Loads a WebView to Keyman's online keyboard search. This WebView will intercept any package download links + * and return the specifications of such interceptions - the search results - to the instance's owner via a closure specified + * during initialization. + */ +public class KeyboardSearchViewController: UIViewController, WKNavigationDelegate { + public enum SearchDownloadResult { + case success(KeymanPackage, AnyLanguageResourceFullID) + case cancelled + case error(Error?) + } + + public enum SearchResult { + /** + * Indicates that the user cancelled the search. + */ + case cancelled + + /** + * Indicates that a package has been selected for download, but we don't know what language + * they wish to use it for. This case will never be specified for the lexical-model selection closure. + * + * Once a target language has been identified, call the third parameter's closure to start a search + * for associated lexical models (or to indicate that none should occur). Otherwise, the lexical model + * search closure provided to the keyboard search will never evaluate. + */ + case untagged(KeymanPackage.Key, URL) + + /** + * Indicates that a package has been selected for download and is already associated with a + * language tag. + */ + case tagged(KeymanPackage.Key, URL, FullID) + } + + // Useful documentation regarding certain implementation details: + // https://docs.google.com/document/d/1rhgMeJlCdXCi6ohPb_CuyZd0PZMoSzMqGpv1A8cMFHY/edit + + /** + * Parameters: + * 1. The unique package identifier for the selected package. If nil, the user 'cancelled' and intends for nothing to be installed. + * 2. The Keyman cloud URL from which that package may be downloaded. Will be nil if and only if the first parameter is nil. + * 3. The unique identifier for the resource WITHIN that package to install. Useful when a package's resource(s) support multiple languages. + */ + public typealias SelectionCompletedHandler = (SearchResult) -> Void + public typealias SearchDownloadHandler = (SearchDownloadResult) -> Void + + private var hasFinalized = false + private let keyboardSelectionClosure: SelectionCompletedHandler! + private let languageCode: String? + private let session: URLSession + + private static var ENDPOINT_ROOT: URL { + var baseURL = KeymanHosts.KEYMAN_COM + baseURL.appendPathComponent("go") + baseURL.appendPathComponent("ios") // platform + // API endpoint only supports major.minor, will break if `.build` is also present + baseURL.appendPathComponent(Version.current.majorMinor.description) + baseURL.appendPathComponent("download-keyboards") + + return baseURL + } + + public init(languageCode: String? = nil, + withSession session: URLSession = URLSession.shared, + keyboardSelectionBlock: @escaping SelectionCompletedHandler) { + self.languageCode = languageCode + self.session = session + self.keyboardSelectionClosure = keyboardSelectionBlock + super.init(nibName: nil, bundle: nil) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public override func loadView() { + let webView = WKWebView() + webView.navigationDelegate = self + if let languageCode = languageCode { + let baseURL = KeyboardSearchViewController.ENDPOINT_ROOT + let specificURL = URL.init(string: "\(baseURL)?q=l:id:\(languageCode)")! + webView.load(URLRequest(url: specificURL)) + } else { + webView.load(URLRequest(url: KeyboardSearchViewController.ENDPOINT_ROOT)) + } + + view = webView + } + + // Used to intercept download links. + public func webView(_ webView: WKWebView, + decidePolicyFor navigationAction: WKNavigationAction, + decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { + if navigationAction.navigationType == .linkActivated { + let link = navigationAction.request.url! + if let parsedLink = UniversalLinks.tryParseKeyboardInstallLink(link) { + decisionHandler(.cancel) + + // Notify our caller of the search results. + self.hasFinalized = true // Prevent popViewController from triggering cancellation events. + self.navigationController?.popViewController(animated: true) // Rewind UI + finalize(with: parsedLink) + return + } + } + + decisionHandler(.allow) + } + + override public func viewWillDisappear(_ animated: Bool) { + // If the view is being dismissed but no matching link has been intercepted... + if self.isMovingFromParent, !hasFinalized { + self.keyboardSelectionClosure(.cancelled) + } + } + + internal func finalize(with parsedLink: UniversalLinks.ParsedKeyboardInstallLink) { + let packageKey = KeymanPackage.Key(id: parsedLink.keyboard_id, type: .keyboard) + + // If we have a language ID AND do not yet have a model for it. + if let lang_id = parsedLink.lang_id { + let resourceKey = FullKeyboardID(keyboardID: parsedLink.keyboard_id, languageID: lang_id) + let kbdURL = ResourceDownloadManager.shared.defaultDownloadURL(forPackage: packageKey, andResource: resourceKey, asUpdate: false) + self.keyboardSelectionClosure(.tagged(packageKey, kbdURL, resourceKey)) + } else { + let kbdURL = ResourceDownloadManager.shared.defaultDownloadURL(forPackage: packageKey, asUpdate: false) + self.keyboardSelectionClosure(.untagged(packageKey, kbdURL)) + } + } + + public static func defaultDownloadClosure(downloadCompletionBlock: @escaping SearchDownloadHandler) -> SelectionCompletedHandler { + return defaultDownloadClosure(withDownloadManager: ResourceDownloadManager.shared, + downloadCompletionBlock: downloadCompletionBlock) + } + + // For unit testing. + internal static func defaultDownloadClosure(withDownloadManager downloadManager: ResourceDownloadManager, + downloadCompletionBlock: @escaping SearchDownloadHandler) -> SelectionCompletedHandler { + return { searchResult in + var packageKey: KeymanPackage.Key + var packageURL: URL + + switch searchResult { + case .cancelled: + downloadCompletionBlock(.cancelled) + return + case .untagged(let key, let url): + packageKey = key + packageURL = url + case .tagged(let key, let url, _): + packageKey = key + packageURL = url + } + + let downloadClosure: ResourceDownloadManager.CompletionHandler = { package, error in + guard let package = package, error == nil else { + downloadCompletionBlock(.error(error)) + return + } + + switch searchResult { + case .untagged(_, _): + let resourceKey = package.installables.first!.first!.fullID + downloadCompletionBlock(.success(package, resourceKey)) + case .tagged(_, _, let resourceKey): + downloadCompletionBlock(.success(package, resourceKey)) + default: + // Illegal state - we already checked this. + fatalError() + } + } + + downloadManager.downloadPackage(withKey: packageKey, from: packageURL, withNotifications: true, completionBlock: downloadClosure) + } + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/LanguagePickAssociator.swift b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/LanguagePickAssociator.swift new file mode 100644 index 0000000000000000000000000000000000000000..3944147fed9176546c87b17b3873e141cfd09bde --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/LanguagePickAssociator.swift @@ -0,0 +1,382 @@ +// +// LanguagePickAssociator.swift +// KeymanEngine +// +// Created by Joshua Horton on 8/3/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +/** + * This class is designed for use with the `PackageInstallViewController` or + * other language-picking UI classes. As languages are selected in a picker, instances of + * this class will use the provided `AssociationSearcher` to look up associated + * resources that are compatible. These searches will be run concurrently in order to + * reduce waiting time for end users. + * + * When the picker signals that language selection is complete, any detected associations + * will be returned through the instance's provided `AssociationReceiver`. + * It is then up to the `AssociationReceiver` to download and install these associations. + * + * A default `AssociationSearcher` for lexical model lookups is provided as + * `static let lexicalModelSearcher`. + */ +public class LanguagePickAssociator { + public enum Progress { + /** + * Indicates that the language-picking process was aborted. No further calls to the receiving AssociationReceiver will occur. + */ + case cancelled + + /** + * Indicates that a set of association queries has returned. Reports the number of completed queries followed by + * the number of detected associated packages found. + * + * For calculating a progress percent, note that the total number of queries + * may be found at `LanguagePickAssociator.languagesQueried`. + */ + case inProgress(Int, Int) + + /** + * Indicates that all generated association queries have returned. Reports the total number of queries that occurred, + * followed by a map of package keys to the corresponding URL and language codes to install from the package. + */ + case complete(Int, AssociationMap) + } + /** + * A callback that returns available packages corresponding to provided language codes. + * + * This callback may preemptively filter out unwanted associations if desired. One good example: + * not searching for associated resources when one of the appropriate type is already installed + * for the specified language code. + */ + public typealias AssociationSearcher = (Set, @escaping ([String: (KeymanPackage.Key, URL)?]) -> Void) -> Void + + /** + * Tracks the progress of the association process. See `LanguagePickAssociator.Progress` for more information. + * + * May be called multiple times, though a few guarantees exist: + * * Either `.cancelled` or `.complete` will be called exactly once, with the other never occurring, so long as `pickerInitialized` has been called. + * * When either occurs, it will be the final call to the `AssociationReceiver`. + */ + public typealias AssociationReceiver = (Progress) -> Void + + public typealias AssociationMap = [KeymanPackage.Key: Association] + + public struct Association { + public let url: URL + public let languageCodes: Set + } + + /** + * The default AssociationSearcher for lexical model lookups. + */ + public static let lexicalModelSearcher: AssociationSearcher = constructLexicalModelSearcher(session: URLSession.shared) + + internal static func constructLexicalModelSearcher(session: URLSession) -> AssociationSearcher { + return { lgCodes, completion in + // Sadly, we don't yet have an actual multi-language-code server-side model query yet. + // So, we have to sync up the results of this query first. + // + // Should we implement such a server-side query, this becomes markedly simpler. + let queueDispatch = DispatchGroup() + var modelMap: [String: (KeymanPackage.Key, URL)?] = [:] + + lgCodes.forEach { lgCode in + // First, filter out any language codes that already have an installed lexical model. + let alreadyInstalled = Storage.active.userDefaults.userLexicalModels?.contains(where: { $0.languageID == lgCode}) ?? false + + if(!alreadyInstalled) { + queueDispatch.enter() + Queries.LexicalModel.fetchModels(forLanguageCode: lgCode, + withSession: session) { models, error in + guard error == nil, let models = models, models.count > 0 else { + modelMap[lgCode] = nil + queueDispatch.leave() + return + } + + modelMap[lgCode] = (models[0].0.packageKey, models[0].1) + queueDispatch.leave() + } + } + } + + queueDispatch.notify(queue: DispatchQueue.global()) { + completion(modelMap) + } + } + } + + /** + * Provides an internal data structure for storing closure-referenced values + * in order to facilitate proper Swift memory management. + * + * If closures using `self` haven't yet been called when the class + * otherwise goes out of scope, those closures maintain `self` and + * prevent `deinit`. + * + * By moving closure-referenced properties to a class field and creating local + * variables to reference it as needed, , `self` is no longer kept alive by + * closures, allowing `deinit` to occur naturally. + * + * The 'master' `deinit` may then ensure everything else `deinit`s properly.. + */ + private class ClosureSharedSpace { + /** + * Used to track whether or not a language picker is currently active. + * Installs will not be started until after this DispatchGroup is completed. + * + * Also used to ensure any queued queries actually start before listening + * for all currently-active queries to complete. + */ + let pickerDispatch: DispatchGroup = DispatchGroup() + + /** + * Used to track whether or not any queries are pending completion. + * + * Note that due to internal constraints,`wait()` **must not** be + * called on this `DispatchGroup` until after `pickerDispatch`'s + * tasks have completed. + */ + let queryDispatch: DispatchGroup = DispatchGroup() + + /** + * The data structure used to collate query results. + */ + var packageMap: [KeymanPackage.Key: Association] = [:] + + /** + * The currently-picked set of languages + */ + var languageSet: Set = Set() + + /** + * Used as a write-lock for collating query results. + */ + let querySyncQueue: DispatchQueue = DispatchQueue(label: "com.keyman.associationQueue.sync") + + /** + * Performs package queries based on picked languages. + */ + let searcher: AssociationSearcher + + /** + * The closure provided to the `LanguagePickAssociator` containing this class + * for processing any detected language associations. + */ + let progressClosure: AssociationReceiver + + /** + * Tracks how many languages have been successfully queried, regardless of whether + * or not they reported that associated resources were available. + */ + var queriesComplete: Int = 0 + + /** + * Notifies the worker threads of query cancellation. + */ + var isCancelled: Bool = false + + public init(searcher: @escaping AssociationSearcher, closure: @escaping AssociationReceiver) { + self.searcher = searcher + self.progressClosure = closure + } + } + + /** + * Used to facilitate common references across various closures and threads by the class. + */ + private let closureShared: ClosureSharedSpace + + /** + * Used to facilitate concurrent association searches and manage internal concurrency. + */ + private let associationQueue: DispatchQueue + + /** + * The set of languages that have been queried, whether or not they are _currently_ picked. + */ + private var languageSetSearched: Set + + /** + * Used to prevent resource leaks from waiting threads/query processing. + */ + private var pickerActive: Bool = false + + private static var queueToken: Int = 0 + + public init(searchWith searcher: @escaping AssociationSearcher, progressClosure: @escaping AssociationReceiver) { + closureShared = ClosureSharedSpace(searcher: searcher, closure: progressClosure) + + let queueID = LanguagePickAssociator.queueToken + LanguagePickAssociator.queueToken += 1 + associationQueue = DispatchQueue(label: "com.keyman.associationQueue.\(queueID)", + qos: .default, + attributes: .concurrent, + autoreleaseFrequency: .inherit, + target: nil) + + languageSetSearched = Set() + } + + deinit { + if(pickerActive) { + // When the class deinits in this state, we have a 'constructive dismissal'. + // Cancelling all selections and then allowing all closures to complete naturally + // will facilitate deinit for everything else. + self.pickerDismissed() + } + } + + public func pickerInitialized() { + let closureShared = self.closureShared + closureShared.pickerDispatch.enter() + pickerActive = true + + closureShared.queryDispatch.enter() + closureShared.pickerDispatch.notify(queue: DispatchQueue.main) { + closureShared.queryDispatch.leave() + } + + // Establishes the actual 'return' callback for the class asynchronously. + // We `notify` on the single-threaded queue to ensure all writes (performed + // exclusively on the same queue) have already completed. + closureShared.queryDispatch.notify(queue: closureShared.querySyncQueue) { + if closureShared.isCancelled { + return + } + + // With all association info collated, it's time to prepare the actual 'return' values, + // filtered to only give data regarding the picked languages. + var associationMap: [KeymanPackage.Key: Association] = [:] + + closureShared.packageMap.forEach { (key, association) in + let selectedLanguages = association.languageCodes.filter { closureShared.languageSet.contains($0) } + + if selectedLanguages.count > 0 { + associationMap[key] = Association(url: association.url, languageCodes: selectedLanguages) + } + } + + // Now that all association stuff is computed, use the finalization callback + // Use the 'main' (UI) thread to prevent unexpected UI issues. + DispatchQueue.main.async { + closureShared.progressClosure(.complete(closureShared.queriesComplete, associationMap)) + } + } + } + + public func selectLanguages(_ languages: Set) { + let unsearched = languages.filter { !languageSetSearched.contains($0) } + + languages.forEach { lgCode in + closureShared.querySyncQueue.sync { + _ = closureShared.languageSet.insert(lgCode) + } + languageSetSearched.insert(lgCode) + } + + // Start fetch queries for any previously-unsearched language codes! + if unsearched.count > 0 { + queueSelection(forLanguages: unsearched) + } + } + + internal func queueSelection(forLanguages languages: Set) { + let closureShared = self.closureShared + + // We synchronize on this to ensure that the queue starts before pickerDispatch can leave. + // Not that human inputs _should_ be able to trigger a race condition here, + // but it's still best to be sure. + closureShared.pickerDispatch.enter() + + // Queries are allowed to function across multiple threads without issue. + // They should be embarrasingly parallel until the fetch is complete. + associationQueue.async { + closureShared.queryDispatch.enter() + closureShared.pickerDispatch.leave() + + // Use the closure provided at initialization to search for associated resource packages. + closureShared.searcher(languages) { map in + // The only non-parallel parts - writing to the result cache and reporting progress. + // We synchronize by evaluating all writes on our single-threaded DispatchQueue. + closureShared.querySyncQueue.async { + if closureShared.isCancelled { + return + } + + // Since the results may be sparse, we rely on the original parameter's count. + closureShared.queriesComplete += languages.count + + map.forEach { (lgCode, tuple) in + guard let (packageKey, url) = tuple else { + return + } + + var languageSet = (closureShared.packageMap[packageKey]?.languageCodes ?? Set()) + languageSet.insert(lgCode) + + closureShared.packageMap[packageKey] = Association(url: url, languageCodes: languageSet) + } + + // How many picked languages have matching dictionaries? + let finishedCodeList: [String] = closureShared.packageMap.flatMap { (key, association) in + association.languageCodes + } + + let finishedCodeSet = Set(finishedCodeList) + let selectedSet = finishedCodeSet.intersection(closureShared.languageSet) + + let packagesToInstall = closureShared.packageMap.filter { (key, value) in + return selectedSet.intersection(value.languageCodes).count > 0 + } + + // Report progress. + closureShared.progressClosure(.inProgress(closureShared.queriesComplete, packagesToInstall.count)) + } + + // We leave this dispatch group AFTER collating all relevant install requests. + closureShared.queryDispatch.leave() + } + } + } + + public func deselectLanguages(_ languages: Set) { + closureShared.querySyncQueue.sync { + languages.forEach { closureShared.languageSet.remove($0) } + } + } + + public func pickerDismissed() { + closureShared.querySyncQueue.sync { + closureShared.languageSet = Set() + closureShared.isCancelled = true + + closureShared.progressClosure(.cancelled) + } + + pickerActive = false + + // Signals that no further queries will start. + // Once all current queries complete, completionClosure will be called. + closureShared.pickerDispatch.leave() + } + + public func pickerFinalized() { + pickerActive = false + + // Signals that no further queries will start. + // Once all current queries complete, completionClosure will be called. + closureShared.pickerDispatch.leave() + } + + public var languagesPicked: Int { + return closureShared.querySyncQueue.sync { closureShared.languageSet.count } + } + + public var languagesQueried: Int { + return languageSetSearched.count + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallViewController.swift index ecde78563611d8afaf73cd77f591f11eb67d3498..d861c7b2b6da223c271e16f6d3948adcdc9dc7a9 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallViewController.swift @@ -8,20 +8,68 @@ import Foundation import WebKit +import DeviceKit -public class PackageInstallViewController: UIViewController { - public typealias CompletionHandler = (Error?) -> Void +public class PackageInstallViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarControllerDelegate { + private enum NavigationMode: Int { // b/c hashable + // left nav + case cancel + case back - let package: KeymanPackage + // right nav + case none + case next + case install + } + + public typealias CompletionHandler = ([Resource.FullID]?) -> Void + + // Needed to support iOS 9 + 10. + @IBOutlet weak var webViewContainer: UIView! + + // Common fields between both layout formats. + @IBOutlet weak var lblVersion: UILabel! + @IBOutlet weak var lblCopyright: UILabel! + @IBOutlet weak var languageTable: UITableView! + + // iPad layout only - May be altered programatically. + @IBOutlet weak var ipadTagWidthConstraint: NSLayoutConstraint? + + // iPhone layout only + // Do _NOT_ use `weak` here - things break otherwise. + @IBOutlet var iphoneTabViewController: UITabBarController! + + let package: Resource.Package var wkWebView: WKWebView? let completionHandler: CompletionHandler - let isCustom: Bool + let defaultLanguageCode: String + let associators: [LanguagePickAssociator] + let languages: [Language] - public init(for package: KeymanPackage, isCustom: Bool, completionHandler: @escaping CompletionHandler) { + private var leftNavMode: NavigationMode = .cancel + private var rightNavMode: NavigationMode = .none + private var navMapping: [NavigationMode : UIBarButtonItem] = [:] + + public init(for package: Resource.Package, + defaultLanguageCode: String? = nil, + languageAssociators: [LanguagePickAssociator] = [], + completionHandler: @escaping CompletionHandler) { self.package = package self.completionHandler = completionHandler - self.isCustom = isCustom - super.init(nibName: nil, bundle: nil) + self.languages = package.languages + + let packageFirstLangCode = package.installableResourceSets[0][0].languageID + self.defaultLanguageCode = package.languages.contains(where: { $0.id == defaultLanguageCode }) ? defaultLanguageCode! : packageFirstLangCode + self.associators = languageAssociators + + var xib: String + if Device.current.isPad { + xib = "PackageInstallView_iPad" + } else { + xib = "PackageInstallView_iPhone" + } + + super.init(nibName: xib, bundle: Bundle.init(for: PackageInstallViewController.self)) _ = view } @@ -30,36 +78,288 @@ public class PackageInstallViewController: UIViewController { fatalError("init(coder:) has not been implemented") } - override public func loadView() { - wkWebView = WKWebView.init(frame: .zero) + override public func viewDidLoad() { + wkWebView = WKWebView.init(frame: webViewContainer.frame) wkWebView!.backgroundColor = .white - view = wkWebView! + wkWebView!.translatesAutoresizingMaskIntoConstraints = false + webViewContainer.addSubview(wkWebView!) + + // Ensure the web view fills its available space. Required b/c iOS 9 & 10 cannot load + // these correctly from XIBs. + wkWebView!.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true + wkWebView!.leadingAnchor.constraint(equalTo: webViewContainer.leadingAnchor).isActive = true + wkWebView!.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true + wkWebView!.trailingAnchor.constraint(equalTo: webViewContainer.trailingAnchor).isActive = true + + loadNavigationItems() + leftNavigationMode = .cancel + rightNavigationMode = .install + navigationItem.title = package.name + + // Initialize the package info labels and the language-picker table. + let versionFormat = NSLocalizedString("installer-label-version", bundle: engineBundle, comment: "") + lblVersion.text = String.localizedStringWithFormat(versionFormat, package.version.description) + if let copyright = package.metadata.info?.copyright?.description { + lblCopyright.text = copyright + } else { + lblCopyright.isHidden = true + } + + languageTable.delegate = self + languageTable.dataSource = self + + // Set the default selection. + let defaultRow = languages.firstIndex(where: { $0.id == self.defaultLanguageCode })! + let defaultIndexPath = IndexPath(row: defaultRow, section: 0) + languageTable.selectRow(at: defaultIndexPath, animated: false, scrollPosition: .top) + languageTable.cellForRow(at: defaultIndexPath)?.accessoryType = .checkmark + + associators.forEach { + $0.pickerInitialized() + $0.selectLanguages(Set([self.defaultLanguageCode])) + } + + // iPhone-only layout setup + if let tabVC = iphoneTabViewController { + tabVC.delegate = self - // Ensure the web view fills its available space. - wkWebView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] + let tabView = tabVC.view! + self.view.addSubview(tabVC.view) - let cancelBtn = UIBarButtonItem(title: "Cancel", style: .plain, + tabView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true + tabView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true + tabView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true + tabView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true + + tabVC.tabBar.items![0].title = NSLocalizedString("installer-label-package-info", bundle: engineBundle, comment: "") + tabVC.tabBar.items![1].title = NSLocalizedString("installer-label-select-languages", bundle: engineBundle, comment: "") + + // Prevents the tab view from being obscured by the navigation bar. + // It's weird, yeah. + edgesForExtendedLayout = [] + + rightNavigationMode = .next + + if #available(*, iOS 13.4) { + // No icon issues here. + } else { + tabVC.tabBar.items![0].titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -16) + tabVC.tabBar.items![1].titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -16) + } + } + + // If there's only one language in the package, hide the language picker. + if languages.count <= 1 { + if let sourceTagConstraint = ipadTagWidthConstraint { + // Rebuild the width constraint, setting it to zero width. + // The 'proper' iOS approach is to disable the old one and replace it with a new one. + sourceTagConstraint.isActive = false + let hideTagConstraint = NSLayoutConstraint(item: sourceTagConstraint.firstItem as Any, + attribute: sourceTagConstraint.firstAttribute, + relatedBy: sourceTagConstraint.relation, + toItem: sourceTagConstraint.secondItem, + attribute: sourceTagConstraint.secondAttribute, + multiplier: 0, + constant: 0) + hideTagConstraint.isActive = true + } else if let tabVC = iphoneTabViewController { + // Hide the tab bar, making it appear as if only the "info view" portion exists. + tabVC.tabBar.isHidden = true + + // Since we won't be showing the user a language list, allow them to install from the info view. + rightNavigationMode = .install + } + } + } + + override public func viewWillAppear(_ animated: Bool) { + if let readmeURL = package.readmePageURL { + wkWebView?.loadFileURL(readmeURL, allowingReadAccessTo: package.sourceFolder) + } else { + wkWebView?.loadHTMLString(package.infoHtml(), baseURL: nil) + } + } + + private func loadNavigationItems() { + navMapping[.cancel] = UIBarButtonItem(title: NSLocalizedString("command-cancel", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(cancelBtnHandler)) - let installBtn = UIBarButtonItem(title: "Install", style: .plain, + + navMapping[.back] = UIBarButtonItem(title: NSLocalizedString("command-back", bundle: engineBundle, comment: ""), style: .plain, + target: self, + action: #selector(backBtnHandler)) + + navMapping[.none] = UIBarButtonItem(title: NSLocalizedString("command-install", bundle: engineBundle, comment: ""), style: .plain, + target: self, + action: nil) + navMapping[.none]!.isEnabled = false + + navMapping[.next] = UIBarButtonItem(title: NSLocalizedString("command-next", bundle: engineBundle, comment: ""), style: .plain, + target: self, + action: #selector(nextBtnHandler)) + + navMapping[.install] = UIBarButtonItem(title: NSLocalizedString("command-install", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(installBtnHandler)) + } + + private var leftNavigationMode: NavigationMode { + get { + return leftNavMode + } + + set(mode) { + leftNavMode = mode - navigationItem.leftBarButtonItem = cancelBtn - navigationItem.rightBarButtonItem = installBtn + navigationItem.leftBarButtonItem = navMapping[mode] + } } - override public func viewWillAppear(_ animated: Bool) { - wkWebView?.loadHTMLString(package.infoHtml(), baseURL: nil) + private var rightNavigationMode: NavigationMode { + get { + return rightNavMode + } + + set(mode) { + rightNavMode = mode + + navigationItem.rightBarButtonItem = navMapping[mode] + } + } + + public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { + if viewController.view.tag == 1, languages.count <= 1 { + return false + } else { + return true + } + } + + public func tabBarController(_ tabBarController: UITabBarController, didSelect item: UIViewController) { + if item.view.tag == 0 { + leftNavigationMode = .cancel + rightNavigationMode = .next + } else if item.view.tag == 1 { + leftNavigationMode = .back + + if languageTable.indexPathsForSelectedRows?.count ?? 0 == 0 { + rightNavigationMode = .none + } else { + rightNavigationMode = .install + } + } } @objc func cancelBtnHandler() { - dismiss(animated: true, completion: nil) + // If it is not the root view of a navigationController, just pop it off the stack. + if let navVC = self.navigationController, navVC.viewControllers[0] != self { + navVC.popViewController(animated: true) + } else { // Otherwise, if the root view of a navigation controller, dismiss it outright. (pop not available) + dismiss(animated: true) + } + self.completionHandler(nil) + self.associators.forEach { $0.pickerDismissed() } + } + + @objc func backBtnHandler() { + guard let tabVC = iphoneTabViewController else { + return + } + // Should only occur for iPhone layouts + tabVC.selectedIndex -= 1 + // Is not automatically called! + tabBarController(tabVC, didSelect: tabVC.viewControllers![tabVC.selectedIndex]) + } + + @objc func nextBtnHandler() { + guard let tabVC = iphoneTabViewController else { + return + } + // Should only occur for iPhone layouts + tabVC.selectedIndex += 1 + // Is not automatically called! + tabBarController(tabVC, didSelect: tabVC.viewControllers![tabVC.selectedIndex]) } @objc func installBtnHandler() { - dismiss(animated: true, completion: { - ResourceFileManager.shared.finalizePackageInstall(self.package, isCustom: self.isCustom, completionHandler: self.completionHandler) - }) + // If it is not the root view of a navigationController, just pop it off the stack. + if let navVC = self.navigationController, navVC.viewControllers[0] != self { + navVC.popViewController(animated: true) + } else { // Otherwise, if the root view of a navigation controller, dismiss it outright. (pop not available) + dismiss(animated: true) + } + + let selectedItems = self.languageTable.indexPathsForSelectedRows ?? [] + let selectedLanguageCodes = selectedItems.map { self.languages[$0.row].id } + + let selectedResources = self.package.installableResourceSets.flatMap { $0.filter { selectedLanguageCodes.contains($0.languageID) }} as! [Resource] + + self.completionHandler(selectedResources.map { $0.typedFullID }) + self.associators.forEach { $0.pickerFinalized() } + } + + public func tableView(_ tableView: UITableView, titleForHeaderInSection: Int) -> String? { + return NSLocalizedString("installer-section-available-languages", bundle: engineBundle, comment: "") + } + + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + switch section { + case 0: + return languages.count + default: + return 0 + } + } + + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cellIdentifier = "any" + var cell: UITableViewCell + + if let reusedCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) { + cell = reusedCell + + // The checkmark is not properly managed by default. + let shouldCheck = languageTable.indexPathsForSelectedRows?.contains(indexPath) ?? false + // Note for later: also ensure that it wasn't already installed. (exception to rule above) + cell.accessoryType = shouldCheck ? .checkmark : .none + } else { + let selectionColor = UIView() + + if #available(iOSApplicationExtension 11.0, *) { + selectionColor.backgroundColor = UIColor(named: "SelectionPrimary") + } else { + selectionColor.backgroundColor = Colors.selectionPrimary + } + + cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) + cell.selectedBackgroundView = selectionColor + } + + switch indexPath.section { + case 0: + let index = indexPath.row + cell.detailTextLabel?.text = languages[index].name + return cell + default: + return cell + } + } + + public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + navigationItem.rightBarButtonItem?.isEnabled = true + tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark + + associators.forEach { $0.selectLanguages( Set([languages[indexPath.row].id]) ) } + } + + public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { + if languageTable.indexPathsForSelectedRows?.count ?? 0 == 0 { + rightNavigationMode = .none + } else { + rightNavigationMode = .install + } + tableView.cellForRow(at: indexPath)?.accessoryType = .none + + associators.forEach { $0.deselectLanguages( Set([languages[indexPath.row].id]) ) } } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallView_iPad.xib b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallView_iPad.xib new file mode 100644 index 0000000000000000000000000000000000000000..d5bc7fe97e54c31d97b066616a161d931eb7bd76 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallView_iPad.xib @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallView_iPhone.xib b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallView_iPhone.xib new file mode 100644 index 0000000000000000000000000000000000000000..93543861543211600af1a2669f1ca982900bda2c --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/PackageInstallView_iPhone.xib @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceDownloadManager.swift b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceDownloadManager.swift index ecbdca826a4386043277d3b3649338770f973bac..1409d74a5eccd888fd2186846d4052cddaf07689 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceDownloadManager.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceDownloadManager.swift @@ -8,113 +8,154 @@ import Foundation +public enum DownloadError : Error { + public enum Cause: Error { + case error(Error) + // code, message, triggering link + case responseCode(Int, String, URL) + } + + // The value: the translation-lookup key. + case failed(Cause) + case busy + case noInternet + + var localizedDescription: String { + switch self { + case .failed(_): + return engineBundle.localizedString(forKey: "alert-download-error-detail", value: nil, table: nil) + case .busy: + return engineBundle.localizedString(forKey: "alert-download-error-busy", value: nil, table: nil) + case .noInternet: + return engineBundle.localizedString(forKey: "alert-no-connection-detail", value: nil, table: nil) + } + } +} + +public enum UpdateError : Error { + public enum Cause: Error { + case error(Error) + // code, message, triggering link + case responseCode(Int, String, URL) + } + + // The value: the translation-lookup key. + case unmanaged + case sourceUnavailable + + var localizedDescription: String { + switch self { + case .unmanaged: + return engineBundle.localizedString(forKey: "error-update-not-managed", value: nil, table: nil) + case .sourceUnavailable: + return engineBundle.localizedString(forKey: "error-update-no-link", value: nil, table: nil) + } + } +} + // One half of the resource management puzzle - this part generates download and update requests at the demand // of app UI and submits them to the actual 'download manager', the ResourceDownloadQueue. // // This will be the public face of resource download management in KMEI, while the other half is private and // only accessible within the library. public class ResourceDownloadManager { - private var downloader: ResourceDownloadQueue + // internal b/c testing access. + internal var session: URLSession + internal var downloader: ResourceDownloadQueue private var isDidUpdateCheck = false + internal var unitTestCurrentDate: Date? + + public static let DISTRIBUTION_CACHE_VALIDITY_THRESHOLD = TimeInterval(60*24*7) // in seconds. 60 minutes, 24 hrs, 7 days. + + public typealias CompletionHandler = (Package?, Error?) throws -> Void + public typealias BatchCompletionHandler = () -> Void + internal typealias InternalBatchCompletionHandler = (CompositeBatch) -> Void public static let shared = ResourceDownloadManager() - - private init() { + + internal init() { + session = URLSession.shared downloader = ResourceDownloadQueue() } - - // MARK: - Common functionality - - private func fetchHandler(for resourceType: DownloadTask.Resource, _ completionHandler: @escaping () -> Void) - -> (_ error: Error?) -> Void { - return { error in - if let error = error { - // TODO: Connect to an error handler (or just render appropriate text) based on the resource type. - self.downloader.downloadFailed(forKeyboards: [], error: error) - } else { - log.info("Fetched repository. Continuing with download.") - completionHandler() - } - } + + // Intended only for use in testing! + internal init(session: URLSession, autoExecute: Bool) { + self.session = session + downloader = ResourceDownloadQueue(session: session, autoExecute: autoExecute) } - // MARK - Downloading keyboards - - private func getInstallableKeyboardMetadata(withID keyboardID: String, languageID: String) -> InstallableKeyboard? { - // Grab info for the relevant API version of the keyboard. - guard let keyboard = Manager.shared.apiKeyboardRepository.installableKeyboard(withID: keyboardID, languageID: languageID) - else { - let message = "Keyboard not found with id: \(keyboardID), languageID: \(languageID)" - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: message]) - downloader.downloadFailed(forKeyboards: [], error: error) - return nil + // MARK - Downloading resources + + // TODO: Consider renaming this if the format will only ever be used for keyboard packages. + /** + * Generates a download link for the specified package. The resulting link is planned to be evergreen, with redirects as + * necessary to support it long, long into the future. + */ + public func defaultDownloadURL(forPackage packageKey: KeymanPackage.Key, + andResource resourceKey: AnyLanguageResourceFullID? = nil, + withVersion version: Version? = nil, + asUpdate: Bool? = nil) -> URL { + var baseURL = KeymanHosts.KEYMAN_COM + baseURL.appendPathComponent("go") + baseURL.appendPathComponent("package") + baseURL.appendPathComponent("download") + baseURL.appendPathComponent(packageKey.id) + + var urlComponents = URLComponents(string: baseURL.absoluteString)! + var queryItems: [URLQueryItem] = [ + URLQueryItem(name: "platform", value: "ios"), + URLQueryItem(name: "tier", value: (Version.currentTagged.tier ?? .stable).rawValue) + ] + + if let version = version { + queryItems.append(URLQueryItem(name: "version", value: version.description)) } - - return keyboard - } - - // We return the batch instance to indicate success. Also, in case we decide to implement Promises based on batch completion, - // since this will expose the generated Promise for the caller's use. - private func downloadKeyboardCore(withMetadata keyboards: [InstallableKeyboard], asActivity activity: DownloadBatch.Activity, - withFilename filename: String, withOptions options: Options) -> DownloadBatch? { - - if let dlBatch = buildKeyboardDownloadBatch(for: keyboards[0], withFilename: filename, asActivity: activity, withOptions: options) { - let tasks = dlBatch.tasks as! [DownloadTask] - // We want to denote ALL language variants of a keyboard as part of the batch's metadata, even if we only download a single time. - tasks.forEach { task in - task.resources = keyboards - } - - // Perform common 'can download' check. We need positive reachability and no prior download queue. - // The parameter facilitates error logging. - if !downloader.canExecute(dlBatch) { - return nil - } - - downloader.queue(dlBatch) - return dlBatch + + if let resourceKey = resourceKey { + queryItems.append(URLQueryItem(name: "bcp47", value: resourceKey.languageID)) } - return nil - } - - private func buildKeyboardDownloadBatch(for keyboard: InstallableKeyboard, withFilename filename: String, - asActivity activity: DownloadBatch.Activity, withOptions options: Options) -> DownloadBatch? { - let keyboardURL = options.keyboardBaseURL.appendingPathComponent(filename) - let fontURLs = Array(Set(keyboardFontURLs(forFont: keyboard.font, options: options) + - keyboardFontURLs(forFont: keyboard.oskFont, options: options))) - do { - try FileManager.default.createDirectory(at: Storage.active.keyboardDir(forID: keyboard.id), - withIntermediateDirectories: true) - } catch { - log.error("Could not create dir for download: \(error)") - return nil + if let asUpdate = asUpdate { + queryItems.append(URLQueryItem(name: "update", value: asUpdate ? "1" : "0")) } - var request = HTTPDownloadRequest(url: keyboardURL, userInfo: [:]) - request.destinationFile = Storage.active.keyboardURL(forID: keyboard.id, version: keyboard.version).path - request.tag = 0 + urlComponents.queryItems = queryItems + return urlComponents.url! + } + + // Used to maintain legacy API: downloadKeyboard and downloadLexicalModel (based on ID, language ID) + private func downloadResource(withFullID fullID: FullID, + sendNotifications: Bool, + asUpdate: Bool? = nil, + completionBlock: CompletionHandler?) + where FullID.Resource.Package: TypedKeymanPackage { + let packageKey = KeymanPackage.Key(id: fullID.id, type: fullID.type) + // TODO: Currently invalid for model downloads. + // + // Fortunately, this currently only affects legacy APIs. + let packageURL = defaultDownloadURL(forPackage: KeymanPackage.Key(id: fullID.id, type: fullID.type), + andResource: fullID, + asUpdate: asUpdate) - let keyboardTask = DownloadTask(do: request, for: [keyboard], type: .keyboard) - var batchTasks: [DownloadTask] = [ keyboardTask ] - - for (i, url) in fontURLs.enumerated() { - request = HTTPDownloadRequest(url: url, userInfo: [:]) - request.destinationFile = Storage.active.fontURL(forKeyboardID: keyboard.id, filename: url.lastPathComponent).path - request.tag = i + 1 - - let fontTask = DownloadTask(do: request, for: nil, type: .other) - batchTasks.append(fontTask) + // Perform common 'can download' check. We need positive reachability and no prior download queue. + guard self.downloader.state == .clear else { + let err = self.downloader.state.error ?? DownloadError.busy + self.resourceDownloadFailed(withKey: packageKey, with: err) + try? completionBlock?(nil, err) + return } - - let batch = DownloadBatch(do: batchTasks, as: activity, ofType: .keyboard) - batchTasks.forEach { task in - task.request.userInfo[Key.downloadBatch] = batch - task.request.userInfo[Key.downloadTask] = task + + let completionClosure: CompletionHandler = completionBlock ?? { package, error in + // If the caller doesn't specify a completion block, this will carry out a default installation. + if let package = package { + try? ResourceFileManager.shared.install(resourceWithID: fullID, from: package) + } } - - return batch + + self.downloadPackage(withKey: packageKey, + from: packageURL, + withNotifications: sendNotifications, + completionBlock: completionClosure) } /// Asynchronously fetches the .js file for the keyboard with given IDs. @@ -125,231 +166,104 @@ public class ResourceDownloadManager { public func downloadKeyboard(withID keyboardID: String, languageID: String, isUpdate: Bool, - fetchRepositoryIfNeeded: Bool = true) { - guard let _ = Manager.shared.apiKeyboardRepository.keyboards, - let options = Manager.shared.apiKeyboardRepository.options - else { - if fetchRepositoryIfNeeded { - log.info("Fetching repository from API for keyboard download") - Manager.shared.apiKeyboardRepository.fetch(completionHandler: fetchHandler(for: .keyboard) { - self.downloadKeyboard(withID: keyboardID, languageID: languageID, isUpdate: isUpdate, fetchRepositoryIfNeeded: false) - }) - return - } else { - let message = "Keyboard repository not yet fetched" - let error = NSError(domain: "Keyman", code: 0, userInfo: [NSLocalizedDescriptionKey: message]) - downloader.downloadFailed(forKeyboards: [], error: error) - return - } - } - - // Grab info for the relevant API version of the keyboard. - guard let keyboard = getInstallableKeyboardMetadata(withID: keyboardID, languageID: languageID), - let filename = Manager.shared.apiKeyboardRepository.keyboards?[keyboardID]?.filename - else { - return - } - - if let _ = downloadKeyboardCore(withMetadata: [keyboard], asActivity: isUpdate ? .update : .download, withFilename: filename, withOptions: options) { - self.downloadLexicalModelsForLanguageIfExists(languageID: languageID) - } - } - - private func keyboardFontURLs(forFont font: Font?, options: Options) -> [URL] { - guard let font = font else { - return [] - } - return font.source.filter({ $0.hasFontExtension }) - .map({ options.fontBaseURL.appendingPathComponent($0) }) - } - - /// Downloads a custom keyboard from the URL (old ad-hoc method) - /// - Parameters: - /// - url: URL to a JSON description of the keyboard - public func downloadKeyboard(from url: URL) { - guard downloader.hasConnection() else { - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: "No connection"]) - downloader.downloadFailed(forKeyboards: [], error: error) - return - } - - guard let data = try? Data(contentsOf: url) else { - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: "Failed to fetch JSON file"]) - downloader.downloadFailed(forKeyboards: [], error: error) - return - } - - decodeKeyboardData(data, decodingStrategy: .ios8601WithFallback) + fetchRepositoryIfNeeded: Bool = true, + completionBlock: CompletionHandler? = nil) { + let kbdFullID = FullKeyboardID(keyboardID: keyboardID, languageID: languageID) + downloadResource(withFullID: kbdFullID, sendNotifications: !isUpdate, completionBlock: completionBlock) } - // Step 2 of old ad-hoc process. May be worth preserving for use with .kmp packages. - private func decodeKeyboardData(_ data: Data, decodingStrategy : JSONDecoder.DateDecodingStrategy) { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = decodingStrategy - - if let keyboard = try? decoder.decode(KeyboardAPICall.self, from: data) { - downloadKeyboard(keyboard) - } else { - decoder.dateDecodingStrategy = .iso8601WithoutTimezone - if let keyboard = try? decoder.decode(KeyboardAPICall.self, from: data) { - downloadKeyboard(keyboard) - } else { - decoder.dateDecodingStrategy = .ios8601WithMilliseconds - do { - let keyboard = try decoder.decode(KeyboardAPICall.self, from: data) - downloadKeyboard(keyboard) - } catch { - downloader.downloadFailed(forKeyboards: [], error: error) + @available(*, deprecated) // Used to maintain deprecated methods stateForKeyboard, stateForLexicalModel. + private func keyboardState(for key: KeymanPackage.Key) -> KeyboardState { + switch(ResourceFileManager.shared.installState(forPackage: key)) { + case .none: + return .needsDownload + case .downloading: + return .downloading + case .pending: + return .downloading + case .installed: + let package = ResourceFileManager.shared.getInstalledPackage(withKey: key)! + switch(package.versionState) { + case .unknown: + return .upToDate + case .upToDate: + return .upToDate + case .needsUpdate: + return .needsUpdate } - } } } - - // Step 3 of the old ad-hoc process. - /// Assumes that Keyboard has font and oskFont set and ignores fonts contained in Language. - private func downloadKeyboard(_ keyboardAPI: KeyboardAPICall) { - let keyboard = keyboardAPI.keyboard - let installableKeyboards = keyboard.languages!.map { language in - InstallableKeyboard(keyboard: keyboard, language: language, isCustom: true) - } - let filename = keyboard.filename - let isUpdate = Storage.active.userDefaults.userKeyboards?.contains { $0.id == keyboard.id } ?? false - - _ = downloadKeyboardCore(withMetadata: installableKeyboards, asActivity: isUpdate ? .update : .download, withFilename: filename, withOptions: keyboardAPI.options) - } - + // Deprecating due to tricky assumption - a keyboard _can_ be installed from two separate packages. /// - Returns: The current state for a keyboard + @available(*, deprecated, message: "Use `ResourceFileManager.shared.installState(forPackage:)` instead. Keyboard states are now tied to the state of their package.") public func stateForKeyboard(withID keyboardID: String) -> KeyboardState { - // Needs validation - I don't think this if-condition can be met in Keyman's current state - // (as of 2019-08-16) - if downloader.keyboardIdForCurrentRequest() == keyboardID { - return .downloading - } let userKeyboards = Storage.active.userDefaults.userKeyboards guard let userKeyboard = userKeyboards?.first(where: { $0.id == keyboardID }) else { - return .needsDownload + // If we don't have a local installed copy, check if we're not downloading a package + // with matching ID. + if downloader.containsPackageKeyInQueue(matchingKey: KeymanPackage.Key(id: keyboardID, type: .keyboard)) { + return .downloading + } else { + return .needsDownload + } } // Check version - if let repositoryVersionString = Manager.shared.apiKeyboardRepository.keyboards?[keyboardID]?.version { - let downloadedVersion = Version(userKeyboard.version) ?? Version.fallback - let repositoryVersion = Version(repositoryVersionString) ?? Version.fallback - if downloadedVersion < repositoryVersion { - return .needsUpdate - } + let packageKey = KeymanPackage.Key(forResource: userKeyboard) + if downloader.containsPackageKeyInQueue(matchingKey: packageKey) { + return .downloading + } else { + return keyboardState(for: packageKey) } - return .upToDate } // MARK - Lexical models - - private func getInstallableLexicalModelMetadata(withID lexicalModelID: String, languageID: String) -> InstallableLexicalModel? { - // Grab info for the relevant API version of the keyboard. - guard let keyboard = Manager.shared.apiLexicalModelRepository.installableLexicalModel(withID: lexicalModelID, languageID: languageID) - else { - let message = "Lexical model not found with id: \(lexicalModelID), languageID: \(languageID)" - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: message]) - // TODO: better error target. - downloader.downloadFailed(forLanguageID: "", error: error) - return nil - } - - return keyboard - } - // We return the batch instance to indicate success. Also, in case we decide to implement Promises based on batch completion, - // since this will expose the generated Promise for the caller's use. - private func downloadLexicalModelCore(withMetadata lexicalModels: [InstallableLexicalModel], asActivity activity: DownloadBatch.Activity, - fromPath path: URL) -> DownloadBatch? { - - if let dlBatch = buildLexicalModelDownloadBatch(for: lexicalModels[0], withFilename: path, asActivity: activity) { - let tasks = dlBatch.tasks as! [DownloadTask] - // We want to denote ALL language variants of a keyboard as part of the batch's metadata, even if we only download a single time. - tasks.forEach { task in - task.resources = lexicalModels - } - - // Perform common 'can download' check. We need positive reachability and no prior download queue. - // The parameter facilitates error logging. - if !downloader.canExecute(dlBatch) { - return nil - } - - downloader.queue(dlBatch) - return dlBatch - } - return nil - } - - private func buildLexicalModelDownloadBatch(for lexicalModel: InstallableLexicalModel, withFilename path: URL, - asActivity activity: DownloadBatch.Activity) -> DownloadBatch? { - do { - try FileManager.default.createDirectory(at: Storage.active.lexicalModelDir(forID: lexicalModel.id), - withIntermediateDirectories: true) - } catch { - log.error("Could not create dir for download: \(error)") - return nil - } - - let request = HTTPDownloadRequest(url: path, userInfo: [:]) - request.destinationFile = Storage.active.lexicalModelPackageURL(forID: lexicalModel.id, version: lexicalModel.version).path - request.tag = 0 - - let lexicalModelTask = DownloadTask(do: request, for: [lexicalModel], type: .lexicalModel) - let batchTasks: [DownloadTask] = [ lexicalModelTask ] - - let batch = DownloadBatch(do: batchTasks, as: activity, ofType: .lexicalModel) - batchTasks.forEach { task in - task.request.userInfo[Key.downloadBatch] = batch - task.request.userInfo[Key.downloadTask] = task - } - - return batch - } - - // Can be called by the cloud keyboard downloader and utilized. + // Can be called by the keyboard downloader and utilized. /// Starts the process of fetching the package file of the lexical model for the given language ID /// first it fetches the list of lexical models for the given language /// then it takes the first of the list and download the KMP package file and asks the app to open it (like adhoc download) /// - Parameters: /// - languageID: the bcp47 string of the desired language - public func downloadLexicalModelsForLanguageIfExists(languageID: String) { - // TODO: This fetch will conflict with the fetch in the next method; we need some scheme to reset - // the other's fetch after this completes. - // - // It _may_ be better to retool how this looks up the lexical model for a language. Not sure yet. - - //get list of lexical models for this languageID /?q=bcp47:en - func listCompletionHandler(lexicalModels: [LexicalModel]?, error: Error?) -> Void { + /// - completionClosure: a optional callback that receives either an error or the default lexical model package for the specified language.. If no closure is specified, all contents of the lexical model package will be installed automatically. + public func downloadLexicalModelsForLanguageIfExists(languageID: String, completionClosure: CompletionHandler? = nil) { + // Note: we aren't caching the result of this query in any way. + // TODO: There's no check to ensure we don't already have a model installed for the language. + // The original lacked this check, as well, and it's a bit of an edge case right now. + Queries.LexicalModel.fetchModels(forLanguageCode: languageID, withSession: session) { results, error in if let error = error { - log.info("Failed to fetch lexical model list for "+languageID+". error: "+(error as! String)) - downloader.downloadFailed(forLanguageID: languageID, error: error) - } else if nil == lexicalModels { + // We never quite started downloading the lexical model, so there's no download to have failed. + log.info("Failed to fetch lexical model list for "+languageID+". error: "+error.localizedDescription) + try? completionClosure?(nil, error) + return + } + + guard let results = results else { // Should not be possible. //TODO: put up an alert instead log.info("No lexical models available for language \(languageID) (nil)") - } else if 0 == lexicalModels?.count { + try? completionClosure?(nil, nil) + return + } + + if results.count == 0 { log.info("No lexical models available for language \(languageID) (empty)") + try? completionClosure?(nil, nil) + // We automatically use the first model in the list. } else { + let lexicalModel = results[0].0 + let lmFullID = results[0].0.fullID log.info("Fetched lexical model list for "+languageID+".") - // choose which of the lexical models to download - // for now, this just downloads the first one - let chosenIndex = 0 - if let lexicalModel = lexicalModels?[chosenIndex] { - //downloadLexicalModelPackage(url: URL.init(string: lexicalModel.packageFilename)!) - // We've already fetched part of the repository to do this. - downloadLexicalModel(withID: lexicalModel.id, languageID: languageID, isUpdate: false, fetchRepositoryIfNeeded: false) - } else { - log.info("no error, but no lexical model in list, either!") - } + + let closure = completionClosure ?? self.standardLexicalModelInstallCompletionBlock(forFullID: lmFullID) + // Its format is not yet supported for lexical models. +// let downloadURL = self.defaultDownloadURL(forPackage: lexicalModel.packageKey, +// andResource: lexicalModel.fullID, +// asUpdate: false) + self.downloadPackage(withKey: lexicalModel.packageKey, from: results[0].1, completionBlock: closure) } } - - Manager.shared.apiLexicalModelRepository.fetchList(languageID: languageID, completionHandler: listCompletionHandler) } /// Asynchronously fetches the .js file for the lexical model with given IDs. @@ -360,234 +274,406 @@ public class ResourceDownloadManager { public func downloadLexicalModel(withID lexicalModelID: String, languageID: String, isUpdate: Bool, - fetchRepositoryIfNeeded: Bool = true) { - - // TODO: We should always force a refetch after new keyboards are installed so we can redo our language queries. - // That should probably be done on successful keyboard installs, not here, though. - if fetchRepositoryIfNeeded { - // A temp measure to make sure things aren't totally broken. Definitely not optimal. - Manager.shared.apiLexicalModelRepository.fetch(completionHandler: nil) - } - - guard let _ = Manager.shared.apiLexicalModelRepository.lexicalModels else { - if fetchRepositoryIfNeeded { - log.info("Fetching repository from API for lexicalModel download") - Manager.shared.apiLexicalModelRepository.fetch(completionHandler: fetchHandler(for: .lexicalModel) { - self.downloadLexicalModel(withID: lexicalModelID, languageID: languageID, isUpdate: isUpdate, fetchRepositoryIfNeeded: false) - }) - return + fetchRepositoryIfNeeded: Bool = true, + completionBlock: CompletionHandler? = nil) { + // Note: in this case, someone knows the "full ID" of the model already, but NOT its location. + // For lexical models, we can use either the LexicalModel query or the PackageVersion query. + // For consistency with keyboard download behavior, we use the PackageVersion query here. + + let lmFullID = FullLexicalModelID(lexicalModelID: lexicalModelID, languageID: languageID) + downloadResource(withFullID: lmFullID, sendNotifications: !isUpdate, completionBlock: completionBlock) + } + + + + /// - Returns: The current state for a lexical model + @available(*, deprecated, message: "Use `ResourceFileManager.shared.installState(forPackage:)` instead. Lexical model states are tied to the state of their package.") + public func stateForLexicalModel(withID lexicalModelID: String) -> KeyboardState { + let userLexicalModels = Storage.active.userDefaults.userLexicalModels + guard let userLexicalModel = userLexicalModels?.first(where: { $0.id == lexicalModelID }) else { + // If we don't have a local installed copy, check if we're not downloading a package + // with matching ID. + if downloader.containsPackageKeyInQueue(matchingKey: KeymanPackage.Key(id: lexicalModelID, type: .lexicalModel)) { + return .downloading } else { - let message = "Lexical model repository not yet fetched" - let error = NSError(domain: "Keyman", code: 0, userInfo: [NSLocalizedDescriptionKey: message]) - downloader.downloadFailed(forKeyboards: [], error: error) - return + return .needsDownload } } - // Grab info for the relevant API version of the keyboard. - guard let lexicalModel = getInstallableLexicalModelMetadata(withID: lexicalModelID, languageID: languageID), - let filename = Manager.shared.apiLexicalModelRepository.lexicalModels?[lexicalModelID]?.packageFilename - else { - return + // Check version + let packageKey = KeymanPackage.Key(forResource: userLexicalModel) + if downloader.containsPackageKeyInQueue(matchingKey: packageKey) { + return .downloading + } else { + return keyboardState(for: packageKey) } - - _ = downloadLexicalModelCore(withMetadata: [lexicalModel], asActivity: isUpdate ? .update : .download, fromPath: URL.init(string: filename)!) } - - /// Downloads a custom lexical model from the URL - /// - Parameters: - /// - url: URL to a JSON description of the lexical model - public func downloadLexicalModel(from url: URL) { - guard downloader.hasConnection() else { - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: "No connection"]) - downloader.downloadFailed(forKeyboards: [], error: error) //??? forLexicalModels - return - } - - guard let data = try? Data(contentsOf: url) else { - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: "Failed to fetch JSON file"]) - downloader.downloadFailed(forKeyboards: [], error: error) //??? forLexicalModels - return + + /** + * Downloads a package for the specified `LanguageResourceFullID` (`FullKeyboardID` / `FullLexicalModelID`) + * and parses it automatically, given a pre-known URL. The fully parsed package (`KeyboardKeymanPackage` / + * `LexicalModelKeymanPackage`) or `Error` that results is available upon completion. + * + * Actual installation of the resource is left to calling code; consider use of `ResourceFileManager`'s `install` methods + * with the returned package. + * + * `withNotifications` specifies whether or not any of KeymanEngine's `NotificationCenter` notifications should be generated. + */ + public func downloadPackage(withKey packageKey: KeymanPackage.Key, + from url: URL, + withNotifications: Bool = false, + completionBlock: @escaping CompletionHandler) { + let batch = buildPackageBatch(withKey: packageKey, + from: url, + withNotifications: withNotifications, + completionBlock: completionBlock) + downloader.queue(.simpleBatch(batch)) + } + + // Facilitates re-use of the downloadPackage core for updates. + // Also allows specifying LanguageResource instances for use in notifications. + internal func buildPackageBatch(withKey packageKey: KeymanPackage.Key, + from url: URL, + withNotifications: Bool = false, + withResource resource: AnyLanguageResource? = nil, + completionBlock: @escaping CompletionHandler) -> DownloadBatch { + var startClosure: (() -> Void)? = nil + var completionClosure: CompletionHandler? = completionBlock + + if withNotifications { + startClosure = resourceDownloadStartClosure(withKey: packageKey) + completionClosure = resourceDownloadCompletionClosure(withKey: packageKey, handler: completionBlock) } - - decodeLexicalModelData(data, decodingStrategy: .ios8601WithFallback) + + // build batch for package + return DownloadBatch(forPackageWithKey: packageKey, from: url, startBlock: startClosure, completionBlock: completionClosure) } - // This should be usable as part of the .model.kmp processing process; we have a kmp.json, after all. - private func decodeLexicalModelData(_ data: Data, decodingStrategy : JSONDecoder.DateDecodingStrategy) { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = decodingStrategy - - if let lexicalModel = try? decoder.decode(LexicalModelAPICall.self, from: data) { - downloadLexicalModel(lexicalModel) - } else { - decoder.dateDecodingStrategy = .iso8601WithoutTimezone - if let lexicalModel = try? decoder.decode(LexicalModelAPICall.self, from: data) { - downloadLexicalModel(lexicalModel) + // MARK: Update checks + management + /** + * Given that an update-check query has already been run, returns whether or not any updates are available. + */ + public var updateCacheIsCurrent: Bool { + let packages = ResourceFileManager.shared.installedPackages + + let packageWithOldestCache = packages.min { lhs, rhs in + if let lhsTimestamp = lhs.versionQueryCache.timestampForLastQuery, + let rhsTimestamp = rhs.versionQueryCache.timestampForLastQuery { + return lhsTimestamp <= rhsTimestamp } else { - decoder.dateDecodingStrategy = .ios8601WithMilliseconds - do { - let lexicalModel = try decoder.decode(LexicalModelAPICall.self, from: data) - downloadLexicalModel(lexicalModel) - } catch { - downloader.downloadFailed(forKeyboards: [], error: error) //??? forLexicalModels - } + // Ensure that the 'nil' timestamp is returned overall if it exists. + return rhs.versionQueryCache.timestampForLastQuery != nil } } + + // If there are no packages, the cache is considered 'current' - there's nothing to update. + guard let package = packageWithOldestCache else { + return true + } + + // If there is no timestamp for the 'oldest' entry, there's nothing cached for at least one package. + // We should run the query to initialize its distribution-state metadata. + guard let timestamp = package.versionQueryCache.timestampForLastQuery else { + return false + } + + // Every package has a cached entry... but are they recent enough? + let date = unitTestCurrentDate ?? Date() + let now = date.timeIntervalSince1970 + let timeDelta = now - timestamp + + return timeDelta <= ResourceDownloadManager.DISTRIBUTION_CACHE_VALIDITY_THRESHOLD } - - // Accordingly, this could be retooled to help with .model.kmp files too. - private func downloadLexicalModel(_ lexicalModelAPI: LexicalModelAPICall) { - let lexicalModel = lexicalModelAPI.lexicalModels[0] - let installableLexicalModels = lexicalModel.languages.map { language in - InstallableLexicalModel(lexicalModel: lexicalModel, languageID: language, isCustom: true) - } - - let packageFilename = lexicalModel.packageFilename - let lexicalModelURL = URL(string: "https://api.keyman.com/model")!.appendingPathComponent(packageFilename) - - do { - try FileManager.default.createDirectory(at: Storage.active.lexicalModelDir(forID: lexicalModel.id), - withIntermediateDirectories: true) - } catch { - log.error("Could not create dir for download: \(error)") - return + + /** + * Indicates whether any packages are known to be updatable based on the most recently + * cached package-version query for each. To bypass the cache and query for updated results, + * use `queryKeysForUpdatablePackages` instead. + */ + public var updatesAvailable: Bool { + get { + return getKeysForUpdatablePackages().count > 0 } - - let isUpdate = Storage.active.userDefaults.userLexicalModels?.contains { $0.id == lexicalModel.id } ?? false - - if let batch = buildLexicalModelDownloadBatch(for: installableLexicalModels[0], withFilename: lexicalModelURL, asActivity: isUpdate ? .update : .download) { - if !downloader.canExecute(batch) { + } + + /** + * Returns a Set of package keys for packages known to be updatable, + * based upon the results of their most recently-run latest-version queries. + * + * If neither `KeymanPackage.queryCurrentVersions` nor `KeymanPackage.queryDistributionStates` + * has been run for a package, it is assumed to be current, as this is a synchronous method. + */ + public func getKeysForUpdatablePackages() -> Set { + let packages = ResourceFileManager.shared.installedPackages + + let keys: [KeymanPackage.Key] = packages.compactMap { package in + guard package.versionQueryCache.distributionMethod == .cloud, + let versionString = package.versionQueryCache.latestVersion, + let latestVersion = Version(versionString) else { + // We only update packages with full cloud support. + return nil + } + + if package.version < latestVersion { + return package.key + } else { + return nil + } + } + + return Set(keys) + } + + /** + * Queries the cloud for the latest version of every installed package, returning a Set + * of keys for packages with available updates. The results will also be cached for use + * with related `get`-prefixed methods, like `getKeysForUpdatablePackages`. + */ + public func queryKeysForUpdatablePackages(completionBlock: @escaping (Set?, Error?) -> Void) { + let allPackages = ResourceFileManager.shared.installedPackages + + // This call will automatically cache the results for future use / access by the 'get' equivalent. + KeymanPackage.queryCurrentVersions(for: allPackages.map { $0.key }, withSession: session) { results, error in + guard error == nil, let results = results else { + completionBlock(nil, error) return } - downloader.queue(batch) + let updatables: [KeymanPackage.Key] = allPackages.compactMap { package in + guard let result = results[package.key] else { + return nil + } + + return package.version < result ? package.key : nil + } + + completionBlock(Set(updatables), nil) } } - - /// - Returns: The current state for a lexical model - //TODO: rename KeyboardState to ResourceState? so it can be used with both keybaoards and lexical models without confusion - public func stateForLexicalModel(withID lexicalModelID: String) -> KeyboardState { - if downloader.lexicalModelIdForCurrentRequest() == lexicalModelID { - return .downloading + + public func performBatchUpdate(forPackageKeys keysToUpdate: Set? = nil, + withNotifications: Bool = true, + completionBlock: (([KeymanPackage.Key], [(KeymanPackage.Key, Error)]) -> Void)? = nil) { + let engineUpdatables = getKeysForUpdatablePackages() + var updatables = Set() + + var invalids: [(KeymanPackage.Key, Error)] = [] + + if keysToUpdate == nil { + updatables = engineUpdatables + } else { + // Verify that KeymanEngine actually can update the entry. + updatables = engineUpdatables.intersection(keysToUpdate!) + + // Generate errors for any entries that KeymanEngine cannot update. + keysToUpdate!.forEach { key in + if !updatables.contains(key) { + invalids.append( (key, UpdateError.unmanaged) ) + } + } } - let userLexicalModels = Storage.active.userDefaults.userLexicalModels - guard let userLexicalModel = userLexicalModels?.first(where: { $0.id == lexicalModelID }) else { - return .needsDownload + + if updatables.count == 0 { + completionBlock?([], invalids) + return } - - // Check version - if let repositoryVersionString = Manager.shared.apiLexicalModelRepository.lexicalModels?[lexicalModelID]?.version { - let downloadedVersion = Version(userLexicalModel.version) ?? Version.fallback - let repositoryVersion = Version(repositoryVersionString) ?? Version.fallback - if downloadedVersion < repositoryVersion { - return .needsUpdate + + var updateMapping: Dictionary = [:] + updatables.forEach { key in + guard let downloadURL = Storage.active.userDefaults.cachedPackageQueryResult(forPackageKey: key)!.downloadURL else { + // Note error - download URL missing. Shouldn't be possible, but still. + invalids.append( (key, UpdateError.sourceUnavailable) ) + return + } + + updateMapping[key] = self.buildPackageBatch(withKey: key, + from: downloadURL) { package, error in + guard let package = package, error == nil else { + let errString = error != nil ? String(describing: error!) : "" + log.error("Could not successfully download package \(key) for update: \(errString)") + return + } + + if let kbdPackage = package as? KeyboardKeymanPackage { + let updatables = ResourceFileManager.shared.findPotentialUpdates(in: kbdPackage) + try ResourceFileManager.shared.install(resourcesWithIDs: updatables.map { $0.fullID }, from: kbdPackage) + } else if let lmPackage = package as? LexicalModelKeymanPackage { + let updatables = ResourceFileManager.shared.findPotentialUpdates(in: lmPackage) + try ResourceFileManager.shared.install(resourcesWithIDs: updatables.map { $0.fullID }, from: lmPackage) + } } } - return .upToDate + + // Build the composite batch. + let batchNodes: [DownloadNode] = updateMapping.values.map { .simpleBatch($0) } + let updateCompletionClosure = resourceBatchUpdateCompletionClosure(withNotifications: withNotifications, completionBlock: completionBlock) + let updateBatch = CompositeBatch(queue: batchNodes, startBlock: nil, completionBlock: updateCompletionClosure) + + downloader.queue(.compositeBatch(updateBatch)) } - - // MARK: Update checks + management - public var updatesAvailable: Bool { - get { - return getAvailableUpdates() != nil - } + + static func packageKeys(forResources resources: [AnyLanguageResource]) -> Set { + let keys = resources.map { $0.packageKey } + return Set(keys) } - - public func getAvailableUpdates() -> [LanguageResource]? { - // Relies upon KMManager's preload; this was the case before the rework. - if Manager.shared.apiKeyboardRepository.languages == nil && Manager.shared.apiLexicalModelRepository.languages == nil { + + @available(*, deprecated) + public func installLexicalModelPackage(at packageURL: URL) -> InstallableLexicalModel? { + do { + if let package = try ResourceFileManager.shared.prepareKMPInstall(from: packageURL) as? LexicalModelKeymanPackage { + try ResourceFileManager.shared.finalizePackageInstall(package, isCustom: false) + // The reason we're deprecating it; only returns the first model, even if more language pairings are installed. + return package.installables[0][0] + } else { + log.error("Specified package (at \(packageURL)) does not contain lexical models: \(KMPError.invalidPackage)") + return nil + } + } catch { + log.error("Error occurred while attempting to install package from \(packageURL): \(String(describing: error))") return nil } + } - isDidUpdateCheck = true - - var updatables: [LanguageResource] = [] + // MARK - Completion handlers. - // Gets the list of current, local keyboards in need of an update. - // Version matches the current version, not the updated version. - let kbds = getUpdatableKeyboards() - updatables.append(contentsOf: kbds) + internal func resourceDownloadStartClosure(withKey packageKey: KeymanPackage.Key) -> (() -> Void) { + return { self.resourceDownloadStarted(withKey: packageKey) } + } - // Likewise for lexical models. - let lexModels = getUpdatableLexicalModels() - updatables.append(contentsOf: lexModels) - - if updatables.count > 0 { - return updatables - } else { - return nil + // Only for use with individual downloads. Updates should have different completion handling. + internal func resourceDownloadCompletionClosure(withKey packageKey: KeymanPackage.Key, handler: CompletionHandler?) -> CompletionHandler { + return { package, error in + guard let package = package, error == nil else { + self.resourceDownloadFailed(withKey: packageKey, + with: DownloadError.failed(.error( error ?? KeymanError.unknown ))) + try? handler?(nil, error) + return + } + + do { + try handler?(package, error) + self.resourceDownloadCompleted(with: package) + } catch { + log.error("Unhandled error occurred after resource successfully downloaded: \(String(describing: error))") + self.resourceDownloadFailed(withKey: packageKey, with: error) + } + + // After the custom handler operates, ensure that any changes it made are synchronized for use + // with the app extension, too. + let userDefaults = Storage.active.userDefaults + userDefaults.set([Date()], forKey: Key.synchronizeSWKeyboard) + userDefaults.synchronize() } } - - public func performUpdates(forResources resources: [LanguageResource]) { - // The plan is to create new notifications to handle batch updates here, rather than - // require a UI to manage the update queue. - var batches: [DownloadBatch] = [] - - resources.forEach { res in - if let kbd = res as? InstallableKeyboard { - if let filename = Manager.shared.apiKeyboardRepository.keyboards?[kbd.id]?.filename, - let kbdUpdate = Manager.shared.apiKeyboardRepository.installableKeyboard(withID: kbd.id, languageID: kbd.languageID), - let options = Manager.shared.apiKeyboardRepository.options { - if let batch = self.buildKeyboardDownloadBatch(for: kbdUpdate, withFilename: filename, asActivity: .update, withOptions: options) { - batches.append(batch) - } - } - } else if let lex = res as? InstallableLexicalModel { - if let filename = Manager.shared.apiLexicalModelRepository.lexicalModels?[lex.id]?.packageFilename, - let lexUpdate = Manager.shared.apiLexicalModelRepository.installableLexicalModel(withID: lex.id, languageID: lex.languageID), - let path = URL.init(string: filename) { - if let batch = self.buildLexicalModelDownloadBatch(for: lexUpdate, withFilename: path, asActivity: .update) { - batches.append(batch) + + internal func resourceBatchUpdateStartClosure(for resources: [AnyLanguageResource]) -> (() -> Void) { + return { + let notification = BatchUpdateStartedNotification(resources) + NotificationCenter.default.post(name: Notifications.batchUpdateStarted, + object: self, + value: notification) + } + } + + internal func resourceBatchUpdateCompletionClosure(withNotifications: Bool, + completionBlock: (([KeymanPackage.Key], [(KeymanPackage.Key, Error)]) -> Void)? = nil) + -> InternalBatchCompletionHandler { + return { batch in + var successes: [KeymanPackage.Key] = [] + var failures: [(KeymanPackage.Key, Error)] = [] + + batch.batchQueue.forEach{ tuple in + if case let .simpleBatch(node) = tuple.0 { + if let err = node.errors.first(where: { $0 != nil }), let error = err { + failures.append( (node.packageKey, error) ) + } else { + successes.append(node.packageKey) } } } + + if withNotifications { + // Send update notification to the UI. + let notification = BatchUpdateCompletedNotification(successes: successes, failures: failures) + NotificationCenter.default.post(name: Notifications.batchUpdateCompleted, + object: self, + value: notification) + } + + completionBlock?(successes, failures) } - - let batchUpdate = DownloadBatch(queue: batches) - downloader.queue(batchUpdate) } - - private func getUpdatableKeyboards() -> [InstallableKeyboard] { - var updateQueue: [InstallableKeyboard] = [] - var kbIDs = Set() - - // Build the keyboard update queue - Storage.active.userDefaults.userKeyboards?.forEach { kb in - let kbState = stateForKeyboard(withID: kb.id) - if kbState == .needsUpdate { - if(!kbIDs.contains(kb.id)) { - kbIDs.insert(kb.id) - updateQueue.append(kb) + + public func standardKeyboardInstallCompletionBlock(forFullID fullID: FullKeyboardID, withModel: Bool = true) -> CompletionHandler { + return { package, error in + if let package = package { + do { + try ResourceFileManager.shared.install(resourceWithID: fullID, from: package) + log.info("succesfully parsed the keyboard in: \(package.sourceFolder)") + + // Maintains legacy behavior; automatically sets the newly-downloaded keyboard as active. + if let keyboard = package.findResource(withID: fullID) { + _ = Manager.shared.setKeyboard(keyboard) + } + + if withModel { + self.downloadLexicalModelsForLanguageIfExists(languageID: fullID.languageID) + } + } catch { + log.error("Keyboard installation error: \(String(describing: error))") } + } else if let error = error { + log.error("Installation failed: \(String(describing: error))") + } else { + log.error("Unknown error when attempting to install \(fullID.description))") } } - - return updateQueue - } - - private func getUpdatableLexicalModels() -> [InstallableLexicalModel] { - // Build the lexical model update queue - var updateQueue: [InstallableLexicalModel] = [] - var lmIDs = Set() - - Storage.active.userDefaults.userLexicalModels?.forEach { lm in - let lmState = stateForLexicalModel(withID: lm.id) - if lmState == .needsUpdate { - if !lmIDs.contains(lm.id) { - lmIDs.insert(lm.id) - updateQueue.append(lm) + } + + public func standardLexicalModelInstallCompletionBlock(forFullID fullID: FullLexicalModelID) -> CompletionHandler { + return { package, error in + if let package = package { + do { + // A raw port of the queue's old installation method for lexical models. + try ResourceFileManager.shared.finalizePackageInstall(package, isCustom: false) + log.info("successfully parsed the lexical model in: \(package.sourceFolder)") + + if let installedLexicalModel = package.findResource(withID: fullID) { + _ = Manager.shared.registerLexicalModel(installedLexicalModel) + } + } catch { + log.error("Error installing the lexical model: \(String(describing: error))") } + } else if let error = error { + log.error("Error downloading the lexical model \(String(describing: error))") + } else { + log.error("Unknown error when attempting to install \(fullID.description)") } } + } - return updateQueue + // MARK - Notifications + internal func resourceDownloadStarted(withKey packageKey: KeymanPackage.Key) { + DispatchQueue.main.async { + NotificationCenter.default.post(name: Notifications.packageDownloadStarted, + object: self, + value: packageKey) + } } - public func installLexicalModelPackage(at packageURL: URL) -> InstallableLexicalModel? { - return downloader.installLexicalModelPackage(downloadedPackageFile: packageURL) + internal func resourceDownloadCompleted(with package: KeymanPackage) { + DispatchQueue.main.async { + NotificationCenter.default.post(name: Notifications.packageDownloadCompleted, + object: self, + value: package) + } + } + + internal func resourceDownloadFailed(withKey packageKey: KeymanPackage.Key, with error: Error) { + DispatchQueue.main.async { + NotificationCenter.default.post(name: Notifications.packageDownloadFailed, + object: self, + value: PackageDownloadFailedNotification(packageKey: packageKey, error: error)) + } } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceDownloadQueue.swift b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceDownloadQueue.swift index 72113df82b8e5b4b03feea18c2e35d3ae0045ec3..8a02be781d4c48d7bbc390e60f1ea58019d3a85b 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceDownloadQueue.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceDownloadQueue.swift @@ -9,167 +9,310 @@ import Foundation import Reachability -protocol DownloadNode { - var resources: [LanguageResource]? { get } -} +enum DownloadNode { + case simpleBatch(AnyDownloadBatch) + case compositeBatch(CompositeBatch) -class DownloadTask: DownloadNode { - public enum Resource { - case keyboard, lexicalModel, other + var packageKeys: [KeymanPackage.Key] { + switch(self) { + case .simpleBatch(let batch): + return batch.packageKeys + case .compositeBatch(let node): + return node.packageKeys + } } - - public final var type: Resource - public final var resources: [LanguageResource]? + + var errors: [Error?] { + get { + switch(self) { + case .simpleBatch(let batch): + return batch.errors + case .compositeBatch(let node): + return node.batchQueue.map{ $0.1 } + } + } + } +} + +protocol AnyDownloadTask { + var request: HTTPDownloadRequest { get } + var file: URL { get } + var downloadFinalizationBlock: ((Bool) throws -> Void)? { get } +} + +class DownloadTask: AnyDownloadTask { public final var request: HTTPDownloadRequest + public var file: URL { + if let file = finalFile { + return file + } else { + return URL(fileURLWithPath: request.destinationFile!) + } + } + + public var finalFile: URL? + + public final var downloadFinalizationBlock: ((Bool) throws -> Void)? = nil - public init(do request: HTTPDownloadRequest, for resources: [LanguageResource]?, type: DownloadTask.Resource) { + public init(do request: HTTPDownloadRequest, forPackage packageKey: KeymanPackage.Key?) { self.request = request - self.type = type - self.resources = resources } + + public init(forPackageWithKey packageKey: KeymanPackage.Key, + from url: URL, + as destURL: URL, tempURL: URL) { + + let request = HTTPDownloadRequest(url: url, userInfo: [:]) + request.destinationFile = tempURL.path + request.tag = 0 + + self.finalFile = destURL + self.request = request + + self.downloadFinalizationBlock = DownloadTask.resourceDownloadFinalizationClosure(tempURL: tempURL, finalURL: destURL) + } + + + /** + * Supports downloading to a 'temp' file that is renamed once the download completes. + */ + internal static func resourceDownloadFinalizationClosure(tempURL: URL, + finalURL: URL) -> ((Bool) throws -> Void) { + return { success in + // How to check for download failure + if !success { + if FileManager.default.fileExists(atPath: tempURL.path) { + try? FileManager.default.removeItem(at: tempURL) + } + } else { + try ResourceFileManager.shared.copyWithOverwrite(from: tempURL, to: finalURL) + try? FileManager.default.removeItem(at: tempURL) + } + } + } +} + +enum DownloadActivityType { + case download, update +} + +protocol AnyDownloadBatch { + var tasks: [AnyDownloadTask] { get } + var packageKey: KeymanPackage.Key { get } + + // Needed for DownloadNode compliance. + var packageKeys: [KeymanPackage.Key] { get } + + var startBlock: (() -> Void)? { get } + var errors: [Error?] { get set } + + func completeWithCancellation() throws -> Void + func completeWithError(error: Error) throws -> Void + func completeWithPackage(fromKMP file: URL) throws -> Void } /** * Represents one overall resource-related command for requests against the Keyman Cloud API. */ -class DownloadBatch: DownloadNode { - public enum Activity { - case download, update, composite - } - - /* - * Three main cases so far: - * - [.download, .keyboard]: download new Keyboard (possibly with an associated lexical model) - * - [.download, .lexicalModel]: download new LexicalModel. - * - [.composite, .other]: batch update of all resources, containing the following within its compositeQueue - * - [.update, .keyboard]: updates one Keyboard - * - [.update, .lexicalModel]: updates one LexicalModel - * - Depending on needs, this may be extended to allow 'nested' .composite instances. - */ - public final var activity: Activity - public final var type: DownloadTask.Resource - - public final var tasks: [DownloadNode] +class DownloadBatch: AnyDownloadBatch { + typealias CompletionHandler = ResourceDownloadManager.CompletionHandler + + public final var downloadTasks: [DownloadTask] + public let packageKey: KeymanPackage.Key var errors: [Error?] // Only used by the ResourceDownloadQueue. - //public final var promise: Int - - public init?(do tasks: [DownloadTask], as activity: Activity, ofType type: DownloadTask.Resource) { - self.activity = activity - self.type = type - self.tasks = tasks + public final var startBlock: (() -> Void)? = nil + public final var completionBlock: CompletionHandler? = nil + + public init(forPackageWithKey packageKey: KeymanPackage.Key, + from url: URL, + startBlock: (() -> Void)?, + completionBlock: CompletionHandler?) { + // If we can't build a proper DownloadTask, we can't build the batch. + self.packageKey = packageKey + let tempArtifact = ResourceFileManager.shared.packageDownloadTempPath(forKey: packageKey) + let finalFile = ResourceFileManager.shared.cachedPackagePath(forKey: packageKey) - self.errors = Array(repeating: nil, count: tasks.count) - - // Indicates 'composite' mode, which should use the other initializer. - if activity == .composite { - return nil - } + let task = DownloadTask(forPackageWithKey: packageKey, from: url, as: finalFile, tempURL: tempArtifact) - // A batch containing tasks should always be targeting a 'primary' language resource. - // .other exists to handle fonts packaged with keyboards, not our primary resources. - if type == .other { - return nil - } + + self.downloadTasks = [task] + self.errors = Array(repeating: nil, count: 1) // We only build the one task. + + self.startBlock = startBlock + self.completionBlock = completionBlock + + task.request.userInfo[Key.downloadTask] = task + task.request.userInfo[Key.downloadBatch] = self } - - public init(queue: [DownloadBatch]) { - self.activity = .composite - self.type = .other - self.tasks = queue - - self.errors = Array(repeating: nil, count: tasks.count) + + public var tasks: [AnyDownloadTask] { + return downloadTasks } - public var resources: [LanguageResource]? { + public var packageKeys: [KeymanPackage.Key] { get { - var resArray: [LanguageResource] = [] - - tasks.forEach{ task in - resArray.append(contentsOf: task.resources ?? []) + return [ packageKey ] + } + } + + public func completeWithCancellation() throws { + let complete = completionBlock + completionBlock = nil + try complete?(nil, nil) + } + + public func completeWithError(error: Error) throws { + let complete = completionBlock + completionBlock = nil + try complete?(nil, error) + } + + public func completeWithPackage(fromKMP file: URL) throws { + let complete = completionBlock + completionBlock = nil + + do { + if let package = try ResourceFileManager.shared.prepareKMPInstall(from: file) as? Package { + try complete?(package, nil) + } else { + try complete?(nil, KMPError.invalidPackage) } - - return resArray + } catch { + try complete?(nil, error) } } } +class CompositeBatch { + public final var batchQueue: [(DownloadNode, Error?)] + public final var startBlock: (() -> Void)? = nil + public final var completionBlock: ResourceDownloadManager.InternalBatchCompletionHandler? = nil + + public init(queue: [DownloadNode], + startBlock: (() -> Void)? = nil, + completionBlock: ResourceDownloadManager.InternalBatchCompletionHandler? = nil) { + self.batchQueue = queue.map { ($0, nil) } + self.startBlock = startBlock + self.completionBlock = completionBlock + } + + public var tasks: [DownloadNode] { + return batchQueue.map { $0.0 } + } + + public var packageKeys: [KeymanPackage.Key] { + return batchQueue.flatMap { $0.0.packageKeys } + } +} + // This is a private class used internally by ResourceDownloadQueue to track progress through // the queue and its DownloadBatches. We need a stack scheme - each instance of this corresponds // to one frame of the stack. private class DownloadQueueFrame { public var nodes: [DownloadNode] = [] public var index: Int = 0 - public final var batch: DownloadBatch? - private(set) var isComposite = false + public final var batch: DownloadNode? public init() { batch = nil } - public init? (from batch: DownloadBatch) { - if batch.activity != .composite { - return nil - } - - self.isComposite = true - self.batch = batch + public init? (from batch: CompositeBatch) { + self.batch = .compositeBatch(batch) nodes.append(contentsOf: batch.tasks) } + + public var isComposite: Bool { + if case .compositeBatch(_) = batch { + return true + } else { + return false + } + } } -// The other half of ResourceDownloadManager, this class is responsible for executing the downloads -// and handling the results. +/** + * The other half of ResourceDownloadManager, this class is responsible for executing the downloads + * and handling the results. Internally manages its own single-threaded `DispatchQueue`, which + * handles all necessary synchronization. + * + * At present, submissions to this class will be evaluated sequentially by its `DispatchQueue`, though + * this may change at a later time. (The 'sequential' aspect is due to legacy design decisions from + * before concurrency was a consideration.) + */ class ResourceDownloadQueue: HTTPDownloadDelegate { + enum QueueState: String { + case clear + case noConnection + + var error: Error? { + switch(self) { + case .clear: + return nil + case .noConnection: + return DownloadError.noInternet + } + } + } + + // ---- CRITICAL SECTION FIELDS ---- + // Any writes to these must be performed on `queueThread`. + // Async reads are permitted. private var queueRoot: DownloadQueueFrame private var queueStack: [DownloadQueueFrame] - + // ------------- END --------------- + + private var queueThread: DispatchQueue private var downloader: HTTPDownloader? private var reachability: Reachability? - private let keymanHostName = "api.keyman.com" + + private let session: URLSession + + // Designed for use with testing. + internal var autoExecute: Bool = true - public init() { + public convenience init() { + self.init(session: URLSession.shared, autoExecute: true) + } + + internal init(session: URLSession, autoExecute: Bool) { do { - try reachability = Reachability(hostname: keymanHostName) + try reachability = Reachability(hostname: KeymanHosts.API_KEYMAN_COM.host!) } catch { log.error("Could not start Reachability object: \(error)") } - + + self.session = session + self.autoExecute = autoExecute + queueRoot = DownloadQueueFrame() queueStack = [queueRoot] // queueRoot will always be the bottom frame of the stack. + + // Creates a single-threaded DispatchQueue, facilitating concurrency at this class's + // critical sections. + queueThread = DispatchQueue(label: "com.keyman.ResourceDownloadQueue") } public func hasConnection() -> Bool { return reachability?.connection != Reachability.Connection.unavailable } - - // Might should add a "withNotification: Bool" option for clarity. - public func canExecute(_ batch: DownloadBatch) -> Bool { + + public var state: QueueState { guard hasConnection() else { - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: "No internet connection"]) - downloadFailed(forBatch: batch, error: error) - return false - } - - // At this stage, we now have everything needed to generate download requests. - guard currentBatch == nil else { // Original behavior - only one download operation is permitted at a time. - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: "Download queue is busy"]) - downloadFailed(forBatch: batch, error: error) - return false + return .noConnection } - return true + return .clear } - public var currentBatch: DownloadBatch? { + public var currentBatch: DownloadNode? { get { let frame = currentFrame if(frame.nodes.count == 0) { return nil // Nothing's downloading. } else { - return (frame.nodes[frame.index] as! DownloadBatch) // Return the currently processing DownloadBatch. + return (frame.nodes[frame.index]) // Return the currently processing DownloadNode. } } } @@ -180,7 +323,13 @@ class ResourceDownloadQueue: HTTPDownloadDelegate { } } - private func finalizeCurrentBatch() { + // ---------- CRITICAL SECTION: START ----------- + // IMPORTANT: These functions should only ever be referenced from `queueThread`. + // as they maintain synchronization for the queue's critical + // tracking fields. + // + // As a result, these functions are intentionally and explicitly `private`. + private func finalizeCurrentBatch(withError error: Error? = nil) { let frame = queueStack[queueStack.count - 1] if queueStack.count == 1 { @@ -191,11 +340,14 @@ class ResourceDownloadQueue: HTTPDownloadDelegate { // when everything's done instead. Might be worth a thought. frame.nodes.remove(at: 0) } else { + if case let .compositeBatch(batch) = frame.batch { + batch.batchQueue[frame.index].1 = error + } // Batches in subframes should be kept so that we can report progress; increment the index instead. frame.index += 1 } } - + private func executeNext() { let frame = queueStack[queueStack.count - 1] @@ -206,69 +358,93 @@ class ResourceDownloadQueue: HTTPDownloadDelegate { return } // else - let batch = frame.nodes[0] as! DownloadBatch - innerExecute(batch) + let node = frame.nodes[0] + innerExecute(node) } else { // We're in a queue stack frame; check our state! if frame.index == frame.nodes.count { // We've hit the end of this stack frame's commands; time to pop and continue from the previous frame's perspective. _ = queueStack.popLast() - - // In the current state of the app, this is only the case for batch updates. - if frame.isComposite { - let parentFrame = queueStack[queueStack.count - 1] - updateBatchFinished(parentFrame.nodes[parentFrame.index] as! DownloadBatch) - } - + // Of course, this means we've "finished" a batch download. We can use the same handlers as before. - finalizeCurrentBatch() - executeNext() + // if-check below: "if the current stack-frame came from a composite batch, let node = that 'composite batch'" + if case .compositeBatch(let node) = frame.batch { + // The base handler requires access to the batch's tracked success/failure data. + let error = node.batchQueue.first(where: { $0.1 != nil })?.1 + finalizeCurrentBatch(withError: error) + node.completionBlock?(node) + } else { + fatalError("Unexpected download queue state; cannot recover") + } + + if autoExecute { + executeNext() + } return } else { // We've got more batches left within this stack frame. Continue. - let batch = frame.nodes[frame.index] as! DownloadBatch - innerExecute(batch) + let node = frame.nodes[frame.index] + innerExecute(node) } } } - private func innerExecute(_ batch: DownloadBatch) { - if batch.activity == .composite { - if batch.type == .other { + private func innerExecute(_ node: DownloadNode) { + switch(node) { + case .simpleBatch(let batch): + // Make a separate one for each batch; this simplifies event handling when multiple batches are in queue, + // as the old downloader will have a final event left to trigger at this point. (downloadQueueFinished) + downloader = HTTPDownloader(self, session: self.session) + let tasks = batch.tasks + + downloader!.userInfo = [Key.downloadBatch: batch] + + tasks.forEach { task in + downloader!.addRequest(task.request) + } + + // Signal that we've started processing this batch. + batch.startBlock?() + downloader!.run() + case .compositeBatch(let batch): // It's the top level of an update operation. Time to make a correpsonding notification. - updateBatchStarted(batch) - } - // We're a batch composed of multiple sub-batches. Time to set that up on the queue! - let frame = DownloadQueueFrame(from: batch)! - queueStack.append(frame) - // TODO: Notify about the new batch being started! - - innerExecute(batch.tasks[0] as! DownloadBatch) - return - } else { - // Make a separate one for each batch; this simplifies event handling when multiple batches are in queue, - // as the old downloader will have a final event left to trigger at this point. (downloadQueueFinished) - downloader = HTTPDownloader(self) - let tasks = batch.tasks as! [DownloadTask] - downloader!.userInfo = [Key.downloadBatch: batch] - - tasks.forEach { task in - downloader!.addRequest(task.request) - } - - downloader!.run() - // TODO: Notify about the new batch being started! + batch.startBlock?() + // We're a batch composed of multiple sub-batches. Time to set that up on the queue! + let frame = DownloadQueueFrame(from: batch)! + queueStack.append(frame) + + innerExecute(batch.tasks[0]) } } - - public func queue(_ batch: DownloadBatch) { - queueRoot.nodes.append(batch) - - // If the queue was empty before this... - if queueRoot.nodes.count == 1 { - executeNext() + + // ----------- CRITICAL SECTION: END ------------ + + // The next two functions are used as queueThread's "API". + // Internally, they must perform `sync` / `async` operations when + // writing to the critical tracking fields. + public func queue(_ node: DownloadNode) { + // `sync` is particularly important here for some automated testing checks + // when `autoExecute == `false`. + queueThread.sync { + self.queueRoot.nodes.append(node) + } + + queueThread.async { + // If the queue was empty before this... + if self.queueRoot.nodes.count == 1 && self.autoExecute { + self.executeNext() + } } } - + + internal func step() { + queueThread.async { self.executeNext() } + } + + // Exposes useful information for runtime mocking. Used by some automated tests. + internal func topLevelNodes() -> [DownloadNode] { + return queueRoot.nodes + } + // MARK - helper methods for ResourceDownloadManager // TODO: Eliminate this property coompletely. @@ -279,294 +455,106 @@ class ResourceDownloadQueue: HTTPDownloadDelegate { } } - // TODO: Needs validation. - func keyboardIdForCurrentRequest() -> String? { - if let currentRequest = currentRequest { - let tmpStr = currentRequest.url.lastPathComponent - if tmpStr.hasJavaScriptExtension { - return String(tmpStr.dropLast(3)) - } - } else { - // TODO: search the queue instead. -// let kbInfo = downloader!.userInfo[Key.keyboardInfo] -// if let keyboards = kbInfo as? [InstallableKeyboard], let keyboard = keyboards.first { -// return keyboard.id -// } - } - return nil - } - - func lexicalModelIdForCurrentRequest() -> String? { - if let currentRequest = currentRequest { - let tmpStr = currentRequest.url.lastPathComponent - if tmpStr.hasJavaScriptExtension { - return String(tmpStr.dropLast(3)) + func containsPackageKeyInQueue(matchingKey: KeymanPackage.Key) -> Bool { + return queueRoot.nodes.contains { node in + node.packageKeys.contains { fullID in + return fullID == matchingKey } - } else { - // TODO: search the queue instead. -// let kbInfo = downloader!.userInfo[Key.lexicalModelInfo] -// if let lexicalModels = kbInfo as? [InstallableLexicalModel], let lexicalModel = lexicalModels.first { -// return lexicalModel.id -// } } - return nil } - // MARK - notification methods + //MARK: - HTTPDownloadDelegate methods - private func downloadFailed(forBatch batch: DownloadBatch, error: Error) { - let tasks = batch.tasks as! [DownloadTask] - if batch.activity == .composite { - // It's an update operation. - // Not yet called in this case. - } else if batch.type == .keyboard { - let keyboards = tasks.compactMap { task in - return task.resources as? [InstallableKeyboard] - }.flatMap {$0} - downloadFailed(forKeyboards: keyboards, error: error) - } else if batch.type == .lexicalModel { - let lexModels = tasks.compactMap { task in - return task.resources as? [InstallableLexicalModel] - }.flatMap {$0} - downloadFailed(forLanguageID: lexModels[0].languageID, error: error) + func downloadQueueFinished(_ queue: HTTPDownloader) { + // We can use the properties of the current "batch" to generate specialized notifications. + let batch = queue.userInfo[Key.downloadBatch] as! AnyDownloadBatch + + let packagePath = batch.tasks[0].file + var err: Error? = nil + do { + try batch.completeWithPackage(fromKMP: packagePath) + } catch { + err = error } - } - - public func downloadFailed(forKeyboards keyboards: [InstallableKeyboard], error: Error) { - let notification = KeyboardDownloadFailedNotification(keyboards: keyboards, error: error) - NotificationCenter.default.post(name: Notifications.keyboardDownloadFailed, - object: self, - value: notification) - } - - public func downloadFailed(forLanguageID languageID: String, error: Error) { - let notification = LexicalModelDownloadFailedNotification(lmOrLanguageID: languageID, error: error) - NotificationCenter.default.post(name: Notifications.lexicalModelDownloadFailed, - object: self, - value: notification) - } - - public func downloadFailed(forLexicalModelPackage packageURL: String, error: Error) { - let notification = LexicalModelDownloadFailedNotification(lmOrLanguageID: packageURL, error: error) - NotificationCenter.default.post(name: Notifications.lexicalModelDownloadFailed, - object: self, - value: notification) - } - - public func downloadSucceeded(forKeyboards keyboards: [InstallableKeyboard]) { - let notification = KeyboardDownloadCompletedNotification(keyboards) - NotificationCenter.default.post(name: Notifications.keyboardDownloadCompleted, - object: self, - value: notification) - } - - public func downloadSucceeded(forLexicalModel lm: InstallableLexicalModel) { - let notification = LexicalModelDownloadCompletedNotification([lm]) - NotificationCenter.default.post(name: Notifications.lexicalModelDownloadCompleted, - object: self, - value: notification) - } - - - public func updateBatchStarted(_ batch: DownloadBatch) { - let notification = BatchUpdateStartedNotification(batch.resources!) - NotificationCenter.default.post(name: Notifications.batchUpdateStarted, - object: self, - value: notification) - } - - public func updateBatchFinished(_ batch: DownloadBatch) { - var successes: [[LanguageResource]] = [] - var failures: [[LanguageResource]] = [] - var errors: [Error] = [] - - // Remember, since this is for .composite batches, batch.tasks is of type [DownloadBatch]. - for (index, res) in batch.tasks.enumerated() { - if batch.errors[index] == nil { - successes.append(res.resources!) + + queueThread.async { + if let error = err { + self.finalizeCurrentBatch(withError: error) } else { - failures.append(res.resources!) - errors.append(batch.errors[index]!) + // Completing the queue means having completed a batch. We should only move forward in this class's + // queue at this time, once a batch's task queue is complete. + self.finalizeCurrentBatch() } - } - - let notification = BatchUpdateCompletedNotification(successes: successes, failures: failures, errors: errors) - NotificationCenter.default.post(name: Notifications.batchUpdateCompleted, - object: self, - value: notification) - } - //MARK: - HTTPDownloadDelegate methods - - func downloadQueueFinished(_ queue: HTTPDownloader) { - // We can use the properties of the current "batch" to generate specialized notifications. - let batch = queue.userInfo[Key.downloadBatch] as! DownloadBatch - - // Due to how the queue operates, batch.activity != .composite. That case is handled elsewhere. - if(batch.activity == .composite) { - // Composite indicates that a batch is made of multiple sub-batches, not individual - // DownloadTasks that the HTTPDownloader can handle, which are 1-to-1 with its requests. - fatalError("HTTPDownloader should never be assigned a .composite-type DownloadBatch.") - } else { - let isUpdate = batch.activity == .update - - if batch.type == .keyboard { - // The request has succeeded. - if downloader!.requestsCount == 0 { // Download queue finished. - let keyboards = batch.resources as! [InstallableKeyboard] - - FontManager.shared.registerCustomFonts() - log.info("Downloaded keyboard: \(keyboards[0].id).") - - if(!isUpdate) { - downloadSucceeded(forKeyboards: keyboards) - } else { - // Since we don't generate the notification as above, we need to manually update - // the keyboards' metadata. - keyboards.forEach { keyboard in - Manager.shared.addKeyboard(keyboard) - } - } - - let userDefaults = Storage.active.userDefaults - userDefaults.set([Date()], forKey: Key.synchronizeSWKeyboard) - userDefaults.synchronize() - } - } else if batch.type == .lexicalModel { - let task = batch.tasks[0] as! DownloadTask // It's always at this index. - if let lm = installLexicalModelPackage(downloadedPackageFile: URL(fileURLWithPath: task.request.destinationFile!)) { - if !isUpdate { - downloadSucceeded(forLexicalModel: lm) - } else { - // Since we don't generate the notification as above, we need to manually update - // the lexical model's metadata. - Manager.shared.updateUserLexicalModels(with: lm) - } - } else if !isUpdate { - let installError = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: "installError"]) - downloadFailed(forLexicalModelPackage: "\(task.request.url)", error: installError) - currentFrame.batch?.errors[currentFrame.index] = installError - } + if self.autoExecute { + self.executeNext() } } - - // Completing the queue means having completed a batch. We should only move forward in this class's - // queue at this time, once a batch's task queue is complete. - finalizeCurrentBatch() - executeNext() } func downloadQueueCancelled(_ queue: HTTPDownloader) { - // - - // In case we're part of a 'composite' operation, we should still keep the queue moving. - finalizeCurrentBatch() - executeNext() + if case .simpleBatch(let batch) = self.currentBatch { + try? batch.completeWithCancellation() + } + + queueThread.async { + // In case we're part of a 'composite' operation, we should still keep the queue moving. + self.finalizeCurrentBatch() + + if self.autoExecute { + self.executeNext() + } + } } func downloadRequestStarted(_ request: HTTPDownloadRequest) { - // If we're downloading a new keyboard. - // The extra check is there to filter out other potential request types in the future. - let batch = request.userInfo[Key.downloadBatch] as! DownloadBatch - - if request.tag == 0 && batch.activity != .update { - let task = request.userInfo[Key.downloadTask] as! DownloadTask - if task.type == .keyboard { - NotificationCenter.default.post(name: Notifications.keyboardDownloadStarted, - object: self, - value: task.resources as! [InstallableKeyboard]) - } else if task.type == .lexicalModel { - NotificationCenter.default.post(name: Notifications.lexicalModelDownloadStarted, - object: self, - value: task.resources as! [InstallableLexicalModel]) - } + if let batch = request.userInfo[Key.downloadBatch] as? AnyDownloadBatch { + batch.startBlock?() } } func downloadRequestFinished(_ request: HTTPDownloadRequest) { + let task = request.userInfo[Key.downloadTask] as! AnyDownloadTask // Did we finish, but with an request error code? if request.responseStatusCode != 200 { // Possible request error (400 Bad Request, 404 Not Found, etc.) + let error = DownloadError.failed(.responseCode(request.responseStatusCode ?? 400, + request.responseStatusMessage ?? "", + request.url)) - let errorMessage = "\(request.responseStatusMessage ?? ""): \(request.url)" - let error = NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: errorMessage]) - currentFrame.batch?.errors[currentFrame.index] = error + if case var .simpleBatch(batch) = currentFrame.batch { + batch.errors[currentFrame.index] = error + } // Now that we've synthesized an appropriate error instance, use the same handler // as for HTTPDownloader's 'failed' condition. downloadRequestFailed(request, with: error) - } // else - handled once the entire queue is completed without errors. - // This particularly matters for keyboards. - } - - func downloadRequestFailed(_ request: HTTPDownloadRequest) { - // We should never be in a state to return 'Unknown error", but better safe than sorry. - downloadRequestFailed(request, with: request.error ?? NSError(domain: "Keyman", code: 0, - userInfo: [NSLocalizedDescriptionKey: "Unknown error"])) + + // If we used a temp filename during download, resolve it. + try? task.downloadFinalizationBlock?(false) + } else { + do { + try task.downloadFinalizationBlock?(true) + } catch { + downloadRequestFailed(request, with: error) + } + } } - func downloadRequestFailed(_ request: HTTPDownloadRequest, with error: Error) { - currentFrame.batch?.errors[currentFrame.index] = error + func downloadRequestFailed(_ request: HTTPDownloadRequest, with error: Error?) { + let task = request.userInfo[Key.downloadTask] as! AnyDownloadTask + var batch = request.userInfo[Key.downloadBatch] as! AnyDownloadBatch + batch.errors[currentFrame.index] = error - let task = request.userInfo[Key.downloadTask] as! DownloadTask - let batch = request.userInfo[Key.downloadBatch] as! DownloadBatch - let isUpdate = batch.activity == .update - - if task.type == .keyboard { - log.error("Keyboard download failed: \(error).") - let keyboards = task.resources as? [InstallableKeyboard] - - if !isUpdate { - // Clean up keyboard file if anything fails - // TODO: Also clean up remaining fonts - try? FileManager.default.removeItem(at: Storage.active.keyboardURL(for: keyboards![0])) - downloadFailed(forKeyboards: keyboards ?? [], error: error as NSError) - } - } else if task.type == .lexicalModel { - log.error("Lexical model download failed: \(error).") - let lexicalModels = task.resources as? [InstallableLexicalModel] - - if !isUpdate { - // Clean up model file if anything fails - try? FileManager.default.removeItem(at: Storage.active.lexicalModelURL(for: lexicalModels![0])) - downloadFailed(forLanguageID: lexicalModels?[0].languageID ?? "", error: error as NSError) - } + var err: Error + if let error = error { + err = error + } else { + err = KeymanError.unknown } - + + try? task.downloadFinalizationBlock?(false) + try? batch.completeWithError(error: err) downloader!.cancelAllOperations() } - - // MARK - Language resource installation methods - - // Processes fetched lexical models. - // return a lexical model so caller can use it in a downloadSucceeded call - // is called by other class funcs - public func installLexicalModelPackage(downloadedPackageFile: URL) -> InstallableLexicalModel? { - var installedLexicalModel: InstallableLexicalModel? = nil - - ResourceFileManager.shared.prepareKMPInstall(from: downloadedPackageFile, completionHandler: { kmp, error in - if let kmp = kmp as! LexicalModelKeymanPackage? { - do { - ResourceFileManager.shared.finalizePackageInstall(kmp, isCustom: false, completionHandler: { error in - if error != nil { - log.error("Error installing the lexical model: \(String(describing: error))") - } else { - log.info("successfully parsed the lexical model in: \(kmp.sourceFolder)") - installedLexicalModel = kmp.models[0].installableLexicalModels[0] - } - }) - - //this can fail gracefully and not show errors to users - try FileManager.default.removeItem(at: downloadedPackageFile) - } catch { - log.error("Error installing the lexical model: \(error)") - } - } else { - log.error("Error extracting the lexical model from the package: \(String(describing: error))") - } - }) - return installedLexicalModel - } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceFileManager.swift b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceFileManager.swift index b9f10985687be7c051d902e9b82d2f5040131e4f..8851bacceb0b53af7b98a520ee10a2e045b4d7d1 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceFileManager.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/ResourceFileManager.swift @@ -19,10 +19,71 @@ public class ResourceFileManager { fileprivate init() { } + public var installedPackages: [KeymanPackage] { + let userResources = Storage.active.userDefaults.userResources ?? [] + + var backingPackages: [KeymanPackage] = [] + for resource in userResources { + if let package = KeymanPackage.parse(Storage.active.resourceDir(for: resource)!) { + // On successful parse, just ensure that we haven't already listed the package. + if !backingPackages.contains(where: { $0.id == package.id }) { + backingPackages.append(package) + } + } + } + + return backingPackages + } + + public func installState(forPackage key: KeymanPackage.Key) -> KeymanPackage.InstallationState { + return installState(forPackage: key, withManager: ResourceDownloadManager.shared) + } + + // For mocked test use. + internal func installState(forPackage key: KeymanPackage.Key, withManager downloadManager: ResourceDownloadManager) -> KeymanPackage.InstallationState { + let localCachePath = self.cachedPackagePath(forKey: key) + + if let package = getInstalledPackage(withKey: key) { + return package.installState + } else if downloadManager.downloader.containsPackageKeyInQueue(matchingKey: key) { + return .downloading + } else if FileManager.default.fileExists(atPath: localCachePath.path) { + return .pending + } else { + return .none + } + } + + public func getInstalledPackage(for resource: Resource) -> Resource.Package? { + if let packageDir = Storage.active.resourceDir(for: resource) { + return KeymanPackage.parse(packageDir) as? Resource.Package + } else { + return nil + } + } + + public func getInstalledPackage(withKey key: KeymanPackage.Key) -> KeymanPackage? { + return KeymanPackage.parse(Storage.active.packageDir(forKey: key)) + } + + internal func packageDownloadTempPath(forKey key: KeymanPackage.Key) -> URL { + let documentDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let tempFilename = KeymanPackage.baseFilename(for: key) + let url = documentDir.appendingPathComponent("\(tempFilename).partial") // marks it as a download in progress + return url + } + + internal func cachedPackagePath(forKey key: KeymanPackage.Key) -> URL { + let documentDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let filename = KeymanPackage.baseFilename(for: key) + let url = documentDir.appendingPathComponent(filename) + return url + } + /** * Apple doesn't provide a method that performs copy-and-overwrite functionality. This function fills in that gap. */ - private func copyWithOverwrite(from source: URL, to destination: URL) throws { + internal func copyWithOverwrite(from source: URL, to destination: URL) throws { let fileManager = FileManager.default // For now, we'll always allow overwriting. @@ -65,7 +126,7 @@ public class ResourceFileManager { * Note that we don't request permissions to support opening/modifying files "in place," so .kmps should already be * located in app-space (by use of `importFile`) before unzipping them. */ - public func prepareKMPInstall(from url: URL, completionHandler: @escaping (KeymanPackage?, Error?) -> Void) { + public func prepareKMPInstall(from url: URL) throws -> KeymanPackage { // Once selected, start the standard install process. log.info("Installing KMP from \(url)") @@ -78,65 +139,118 @@ public class ResourceFileManager { try copyWithOverwrite(from: url, to: archiveUrl) } catch { log.error(error) - completionHandler(nil, KMPError.copyFiles) - return + throw KMPError.copyFiles } var extractionFolder = cacheDirectory extractionFolder.appendPathComponent("temp/\(archiveUrl.lastPathComponent)") + if let kmp = try KeymanPackage.extract(fileUrl: archiveUrl, destination: extractionFolder) { + return kmp + } else { + throw KMPError.invalidPackage + } + } + + /** + * Use this function to "install" external KMP files to within the Keyman app's alloted iOS file management domain. + * Note that we don't request permissions to support opening/modifying files "in place," so .kmps should already be + * located in app-space (by use of `importFile`) before unzipping them. + */ + @available(*, deprecated) + public func prepareKMPInstall(from url: URL, completionHandler: @escaping (KeymanPackage?, Error?) -> Void) { do { - try KeymanPackage.extract(fileUrl: archiveUrl, destination: extractionFolder, complete: { kmp in - if let kmp = kmp { - completionHandler(kmp, nil) - } else { - log.error(KMPError.invalidPackage) - completionHandler(nil, KMPError.invalidPackage) - } - }) + let kmp = try prepareKMPInstall(from: url) + completionHandler(kmp, nil) } catch { log.error(error) + completionHandler(nil, error) } } /** * A utility version of `prepareKMPInstall` that displays default UI alerts if errors occur when preparing a KMP for installation. + * + * The completion handler will only be called when a package is successfully "prepared". */ + @available(*, deprecated) public func prepareKMPInstall(from url: URL, alertHost: UIViewController, completionHandler: @escaping (KeymanPackage) -> Void) { - self.prepareKMPInstall(from: url, completionHandler: { package, error in - if error != nil { - let alert = self.buildKMPError(KMPError.copyFiles) - alertHost.present(alert, animated: true, completion: nil) + if let package = prepareKMPInstall(from: url, alertHost: alertHost) { + completionHandler(package) + } + } + + /** + * A utility version of `prepareKMPInstall` that displays default UI alerts if errors occur when preparing a KMP for installation. + */ + public func prepareKMPInstall(from url: URL, alertHost: UIViewController) -> KeymanPackage? { + do { + return try self.prepareKMPInstall(from: url) + } catch { + let alert: UIAlertController + if let kmpError = error as? KMPError { + alert = self.buildKMPError(kmpError) } else { - completionHandler(package!) + alert = self.buildKMPError(KMPError.copyFiles) } - }) + + alertHost.present(alert, animated: true, completion: nil) + return nil + } } - public func promptPackageInstall(of package: KeymanPackage, - in rootVC: UIViewController, - isCustom: Bool, - successHandler: ((KeymanPackage) -> Void)? = nil) { - let vc = PackageInstallViewController(for: package, isCustom: isCustom, completionHandler: { error in - if let err = error { - if let kmpError = err as? KMPError { - let alert = self.buildKMPError(kmpError) - rootVC.present(alert, animated: true, completion: nil) + internal func doInstallPrompt>( + for package: Package, + defaultLanguageCode: String? = nil, + in rootVC: UIViewController, + withAssociators associators: [AssociatingPackageInstaller.Associator] = [], + successHandler: ((KeymanPackage) -> Void)? = nil) + where Resource.Package == Package { + let activitySpinner = Alerts.constructActivitySpinner() + activitySpinner.center = rootVC.view.center + + let packageInstaller = AssociatingPackageInstaller(for: package, + withAssociators: associators) { status in + if status == .starting { + // Start a spinner! + activitySpinner.startAnimating() + rootVC.view.addSubview(activitySpinner) + + activitySpinner.centerXAnchor.constraint(equalTo: rootVC.view.centerXAnchor).isActive = true + activitySpinner.centerYAnchor.constraint(equalTo: rootVC.view.centerYAnchor).isActive = true + rootVC.view.isUserInteractionEnabled = false + } else if status == .complete { + // Report completion! + activitySpinner.stopAnimating() + activitySpinner.removeFromSuperview() + rootVC.view.isUserInteractionEnabled = true + rootVC.dismiss(animated: true, completion: nil) + successHandler?(package) } + } + + if let navVC = rootVC as? UINavigationController { + packageInstaller.promptForLanguages(inNavigationVC: navVC) } else { - let alert = self.buildSimpleAlert(title: "Success", message: "Installed successfully.", completionHandler: { - successHandler?(package) - }) - rootVC.present(alert, animated: true, completion: nil) + let nvc = UINavigationController.init() + packageInstaller.promptForLanguages(inNavigationVC: nvc) + rootVC.present(nvc, animated: true, completion: nil) } - }) + } - let nvc = UINavigationController.init(rootViewController: vc) - rootVC.present(nvc, animated: true, completion: nil) + public func promptPackageInstall(of package: KeymanPackage, + in rootVC: UIViewController, + isCustom: Bool, + successHandler: ((KeymanPackage) -> Void)? = nil) { + if let kbdPackage = package as? KeyboardKeymanPackage { + doInstallPrompt(for: kbdPackage, in: rootVC, withAssociators: [.lexicalModels], successHandler: successHandler) + } else if let lmPackage = package as? LexicalModelKeymanPackage { + doInstallPrompt(for: lmPackage, in: rootVC, withAssociators: [], successHandler: successHandler) + } } public func buildKMPError(_ error: KMPError) -> UIAlertController { - return buildSimpleAlert(title: "Error", message: error.rawValue) + return buildSimpleAlert(title: "Error", message: error.localizedDescription) } public func buildSimpleAlert(title: String, message: String, completionHandler: (() -> Void)? = nil ) -> UIAlertController { @@ -155,27 +269,124 @@ public class ResourceFileManager { /** * Performs the actual installation of a package's resources once confirmation has been received from the user. */ + public func finalizePackageInstall(_ package: KeymanPackage, isCustom: Bool) throws { + // Time to pass the package off to the final installers - the parse__KMP methods. + // TODO: (14.0+) These functions should probably be refactored to within this class eventually. + if package.isKeyboard() { + try Manager.shared.parseKbdKMP(package.sourceFolder, isCustom: isCustom) + } else { + try Manager.parseLMKMP(package.sourceFolder, isCustom: isCustom) + } + } + + @available(*, deprecated) public func finalizePackageInstall(_ package: KeymanPackage, isCustom: Bool, completionHandler: (Error?) -> Void) { do { - // Time to pass the package off to the final installers - the parse__KMP methods. - // TODO: (14.0+) These functions should probably be refactored to within this class eventually. - if package.isKeyboard() { - try Manager.shared.parseKbdKMP(package.sourceFolder, isCustom: isCustom) - } else { - try Manager.parseLMKMP(package.sourceFolder, isCustom: isCustom) - } + try finalizePackageInstall(package, isCustom: isCustom) completionHandler(nil) } catch { - log.error(error as! KMPError) + log.error(error) completionHandler(error) } + } + + /** + * Searches the specified package for a language resource with the indicated resource-language-code "full ID" key, + * importing the package's files and installing the indicated resource-language pairing upon success. + * + * The`resourcesWithIDs:` variant is better optimized for installing multiple resources from the same package. + */ + public func install ( + resourceWithID fullID: FullID, + from package: FullID.Resource.Package) throws + where FullID.Resource.Package: TypedKeymanPackage { + try install(resourcesWithIDs: [fullID], from: package) + } + + /** + * Searches the specified package for language resources with the indicated resource-language-code "full ID" keys + * importing the package's files and installing the indicated resource-language pairings upon success. + */ + public func install ( + resourcesWithIDs fullIDs: [FullID], from package: FullID.Resource.Package) throws + where FullID.Resource.Package: TypedKeymanPackage { + if fullIDs.contains(where: { package.findResource(withID: $0) == nil }) { + let missingResource = fullIDs.first(where: { package.findResource(withID: $0) == nil })! + log.error("Resource with full ID \(missingResource.description) not in package") + throw KMPError.resourceNotInPackage + } - //this can fail gracefully and not show errors to users do { - try FileManager.default.removeItem(at: package.sourceFolder) + try copyWithOverwrite(from: package.sourceFolder, + to: Storage.active.packageDir(for: package)!) } catch { - log.error("unable to delete temp files: \(error)") - completionHandler(error) + log.error("Could not create installation directory and/or copy resources: \(error)") + throw KMPError.fileSystem + } + + let updatables: [FullID] = findPotentialUpdates(in: package, ignoring: [] as [FullID.Resource]).map { return $0.typedFullID } + let fullList = fullIDs + updatables + + fullList.forEach { addResource(package.findResource(withID: $0)!) } + } + + internal func findPotentialUpdates> ( + in package: Package, + ignoring resourcesToIgnore: [Resource] = []) -> [Resource] { + let installedResources = Storage.active.userDefaults.userResources(ofType: Resource.self) ?? [] + var updatableResources: [Resource] = [] + + installedResources.forEach { resource in + // If there's no package ID, default to the resource's ID. + // If the package ID matches the resource's package ID and we're not ignoring the resource, + // check to ensure that the package does contain the resource. + if (resource.packageID ?? resource.id) == package.id, + !resourcesToIgnore.contains(where: { $0.typedFullID == resource.typedFullID }) { + if let updatable = package.findResource(withID: resource.typedFullID) { + updatableResources.append(updatable) + } + } + } + + return updatableResources + } + + internal func addResource(_ resource: Resource) { + let path = Storage.active.resourceURL(for: resource)!.path + if !FileManager.default.fileExists(atPath: path) { + log.error("Could not add resource of type: \(resource.fullID.type) with ID: \(resource.id) because the resource file does not exist") + return + } + + // Get keyboards list if it exists in user defaults, otherwise create a new one + let userDefaults = Storage.active.userDefaults + + // Local, inline func used by the block following it. + func addOrAppend(_ resource: Resource, to resourceList: [Resource]) -> [Resource] { + var list = resourceList + // Update resource if it exists + if let index = resourceList.firstIndex(where: { $0.typedFullID == resource.typedFullID }) { + list[index] = resource + } else { + list.append(resource) + } + return list } + + // Use the func we just declared while performing proper Swift type coersion. + if resource is InstallableKeyboard { + let resourceList = addOrAppend(resource, to: userDefaults.userKeyboards as? [Resource] ?? []) + userDefaults.userKeyboards = (resourceList as! [InstallableKeyboard]) + } else if resource is InstallableLexicalModel { + let resourceList = addOrAppend(resource, to: userDefaults.userLexicalModels as? [Resource] ?? []) + userDefaults.userLexicalModels = (resourceList as! [InstallableLexicalModel]) + } else { + fatalError("Cannot install instance of unexpected LanguageResource subclass") + } + + userDefaults.set([Date()], forKey: Key.synchronizeSWKeyboard) + userDefaults.synchronize() + log.info("Added \(resource.fullID.type) with ID: \(resource.id) and language code: \(resource.languageID)") } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Storage.swift b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/Storage.swift similarity index 63% rename from ios/engine/KMEI/KeymanEngine/Classes/Storage.swift rename to ios/engine/KMEI/KeymanEngine/Classes/Resource Management/Storage.swift index b8aa3c149fce81c0245c0e43a2d62046f6aacc9b..cfdc3a91c7e8195a0dbadee39bb4b7ce1a69b333 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Storage.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Resource Management/Storage.swift @@ -84,52 +84,111 @@ class Storage { return nil } } - - func keyboardDir(forID keyboardID: String) -> URL { + + // Note: legacy* methods are utilized for migrations through 14.0, at which point + // KeymanEngine transitioned entirely to using LanguageResource instances + // for path lookups. + + func legacyKeyboardDir(forID keyboardID: String) -> URL { return keyboardDir.appendingPathComponent(keyboardID) } - - func lexicalModelDir(forID lexicalModelID: String) -> URL { + + func legacyLexicalModelDir(forID lexicalModelID: String) -> URL { return lexicalModelDir.appendingPathComponent(lexicalModelID) } + + func packageDir(forID packageID: String, ofType resourceType: LanguageResourceType) -> URL { + switch resourceType { + case .keyboard: + return keyboardDir.appendingPathComponent(packageID) + case .lexicalModel: + return lexicalModelDir.appendingPathComponent(packageID) + } + } + + func packageDir(forKey key: KeymanPackage.Key) -> URL { + return packageDir(forID: key.id, ofType: key.type) + } + + func packageDir(for package: KeymanPackage) -> URL? { + return packageDir(forID: package.id, ofType: package.resourceType()) + } + + func resourceDir(for resource: AnyLanguageResource) -> URL? { + if let keyboard = resource as? InstallableKeyboard { + return packageDir(forID: keyboard.packageID ?? keyboard.id, ofType: .keyboard) + } else if let lexicalModel = resource as? InstallableLexicalModel { + return packageDir(forID: lexicalModel.packageID ?? lexicalModel.id, ofType: .lexicalModel) + } else { + return nil + } + } func keyboardURL(for keyboard: InstallableKeyboard) -> URL { - return keyboardURL(forID: keyboard.id, version: keyboard.version) + return resourceDir(for: keyboard)!.appendingPathComponent("\(keyboard.id).js") } func lexicalModelURL(for lexicalModel: InstallableLexicalModel) -> URL { - return lexicalModelURL(forID: lexicalModel.id, version: lexicalModel.version) + return resourceDir(for: lexicalModel)!.appendingPathComponent("\(lexicalModel.id).model.js") + } + + // Facilitates abstractions based on the LanguageResource protocol. + func resourceURL(for resource: AnyLanguageResource) -> URL? { + if let keyboard = resource as? InstallableKeyboard { + return keyboardURL(for: keyboard) + } else if let lexicalModel = resource as? InstallableLexicalModel { + return lexicalModelURL(for: lexicalModel) + } else { + return nil + } + } + + // Facilitates abstractions based on the LanguageResource protocol. + func legacyResourceURL(for resource: AnyLanguageResource) -> URL? { + if let keyboard = resource as? InstallableKeyboard { + return legacyKeyboardURL(forID: keyboard.id, version: keyboard.version) + } else if let lexicalModel = resource as? InstallableLexicalModel { + return legacyLexicalModelURL(forID: lexicalModel.id, version: lexicalModel.version) + } else { + return nil + } } func lexicalModelPackageURL(for lexicalModel: InstallableLexicalModel) -> URL { - return lexicalModelPackageURL(forID: lexicalModel.id, version: lexicalModel.version) + return resourceDir(for: lexicalModel)!.appendingPathComponent("\(lexicalModel.id).model.kmp") } - - func keyboardURL(forID keyboardID: String, version: String) -> URL { + + // TODO: Once we drop cloud-keyboard downloads, remove this function. + func cloudKeyboardURL(forID keyboardID: String) -> URL { + // For now, we treat cloud keyboards as KMP-less packages, generating a kmp.json after download. + return packageDir(forID: keyboardID, ofType: .keyboard).appendingPathComponent("\(keyboardID).js") + } + + func legacyKeyboardURL(forID keyboardID: String, version: String) -> URL { // We no longer embed version numbers into filenames // This allows us to support existing installs and OEM products that // still include the version string, at reasonable cost // Note, that for installing a keyboard, it will no longer perform this // rename with this model, as the target file will obviously not already // exist. - let filename = keyboardDir(forID: keyboardID).appendingPathComponent("\(keyboardID).js") + let filename = legacyKeyboardDir(forID: keyboardID).appendingPathComponent("\(keyboardID).js") if FileManager.default.fileExists(atPath: filename.path) { return filename } - return keyboardDir(forID: keyboardID).appendingPathComponent("\(keyboardID)-\(version).js") + return legacyKeyboardDir(forID: keyboardID).appendingPathComponent("\(keyboardID)-\(version).js") } - func lexicalModelURL(forID lexicalModelID: String, version: String) -> URL { - return lexicalModelDir(forID: lexicalModelID).appendingPathComponent("\(lexicalModelID)-\(version).model.js") + func legacyLexicalModelURL(forID lexicalModelID: String, version: String) -> URL { + return legacyLexicalModelDir(forID: lexicalModelID).appendingPathComponent("\(lexicalModelID)-\(version).model.js") } - func lexicalModelPackageURL(forID lexicalModelID: String, version: String, asZip: Bool = false) -> URL { + func legacyLexicalModelPackageURL(forID lexicalModelID: String, version: String, asZip: Bool = false) -> URL { // Our unzipping dependency requires a .zip extension to function, so we append that here. - return lexicalModelDir(forID: lexicalModelID).appendingPathComponent("\(lexicalModelID)-\(version).model.kmp\(asZip ? ".zip" : "")") + return legacyLexicalModelDir(forID: lexicalModelID).appendingPathComponent("\(lexicalModelID)-\(version).model.kmp\(asZip ? ".zip" : "")") } - func fontURL(forKeyboardID keyboardID: String, filename: String) -> URL { - return keyboardDir(forID: keyboardID).appendingPathComponent(filename) + func fontURL(forResource resource: AnyLanguageResource, filename: String) -> URL? { + return resourceDir(for: resource)?.appendingPathComponent(filename) } var keyboardDirs: [URL]? { @@ -164,6 +223,10 @@ extension Storage { resourceName: "keymanios.js", dstDir: baseDir, excludeFromBackup: true) + try Storage.copy(from: bundle, + resourceName: "keyman-sentry.js", + dstDir: baseDir, + excludeFromBackup: true) // For debug compilations - IF we have a sourcemap file, copy that over too. if bundle.url(forResource: "keyman.js.map", withExtension: nil) != nil { try Storage.copy(from: bundle, @@ -182,50 +245,45 @@ extension Storage { } func installDefaultKeyboard(from bundle: Bundle) throws { - let defaultKeyboardDir = self.keyboardDir(forID: Defaults.keyboard.id) + let defaultKeyboardDir = self.resourceDir(for: Defaults.keyboard)! try FileManager.default.createDirectory(at: defaultKeyboardDir, withIntermediateDirectories: true) // Since we only want to do this installation the first time (rather than constantly force-reinstalling // the resource), we don't want this excluded from backup. try Storage.copy(from: bundle, - resourceName: "\(Defaults.keyboard.id)-\(Defaults.keyboard.version).js", - dstDir: defaultKeyboardDir, - excludeFromBackup: false) - try Storage.copy(from: bundle, - resourceName: "DejaVuSans.ttf", + resourceName: "\(Defaults.keyboard.id).kmp", dstDir: defaultKeyboardDir, excludeFromBackup: false) + + do { + // Perform an auto-install of the keyboard's KMP if not already installed. + let defaultKMPFile = defaultKeyboardDir.appendingPathComponent("\(Defaults.keyboard.id).kmp") + let package = try ResourceFileManager.shared.prepareKMPInstall(from: defaultKMPFile) as! KeyboardKeymanPackage + try ResourceFileManager.shared.install(resourceWithID: Defaults.keyboard.fullID, from: package) + } catch { + log.error("Failed to install the default keyboard from the bundled KMP: \(error)") + } } func installDefaultLexicalModel(from bundle: Bundle) throws { - let defaultLexicalModelDir = self.lexicalModelDir(forID: Defaults.lexicalModel.id) + let defaultLexicalModelDir = self.resourceDir(for: Defaults.lexicalModel)! try FileManager.default.createDirectory(at: defaultLexicalModelDir, withIntermediateDirectories: true) // Since we only want to do this installation the first time (rather than constantly force-reinstalling // the resource), we don't want this excluded from backup. try Storage.copy(from: bundle, - resourceName: "\(Defaults.lexicalModel.id)-\(Defaults.lexicalModel.version).model.kmp", + resourceName: "\(Defaults.lexicalModel.id).model.kmp", dstDir: defaultLexicalModelDir, excludeFromBackup: false) - // Perform an auto-install of the lexical model's KMP if not already installed. - let lexicalModelURLasZIP = Storage.active.lexicalModelPackageURL(forID: Defaults.lexicalModel.id, - version: Defaults.lexicalModel.version, - asZip: true) - let lexicalModelURL = Storage.active.lexicalModelPackageURL(forID: Defaults.lexicalModel.id, - version: Defaults.lexicalModel.version, - asZip: false) - - // Because of how our .zip dependency works, we need to make the .kmp look like a .zip. A simple rename will do. do { - try Storage.copy(at: lexicalModelURL, to: lexicalModelURLasZIP, excludeFromBackup: true) - let downloader = ResourceDownloadQueue() - - // Hijacking the download queue's KMP installer. - // Issue - requests DL confirmation - // Issue - in a roundabout way, results in attempted access to Manager.shared during Manager.init, causing crash. - _ = downloader.installLexicalModelPackage(downloadedPackageFile: lexicalModelURLasZIP) + // Perform an auto-install of the lexical model's KMP if not already installed. + let defaultKMPFile = defaultLexicalModelDir.appendingPathComponent("\(Defaults.lexicalModel.id).model.kmp") + let package = try ResourceFileManager.shared.prepareKMPInstall(from: defaultKMPFile) as! LexicalModelKeymanPackage + + // Install all languages for the model, not just the default-listed one. + try ResourceFileManager.shared.install(resourcesWithIDs: package.installables[0].map { $0.fullID }, from: package) } catch { log.error("Failed to install the default lexical model from the bundled KMP: \(error)") } @@ -250,8 +308,7 @@ extension Storage { private static func copy(from bundle: Bundle, resourceName: String, dstDir: URL, excludeFromBackup: Bool = false) throws { guard let srcURL = bundle.url(forResource: resourceName, withExtension: nil) else { - let message = "Could not locate \(resourceName) in the Keyman bundle" - throw NSError(domain: "Keyman", code: 0, userInfo: [NSLocalizedDescriptionKey: message]) + throw KeymanError.missingFile(resourceName, true) } let dstURL = dstDir.appendingPathComponent(srcURL.lastPathComponent) @@ -288,8 +345,7 @@ extension Storage { } if !fileExists { - let message = "Nothing to copy at \(src)" - throw NSError(domain: "Keyman", code: 0, userInfo: [NSLocalizedDescriptionKey: message]) + throw KeymanError.missingFile(src.path, false) } if !fm.fileExists(atPath: dst.path) { diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Settings/InstalledLanguagesViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/Settings/InstalledLanguagesViewController.swift index 2ca5d38839c32a9b8b342e2cdc0c6b521fb6bff1..817180636434dd916a66aafab4e60a95f1bf88a7 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Settings/InstalledLanguagesViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Settings/InstalledLanguagesViewController.swift @@ -22,17 +22,12 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie private var selectedSection = 0 private var installedLanguages: [String: Language] private var languages: [Language] = [] - private let keyboardRepository: KeyboardRepository? - private let lexicalModelRepository: LexicalModelRepository? private var isDidUpdateCheck = false - private var keyboardDownloadStartedObserver: NotificationObserver? - private var keyboardDownloadCompletedObserver: NotificationObserver? - private var keyboardDownloadFailedObserver: NotificationObserver? - private var lexicalModelDownloadStartedObserver: NotificationObserver? - private var lexicalModelDownloadCompletedObserver: NotificationObserver? - private var lexicalModelDownloadFailedObserver: NotificationObserver? + private var packageDownloadStartedObserver: NotificationObserver? + private var packageDownloadCompletedObserver: NotificationObserver? + private var packageDownloadFailedObserver: NotificationObserver? private var batchUpdateStartedObserver: NotificationObserver? private var batchUpdateCompletedObserver: NotificationObserver? @@ -42,10 +37,7 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie } else { self.installedLanguages = givenLanguages! } - self.keyboardRepository = Manager.shared.apiKeyboardRepository - self.lexicalModelRepository = nil super.init(nibName: nil, bundle: nil) -// keyboardRepository.delegate = self } required init?(coder aDecoder: NSCoder) { @@ -56,37 +48,30 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie super.loadView() languages = languageList(installedLanguages) } + + private func languageList(_ languageDict: [String: Language]) -> [Language] { + return languageDict.values.sorted { a, b -> Bool in + a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending + } + } override public func viewDidLoad() { super.viewDidLoad() - - title = "Installed Languages" + + title = NSLocalizedString("menu-installed-languages-title", bundle: engineBundle, comment: "") selectedSection = NSNotFound - keyboardDownloadStartedObserver = NotificationCenter.default.addObserver( - forName: Notifications.keyboardDownloadStarted, - observer: self, - function: InstalledLanguagesViewController.keyboardDownloadStarted) - keyboardDownloadCompletedObserver = NotificationCenter.default.addObserver( - forName: Notifications.keyboardDownloadCompleted, - observer: self, - function: InstalledLanguagesViewController.keyboardDownloadCompleted) - keyboardDownloadFailedObserver = NotificationCenter.default.addObserver( - forName: Notifications.keyboardDownloadFailed, + packageDownloadStartedObserver = NotificationCenter.default.addObserver( + forName: Notifications.packageDownloadStarted, observer: self, - function: InstalledLanguagesViewController.keyboardDownloadFailed) - - lexicalModelDownloadStartedObserver = NotificationCenter.default.addObserver( - forName: Notifications.lexicalModelDownloadStarted, - observer: self, - function: InstalledLanguagesViewController.lexicalModelDownloadStarted) - lexicalModelDownloadCompletedObserver = NotificationCenter.default.addObserver( - forName: Notifications.lexicalModelDownloadCompleted, + function: InstalledLanguagesViewController.packageDownloadStarted) + packageDownloadCompletedObserver = NotificationCenter.default.addObserver( + forName: Notifications.packageDownloadCompleted, observer: self, - function: InstalledLanguagesViewController.lexicalModelDownloadCompleted) - lexicalModelDownloadFailedObserver = NotificationCenter.default.addObserver( - forName: Notifications.lexicalModelDownloadFailed, + function: InstalledLanguagesViewController.packageDownloadCompleted) + packageDownloadFailedObserver = NotificationCenter.default.addObserver( + forName: Notifications.packageDownloadFailed, observer: self, - function: InstalledLanguagesViewController.lexicalModelDownloadFailed) + function: InstalledLanguagesViewController.packageDownloadFailed) batchUpdateStartedObserver = NotificationCenter.default.addObserver( forName: Notifications.batchUpdateStarted, @@ -134,20 +119,25 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie // We do have updates - prepare the UI! if let toolbar = navigationController?.toolbar as? ResourceDownloadStatusToolbar { - toolbar.displayButton("Update available", with: self, callback: #selector(self.updateClicked)) + toolbar.displayButton(NSLocalizedString("notification-update-available", bundle: engineBundle, comment: ""), with: self, callback: #selector(self.updateClicked)) } } @objc func updateClicked(_ sender: Any) { if let toolbar = navigationController?.toolbar as? ResourceDownloadStatusToolbar { - toolbar.displayStatus("Updating\u{2026}", withIndicator: true) + toolbar.displayStatus(NSLocalizedString("notification-update-processing", bundle: engineBundle, comment: ""), withIndicator: true) } // Do the actual updates! // TODO: Consider prompting per resource, rather than wholesale as a group. // (This would be an enhancement, though.) - let availableUpdates = ResourceDownloadManager.shared.getAvailableUpdates()! - ResourceDownloadManager.shared.performUpdates(forResources: availableUpdates) + let availableUpdates = ResourceDownloadManager.shared.getKeysForUpdatablePackages() + ResourceDownloadManager.shared.performBatchUpdate(forPackageKeys: availableUpdates, + withNotifications: true, + completionBlock: { successes, failures in + // TODO: future feature: consider reworking the notification listener for use with this callback. + // (See `batchUpdateCompleted` later in this file.) + }) } override public func numberOfSections(in tableView: UITableView) -> Int { @@ -219,7 +209,11 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie cell.selectedBackgroundView = selectionColor cell.accessoryType = .disclosureIndicator } - cell.detailTextLabel?.text = keyboards.count < 2 ? (keyboards.first?.name ?? "") : "\(keyboards.count) installed" + + let formatString = NSLocalizedString("settings-keyboards-installed-count", bundle: engineBundle, comment: "") + cell.detailTextLabel?.text = keyboards.count < 2 ? + (keyboards.first?.name ?? "") : + String.localizedStringWithFormat(formatString, keyboards.count) return cell } @@ -266,7 +260,7 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie } private func showLanguageSettingsView(title: String, languageIndex: Int) { - let langSettingsView = LanguageSettingsViewController(keyboardRepository, languages[languageIndex]) + let langSettingsView = LanguageSettingsViewController(languages[languageIndex]) langSettingsView.title = title navigationController?.pushViewController(langSettingsView, animated: true) } @@ -277,12 +271,6 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie } } - func downloadHandler(_ keyboardIndex: Int) { - let language = languages[selectedSection] - let keyboard = language.keyboards![keyboardIndex] - ResourceDownloadManager.shared.downloadKeyboard(withID: keyboard.id, languageID: language.id, isUpdate: false) - } - private func restoreNavigation() { view.isUserInteractionEnabled = true navigationItem.setHidesBackButton(false, animated: true) @@ -291,90 +279,78 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie navigationItem.rightBarButtonItem?.isEnabled = true } } - - private func showDownloading(_ downloadLabel: String) { + + private func packageDownloadStarted(key: KeymanPackage.Key) { + log.info("download started for \(key.type.rawValue): InstalledLanguagesViewController") + view.isUserInteractionEnabled = false + navigationItem.setHidesBackButton(true, animated: true) + guard let toolbar = navigationController?.toolbar as? ResourceDownloadStatusToolbar else { return } - - toolbar.displayStatus("Downloading \(downloadLabel)\u{2026}", withIndicator: true) - } - - private func keyboardDownloadStarted() { - log.info("keyboardDownloadStarted: InstalledLanguagesViewController") - view.isUserInteractionEnabled = false - navigationItem.setHidesBackButton(true, animated: true) - showDownloading("keyboard") - } - - private func lexicalModelDownloadStarted(_ lexicalModels: [InstallableLexicalModel]) { - log.info("lexicalModelDownloadStarted") - view.isUserInteractionEnabled = false - navigationItem.setHidesBackButton(true, animated: true) - showDownloading("dictionary") + + var msg: String + switch(key.type) { + case .keyboard: + msg = NSLocalizedString("notification-downloading-keyboard", bundle: engineBundle, comment: "") + case .lexicalModel: + msg = NSLocalizedString("notification-downloading-lexical-model", bundle: engineBundle, comment: "") + } + + toolbar.displayStatus(msg, withIndicator: true) } - - private func keyboardDownloadCompleted(_ keyboards: [InstallableKeyboard]) { - log.info("keyboardDownloadCompleted: InstalledLanguagesViewController") - Manager.shared.shouldReloadKeyboard = true - - // Update keyboard version - for keyboard in keyboards { - Manager.shared.updateUserKeyboards(with: keyboard) + + private func packageDownloadCompleted(package: KeymanPackage) { + log.info("lexicalModelDownloadCompleted: InstalledLanguagesViewController") + + var msg: String + + switch(package.resourceType()) { + case .keyboard: + Manager.shared.shouldReloadKeyboard = true + msg = NSLocalizedString("notification-download-success-keyboard", bundle: engineBundle, comment: "") + case .lexicalModel: + msg = NSLocalizedString("notification-download-success-lexical-model", bundle: engineBundle, comment: "") } - + if let toolbar = navigationController?.toolbar as? ResourceDownloadStatusToolbar { - toolbar.displayStatus("Keyboard successfully downloaded!", withIndicator: false, duration: 3.0) + toolbar.displayStatus(msg, withIndicator: false, duration: 3.0) } + restoreNavigation() - - // Add keyboard. - for keyboard in keyboards { - Manager.shared.addKeyboard(keyboard) - _ = Manager.shared.setKeyboard(keyboard) + + // Do NOT do this for keyboards; they're not yet installed and have a managed installer + // yet to operate. + if package.resourceType() == .lexicalModel { + navigationController?.popToRootViewController(animated: true) } - - navigationController?.popToRootViewController(animated: true) } - - private func lexicalModelDownloadCompleted(_ lexicalModels: [InstallableLexicalModel]) { - log.info("lexicalModelDownloadCompleted: InstalledLanguagesViewController") - // Add models. - for lexicalModel in lexicalModels { - Manager.addLexicalModel(lexicalModel) - _ = Manager.shared.registerLexicalModel(lexicalModel) + + private func packageDownloadFailed(notification: PackageDownloadFailedNotification) { + guard let packageKey = notification.packageKey else { + return } - + + log.info("keyboardDownloadFailed: InstalledLanguagesViewController") + + var msg: String + switch(packageKey.type) { + case .keyboard: + msg = NSLocalizedString("notification-download-failure-keyboard", bundle: engineBundle, comment: "") + case .lexicalModel: + msg = NSLocalizedString("notification-download-failure-lexical-model", bundle: engineBundle, comment: "") + } + if let toolbar = navigationController?.toolbar as? ResourceDownloadStatusToolbar { - toolbar.displayStatus("Dictionary successfully downloaded!", withIndicator: false, duration: 3.0) + toolbar.displayStatus(msg, withIndicator: false, duration: 3.0) } - + restoreNavigation() + navigationController?.popToRootViewController(animated: true) } - private func keyboardDownloadFailed() { - log.info("keyboardDownloadFailed: InstalledLanguagesViewController") - restoreNavigation() - } - - private func lexicalModelDownloadFailed() { - log.info("lexicalModelDownloadFailed: InstalledLanguagesViewController") - restoreNavigation() - - let title = "Dictionary Download Error" - navigationController?.setToolbarHidden(true, animated: true) - - let alertController = UIAlertController(title: title, message: "", - preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "OK", - style: UIAlertAction.Style.cancel, - handler: nil)) - - self.present(alertController, animated: true, completion: nil) - } - - private func batchUpdateStarted(_: [LanguageResource]) { + private func batchUpdateStarted(_: [AnyLanguageResource]) { log.info("batchUpdateStarted: InstalledLanguagesViewController") view.isUserInteractionEnabled = false navigationItem.setHidesBackButton(true, animated: true) @@ -383,12 +359,20 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie return } - toolbar.displayStatus("Updating\u{2026}", withIndicator: true) + toolbar.displayStatus(NSLocalizedString("notification-update-available", bundle: engineBundle, comment: ""), withIndicator: true) } - + private func batchUpdateCompleted(results: BatchUpdateCompletedNotification) { if let toolbar = navigationController?.toolbar as? ResourceDownloadStatusToolbar { - toolbar.displayStatus("Updates successfully downloaded!", withIndicator: false, duration: 3.0) + if results.failures.count == 0 { + let formatString = NSLocalizedString("notification-update-success", bundle: engineBundle, comment: "") + toolbar.displayStatus(String.localizedStringWithFormat(formatString, results.successes.count), withIndicator: false, duration: 3.0) + } else { + // Needs to be a short string on iPhones. + // Possible TODO: condition on "is an iPad", provide more info on iPads? + let formatString = NSLocalizedString("notification-update-failed", bundle: engineBundle, comment: "") + toolbar.displayStatus(String.localizedStringWithFormat(formatString, results.failures.count), withIndicator: false, duration: 3.0) + } } restoreNavigation() @@ -445,75 +429,30 @@ public class InstalledLanguagesViewController: UITableViewController, UIAlertVie private func showConnectionErrorAlert() { dismissActivityView() - let alertController = UIAlertController(title: "Connection Error", - message: "Could not reach Keyman server. Please try again later.", - preferredStyle: UIAlertController.Style.alert) - alertController.addAction(UIAlertAction(title: "OK", - style: UIAlertAction.Style.default, - handler: errorAcknowledgmentHandler)) - - self.present(alertController, animated: true, completion: nil) + Alerts.showDownloadErrorAlert(in: self, handler: errorAcknowledgmentHandler) } } -// MARK: - KeyboardRepositoryDelegate -extension InstalledLanguagesViewController: KeyboardRepositoryDelegate { - public func keyboardRepositoryDidFetch(_ repository: KeyboardRepository) { - if let languageDict = repository.languages { - languages = languageList(languageDict) - } - self.dismissActivityView() - self.tableView.reloadData() - if self.numberOfSections(in: self.tableView) == 0 { - self.showConnectionErrorAlert() - } - } - - public func keyboardRepository(_ repository: KeyboardRepository, didFailFetch error: Error) { - dismissActivityView() - showConnectionErrorAlert() - } - - private func languageList(_ languageDict: [String: Language]) -> [Language] { - return languageDict.values.sorted { a, b -> Bool in - a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending - } - } -} - -// MARK: - LexicalModelRepositoryDelegate - -extension InstalledLanguagesViewController: LexicalModelRepositoryDelegate { - /** lexicalModelRepositoryDidFetchList callback on successful fetching of list of lexical models for a language - * caller should wrap in DispatchQueue.main.async {} if not already on main thread - */ - public func lexicalModelRepositoryDidFetchList(_ repository: LexicalModelRepository) { - if let languageDict = repository.languages { - languages = languageList(languageDict) - } - self.dismissActivityView() - self.tableView.reloadData() - if self.numberOfSections(in: self.tableView) == 0 { - self.showConnectionErrorAlert() - } - } - - /** lexicalModelRepository didFailFetch callback on failure to fetch list of lexical models for a language - * caller should wrap in DispatchQueue.main.async {} if not already on main thread - */ - public func lexicalModelRepository(_ repository: LexicalModelRepository, didFailFetch error: Error) { - dismissActivityView() - showConnectionErrorAlert() - } +extension InstalledLanguagesViewController { @objc func addClicked(_ sender: Any) { - showAddKeyboard() - } - - func showAddKeyboard() { - navigationController?.setToolbarHidden(true, animated: true) - let vc = LanguageViewController(keyboardRep: Manager.shared.apiKeyboardRepository, modelRep: Manager.shared.apiLexicalModelRepository) - navigationController?.pushViewController(vc, animated: true) + let keyboardSearchVC = KeyboardSearchViewController(keyboardSelectionBlock: KeyboardSearchViewController.defaultDownloadClosure() { result in + switch result { + case .cancelled: + break + case .error(let error): + if let error = error { + log.error(String(describing: error)) + } + case .success(let package, let fullID): + ResourceFileManager.shared.doInstallPrompt(for: package as! KeyboardKeymanPackage, + defaultLanguageCode: fullID.languageID, + in: self.navigationController!, + withAssociators: [.lexicalModels]) + } + }) + + navigationController!.pushViewController(keyboardSearchVC, animated: true) } } diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Settings/LanguageSettingsViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/Settings/LanguageSettingsViewController.swift index 1f3ad20de7128406c98bb6b990a078ee3a7671b1..dd293966f38ef84cca6fcfcd6dd3530e8f16db08 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Settings/LanguageSettingsViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Settings/LanguageSettingsViewController.swift @@ -13,16 +13,14 @@ private let toolbarButtonTag = 100 class LanguageSettingsViewController: UITableViewController { let language: Language private var settingsArray = [[String: String]]() - private var keyboardRepository: KeyboardRepository? private var doPredictionsSwitch: UISwitch? private var doCorrectionsSwitch: UISwitch? private var doCorrectionsLabel: UILabel? private var correctionsCell: UITableViewCell? - public init(_ keyboardRepository: KeyboardRepository?, _ inLanguage: Language) { + public init(_ inLanguage: Language) { language = inLanguage - self.keyboardRepository = keyboardRepository super.init(nibName: nil, bundle: nil) } @@ -37,7 +35,8 @@ class LanguageSettingsViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() - title = "\(language.name) Settings" + let titleFormat = NSLocalizedString("menu-langsettings-title", bundle: engineBundle, comment: "") + title = String.localizedStringWithFormat(titleFormat, language.name) log.info("viewDidLoad: LanguageSettingsViewController title: \(title ?? "")") if Manager.shared.canAddNewKeyboards { @@ -193,9 +192,11 @@ class LanguageSettingsViewController: UITableViewController { var title: String switch (section) { case 0: - title = "Keyboards" + // We do NOT use a general-use "keyboards" entry because different languages have different + // pluralization rules, and it's a major assumption to assume which is preferred for general use. + title = NSLocalizedString("menu-langsettings-section-keyboards", bundle: engineBundle, comment: "") case 1: - title = "Language settings" + title = NSLocalizedString("menu-langsettings-section-settings", bundle: engineBundle, comment: "") default: title = "unknown header" } @@ -235,30 +236,21 @@ class LanguageSettingsViewController: UITableViewController { cell.accessoryType = .none switch indexPath.row { case 0: - cell.textLabel?.text = "Enable predictions" + cell.textLabel?.text = NSLocalizedString("menu-langsettings-toggle-predict", bundle: engineBundle, comment: "") case 1: doCorrectionsLabel = cell.textLabel - cell.textLabel?.text = "Enable corrections" + cell.textLabel?.text = NSLocalizedString("menu-langsettings-toggle-correct", bundle: engineBundle, comment: "") cell.textLabel?.isEnabled = !(doCorrectionsSwitch?.isHidden ?? false) case 2: - cell.textLabel?.text = "Dictionaries" + cell.textLabel?.text = NSLocalizedString("menu-langsettings-label-lexical-models", bundle: engineBundle, comment: "") cell.accessoryType = .disclosureIndicator - if let modelCt = language.lexicalModels?.count { - switch modelCt { - case 0: - cell.detailTextLabel?.text = "no dictionaries installed" - case 1: - cell.detailTextLabel?.text = "\(language.lexicalModels![0].name)" - default: - cell.detailTextLabel?.text = "\(modelCt) dictionaries installed" - } + let modelCt = language.lexicalModels?.count ?? 0 + if modelCt != 1 { + let formatString = NSLocalizedString("menu-langsettings-lexical-model-count", bundle: engineBundle, comment: "") + cell.detailTextLabel?.text = String.localizedStringWithFormat(formatString, modelCt) } else { - cell.detailTextLabel?.text = "no dictionaries installed" + cell.detailTextLabel?.text = "\(language.lexicalModels![0].name)" } - case 3: // future - cell.textLabel?.text = "Manage dictionary" - cell.accessoryType = .disclosureIndicator - cell.isUserInteractionEnabled = false default: cell.textLabel?.text = "error" @@ -308,16 +300,26 @@ class LanguageSettingsViewController: UITableViewController { } @objc func addClicked(_ sender: Any) { - showAddLanguageKeyboard() - } - - func showAddLanguageKeyboard() { - let button: UIButton? = (navigationController?.toolbar?.viewWithTag(toolbarButtonTag) as? UIButton) - button?.isEnabled = false - let vc = LanguageDetailViewController(keyboardRepository, language: language) - vc.title = "Add new \(language.name) keyboard" - navigationController?.pushViewController(vc, animated: true) + let keyboardSearchVC = KeyboardSearchViewController(languageCode: self.language.id, + keyboardSelectionBlock: KeyboardSearchViewController.defaultDownloadClosure() { result in + switch result { + case .cancelled: + break + case .error(let error): + if let error = error { + log.error(String(describing: error)) + } + case .success(let package, let fullID): + ResourceFileManager.shared.doInstallPrompt(for: package as! KeyboardKeymanPackage, + defaultLanguageCode: fullID.languageID, + in: self.navigationController!, + withAssociators: [.lexicalModels]) + } + }) + + navigationController!.pushViewController(keyboardSearchVC, animated: true) } + private func performAction(for indexPath: IndexPath) { switch indexPath.section { @@ -374,10 +376,8 @@ class LanguageSettingsViewController: UITableViewController { } let kbIndex:Int = index let thisKb = globalUserKeyboards[kbIndex] - let infoView = ResourceInfoViewController(for: thisKb) - infoView.title = thisKb.name - infoView.keyboardCount = globalUserKeyboards.count - infoView.keyboardIndex = index + let mayDelete = mayDeleteKeyboard(keyboardIndex: index, keyboardCount: globalUserKeyboards.count) + let infoView = ResourceInfoViewController(for: thisKb, mayDelete: mayDelete) infoView.isCustomKeyboard = thisKb.isCustom navigationController?.pushViewController(infoView, animated: true) } else { @@ -385,44 +385,27 @@ class LanguageSettingsViewController: UITableViewController { return } } - + + private func mayDeleteKeyboard(keyboardIndex: Int, keyboardCount: Int) -> Bool { + if !Manager.shared.canRemoveKeyboards { + return false + } + + if !Manager.shared.canRemoveDefaultKeyboard { + return keyboardIndex != 0 + } + + if keyboardIndex > 0 { + return true + } + return keyboardCount > 1 + } + func showLexicalModelsView() { //LanguageLexicalModelPickerViewController? (should show just the models for this language) let lmListView = LexicalModelPickerViewController(self.language) lmListView.language = self.language navigationController?.pushViewController(lmListView, animated: true) - } - - func showLexicalModelInfoView() { - if let lm = language.lexicalModels?[safe: 0] { - let version = lm.version - let matchingFullID = FullLexicalModelID(lexicalModelID: lm.id, languageID: language.id) - - let userData = Storage.active.userDefaults - - if let globalUserLexicalModels = userData.userLexicalModels { - if let index = globalUserLexicalModels.firstIndex(where: { $0.fullID == matchingFullID }) { - guard index < globalUserLexicalModels.count else { - return - } - let lmIndex:Int = index - let thisLm = globalUserLexicalModels[lmIndex] - let infoView = LexicalModelInfoViewController() - infoView.title = thisLm.name - infoView.lexicalModelCount = globalUserLexicalModels.count - infoView.lexicalModelIndex = index - infoView.lexicalModelID = thisLm.id - infoView.languageID = language.id - infoView.lexicalModelVersion = version ?? InstallableConstants.defaultVersion - infoView.isCustomLexicalModel = thisLm.isCustom - navigationController?.pushViewController(infoView, animated: true) - } else { - log.error("this lexical model \(matchingFullID) not found among language's installed lexical model!") - } - } else { - log.error("no lexical models in the global models list!") - } - } } /* diff --git a/ios/engine/KMEI/KeymanEngine/Classes/Settings/SettingsViewController.swift b/ios/engine/KMEI/KeymanEngine/Classes/Settings/SettingsViewController.swift index 468a7f7110bec9029f7523c53e740f2348f8049c..91c5f099ac741029c74599a67c45e390c99aab2c 100644 --- a/ios/engine/KMEI/KeymanEngine/Classes/Settings/SettingsViewController.swift +++ b/ios/engine/KMEI/KeymanEngine/Classes/Settings/SettingsViewController.swift @@ -22,8 +22,8 @@ open class SettingsViewController: UITableViewController { override open func viewDidLoad() { super.viewDidLoad() - title = "Keyman Settings" - let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, + title = NSLocalizedString("menu-settings-title", bundle: engineBundle, comment: "") + let doneButton = UIBarButtonItem(title: NSLocalizedString("Done", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(self.doneClicked)) navigationItem.leftBarButtonItem = doneButton @@ -55,19 +55,19 @@ open class SettingsViewController: UITableViewController { itemsArray = [[String: String]]() itemsArray.append([ - "title": "Installed Languages", + "title": NSLocalizedString("menu-installed-languages-title", bundle: engineBundle, comment: ""), "subtitle": "0", //count of installed languages as string "reuseid" : "languages" ]) itemsArray.append([ - "title": "Show Banner", + "title": NSLocalizedString("menu-settings-show-banner", bundle: engineBundle, comment: ""), "subtitle": "", "reuseid" : "showbanner" ]) itemsArray.append([ - "title": "Show 'Get Started' at startup", + "title": NSLocalizedString("menu-settings-startup-get-started", bundle: engineBundle, comment: ""), "subtitle": "", "reuseid" : "showgetstarted" ]) @@ -75,8 +75,8 @@ open class SettingsViewController: UITableViewController { // The iOS Files app is only available with 11.0+. if #available(iOS 11.0, *) { itemsArray.append([ - "title": "Install From File", - "subtitle": "Browse for .kmp files", + "title": NSLocalizedString("menu-settings-install-from-file", bundle: engineBundle, comment: ""), + "subtitle": NSLocalizedString("menu-settings-install-from-file-description", bundle: engineBundle, comment: ""), "reuseid" : "installfile" ]) } @@ -342,18 +342,15 @@ open class SettingsViewController: UITableViewController { } userLanguages = keyboardLanguages - if 1 == userLanguages.count { - itemsArray[0]["subtitle"] = "one language installed" - } else { - itemsArray[0]["subtitle"] = "\(userLanguages.count) languages installed" - } + let formatString = NSLocalizedString("settings-languages-installed-count", bundle: engineBundle, comment: "") + itemsArray[0]["subtitle"] = String.localizedStringWithFormat(formatString, userLanguages.count) tableView.reloadData() } public func setIsDoneButtonEnabled(_ nc: UINavigationController, _ value: Bool) { let doneOrCancel = value if doneOrCancel { - let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, + let doneButton = UIBarButtonItem(title: NSLocalizedString("command-done", bundle: engineBundle, comment: ""), style: .plain, target: self, action: nil /* #selector(self.doneClicked) */ ) nc.navigationItem.leftBarButtonItem = doneButton } else { diff --git a/ios/engine/KMEI/KeymanEngine/Classes/UniversalLinks.swift b/ios/engine/KMEI/KeymanEngine/Classes/UniversalLinks.swift new file mode 100644 index 0000000000000000000000000000000000000000..0e82bff10be12c79c143cba040675b4243780903 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/UniversalLinks.swift @@ -0,0 +1,45 @@ +// +// UniversalLinks.swift +// KeymanEngine +// +// Created by Joshua Horton on 7/27/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +public class UniversalLinks { + public struct ParsedKeyboardInstallLink { + public let keyboard_id: String + public let lang_id: String? + + public var packageKey: KeymanPackage.Key { + return KeymanPackage.Key(id: keyboard_id, type: .keyboard) + } + } + + private static let KEYBOARD_INSTALL_LINK_REGEX = try! NSRegularExpression(pattern: "^http(?:s)?:\\/\\/[^\\/]+\\/keyboards\\/install\\/([^?\\/]+)(?:\\?(.+))?$") + + public static func tryParseKeyboardInstallLink(_ link: URL) -> ParsedKeyboardInstallLink? { + let linkString = link.absoluteString + + // If it matches the format for the Keyboard Universal Link URL Pattern... + // (see https://docs.google.com/document/d/1rhgMeJlCdXCi6ohPb_CuyZd0PZMoSzMqGpv1A8cMFHY/edit?ts=5f11cb13#heading=h.qw7pas2adckj) + if let match = KEYBOARD_INSTALL_LINK_REGEX.firstMatch(in: linkString, + options: [], + range: NSRange(location: 0, length: linkString.utf16.count)) { + let keyboard_id_range = Range(match.range(at: 1), in: linkString)! + let keyboard_id = String(linkString[keyboard_id_range]) + + var lang_id: String? = nil + let urlComponents = URLComponents(string: linkString)! + if let lang_id_component = urlComponents.queryItems?.first(where: { $0.name == "bcp47" }) { + lang_id = lang_id_component.value + } + + return ParsedKeyboardInstallLink(keyboard_id: keyboard_id, lang_id: lang_id) + } else { + return nil + } + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPFile.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPFile.swift new file mode 100644 index 0000000000000000000000000000000000000000..ba39e34308599efcc78187efbb298608948833c0 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPFile.swift @@ -0,0 +1,26 @@ +// +// KMPFile.swift +// KeymanEngine +// +// Created by Joshua Horton on 6/1/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +struct KMPFile: Codable { + var name: String + var description: String + + enum CodingKeys: String, CodingKey { + case name + case description + // case copyLocation // deliberately omitted + } + + init(_ name: String, description: String? = nil) { + let desc = description ?? name + self.name = name + self.description = desc + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPInfo.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPInfo.swift new file mode 100644 index 0000000000000000000000000000000000000000..f6b396d88f43e192bb2e6cdd912a859e25eae06e --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPInfo.swift @@ -0,0 +1,47 @@ +// +// KMPInfo.swift +// KeymanEngine +// +// Created by Joshua Horton on 6/2/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +class KMPInfoItem: Codable { + var description: String + var url: String? + + init(description: String, url: String? = nil) { + self.description = description + self.url = url + } +} + +class KMPInfo: Codable { + static let DEFAULT_VERSION = KMPInfoItem(description: "1.0.0") + static let AUTOGEN_VERSION = KMPInfoItem(description: "0.0.0") + + var name: KMPInfoItem? = nil + var author: KMPInfoItem? = nil + var copyright: KMPInfoItem? = nil + var website: KMPInfoItem? = nil + // If a package doesn't have this set, we default to 1.0.0. + var version: KMPInfoItem? = KMPInfo.DEFAULT_VERSION + + enum CodingKeys: String, CodingKey { + case name + case author + case copyright + case website + case version + } + + convenience init(version: String) { + self.init(version: KMPInfoItem(description: version)) + } + + init(version: KMPInfoItem) { + self.version = version + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPKeyboard.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPKeyboard.swift new file mode 100644 index 0000000000000000000000000000000000000000..75e54f26aa2d416d018e386541001cf726968233 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPKeyboard.swift @@ -0,0 +1,122 @@ +// +// KMPKeyboard.swift +// KeymanEngine +// +// Created by Jacob Bullock on 2/16/18. +// Copyright © 2018 SIL International. All rights reserved. +// + +import Foundation + +class KMPKeyboard: Codable, KMPResource { + public var name: String + public var keyboardId: String + public var packageId: String? + public var version: String + public var osk: String? + public var font: String? + public var isRTL: Bool = false + // Technically, the schema says that this doesn't have to be specified. + // However, it's a requirement for KeymanEngine for iOS. + public var languages: [KMPLanguage] + + enum CodingKeys: String, CodingKey { + case name + case keyboardId = "id" + case version + case osk = "oskFont" + case font = "displayFont" + case isRTL = "rtl" + case languages + } + + internal required init?(from keyboard: InstallableKeyboard) { + self.name = keyboard.name + self.keyboardId = keyboard.id + self.packageId = keyboard.packageID ?? keyboard.id + self.version = keyboard.version + self.isRTL = keyboard.isRTL + + self.font = keyboard.font?.source[0] + self.osk = keyboard.oskFont?.source[0] + + self.languages = [KMPLanguage(name: keyboard.languageName, languageId: keyboard.languageID)] + } + + required public init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + + name = try values.decode(String.self, forKey: .name) + keyboardId = try values.decode(String.self, forKey: .keyboardId) + version = try values.decode(String.self, forKey: .version) + osk = try values.decodeIfPresent(String.self, forKey: .osk) + font = try values.decodeIfPresent(String.self, forKey: .font) + isRTL = try values.decodeIfPresent(Bool.self, forKey: .isRTL) ?? false + languages = try values.decode([KMPLanguage].self, forKey: .languages) + } + + func hasMatchingMetadata(for resource: InstallableKeyboard, ignoreLanguage: Bool = false, ignoreVersion: Bool = true) -> Bool { + if id != resource.id { + return false + } else if !ignoreVersion, version != resource.version { + return false + } + + if !ignoreLanguage { + let resourceMetadata = KMPKeyboard(from: resource)! + return languages.contains(where: { language in + return language.languageId == resourceMetadata.languages[0].languageId + }) + } + + return true + } + + internal var installableKeyboards: [InstallableKeyboard] { + var installableKeyboards : [InstallableKeyboard] = [] + + for language in self.languages { + let keyboard = InstallableKeyboard(from: self, packageID: packageId!, lgCode: language.languageId)! + installableKeyboards.append( keyboard ) + } + + return installableKeyboards + } + + // Needed to properly support AnyKMPResource.installableResources + // because of weird, weird Swift rules. + public var typedInstallableResources: [InstallableKeyboard] { + return installableKeyboards + } + + // Provides our class's method of the same signature, but with + // the local type signature we know is available. + public var installableResources: [InstallableKeyboard] { + return installableKeyboards + } + + public var displayFont: Font? { + if let f = font { + return Font(filename: f) + } + return nil + } + + public var oskFont: Font? { + if let f = osk { + return Font(filename: f) + } + return nil + } + + public var isValid: Bool { + // Ensures that our 'optional' members are properly instantiated. + // Any file-based checks will be performed by the object's owner, + // which knows the containing package's root folder. + return installableKeyboards.count > 0 && self.languages.count > 0 + } + + public var id: String { + return keyboardId + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPLanguage.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPLanguage.swift new file mode 100644 index 0000000000000000000000000000000000000000..9f4651f9797fbcb84ad7bb4e34fcd75111bdd116 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPLanguage.swift @@ -0,0 +1,43 @@ +// +// KMPLanguage.swift +// KeymanEngine +// +// Created via refactor by Joshua Horton on 6/1/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +struct KMPLanguage: Codable { + public var name: String + public var languageId: String + + enum CodingKeys: String, CodingKey { + case name + case languageId = "id" + } + + public init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + + name = try values.decode(String.self, forKey: .name) + languageId = try values.decode(String.self, forKey: .languageId).lowercased() + } + + public init?(from resource: Resource) { + if let kbd = resource as? InstallableKeyboard { + self.name = kbd.languageName + self.languageId = kbd.languageID + } else if let lm = resource as? InstallableLexicalModel { + self.name = lm.languageID // We never stored the language name for lexical models. + self.languageId = lm.languageID + } else { + return nil + } + } + + public init(name: String, languageId: String) { + self.name = name + self.languageId = languageId + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPLexicalModel.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPLexicalModel.swift new file mode 100644 index 0000000000000000000000000000000000000000..d63f451e5654da44191abdd0e89376d2fdddad98 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPLexicalModel.swift @@ -0,0 +1,110 @@ +// +// KMPLexicalModel.swift +// KeymanEngine +// +// Created by Randy Boring on 3/12/19. +// Copyright © 2019 SIL International. All rights reserved. +// + +import Foundation + +class KMPLexicalModel: Codable, KMPResource { + public var name: String + public var lexicalModelId: String + public var packageId: String? + public var version: String? + public var isRTL: Bool = false + public var languages: [KMPLanguage] + + enum CodingKeys: String, CodingKey { + case name + case lexicalModelId = "id" + case version + case isRTL = "rtl" + case languages + } + + internal required init?(from lexicalModel: InstallableLexicalModel) { + + self.name = lexicalModel.name + self.lexicalModelId = lexicalModel.id + self.version = lexicalModel.version + self.packageId = lexicalModel.packageID ?? lexicalModel.id + + // InstallableLexicalModel doesn't store the language name, so we use the id as a fill-in. + // The 'name' part isn't used for matching, anyway. + self.languages = [KMPLanguage(name: lexicalModel.languageID, languageId: lexicalModel.languageID)] + } + + required public init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + + name = try values.decode(String.self, forKey: .name) + lexicalModelId = try values.decode(String.self, forKey: .lexicalModelId) + // Our schema says that this field is optional for lexical models. + // In these cases, the version should probably be set to the package's version... + // but this constructor lacks access. We'll let the owning Package instance handle this. + version = try values.decodeIfPresent(String.self, forKey: .version) + isRTL = try values.decodeIfPresent(Bool.self, forKey: .isRTL) ?? false + languages = try values.decode([KMPLanguage].self, forKey: .languages) + } + + /** This function will set the value for version only when a lexical model doesn't have a value for it specified directly in its definition. + */ + public func setNilVersion(to version: String) { + self.version = self.version ?? version + } + + func hasMatchingMetadata(for resource: InstallableLexicalModel, ignoreLanguage: Bool = false, ignoreVersion: Bool = true) -> Bool { + if id != resource.id { + return false + } else if !ignoreVersion, version != resource.version { + return false + } + + if !ignoreLanguage { + let resourceMetadata = KMPLexicalModel(from: resource)! + return languages.contains(where: { language in + return language.languageId == resourceMetadata.languages[0].languageId + }) + } + + return true + } + + internal var installableLexicalModels: [InstallableLexicalModel] { + var installableLexicalModels : [InstallableLexicalModel] = [] + + for language in self.languages { + let model = InstallableLexicalModel(from: self, packageID: packageId!, lgCode: language.languageId)! + installableLexicalModels.append( model ) + } + + return installableLexicalModels + } + + // Needed to properly support AnyKMPResource.installableResources + // because of weird, weird Swift rules. + public var typedInstallableResources: [InstallableLexicalModel] { + return installableLexicalModels + } + + // Provides our class's method of the same signature, but with + // the local type signature we know is available. + public var installableResources: [InstallableLexicalModel] { + return installableLexicalModels + } + + public var isValid: Bool { + // Ensures that our 'optional' members are properly instantiated. + // Any file-based checks will be performed by the object's owner, + // which knows the containing package's root folder. + return installableLexicalModels.count > 0 + && self.languages.count > 0 + } + + public var id: String { + return lexicalModelId + } +} + diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPMetadata.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPMetadata.swift new file mode 100644 index 0000000000000000000000000000000000000000..767d216baeaab83c829d9696b4c82ae69a343379 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPMetadata.swift @@ -0,0 +1,121 @@ +// +// KMPInfo.swift +// KeymanEngine +// +// Created by Joshua Horton on 6/2/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +/** + * This class serializes to and deserializes from JSON following the schema found here for every package's kmp.json: + * - https://api.keyman.com/schemas/package/1.1.0/package.json + * + * It should be kept updated to match the latest schema version whenever updates occur. + * + * Documentation link: https://help.keyman.com/developer/current-version/reference/file-types/metadata + */ +class KMPMetadata: Codable { + var system: KMPSystem + var options: KMPOptions + var info: KMPInfo? + var files: [KMPFile]? + var keyboards: [KMPKeyboard]? + var lexicalModels: [KMPLexicalModel]? + + enum CodingKeys: String, CodingKey { + case system + case options + case info + case files + case keyboards + case lexicalModels + // The following reflect members that may exist, according to our schema, + // but that are currently unused by Keyman for iOS. + // case strings + } + + enum PackageType: String { + case Keyboard + case LexicalModel + case Unsupported + } + + /** + * This constructor is designed for use in resource migration needed for the 13.0 -> 14.0 + * cloud resource -> KMP-backed transition. The result of this constructor is designed to provide + * a kmp.json "wrapper" for pre-existing cloud resources as if it had come from an actual KMP. + * + * As this is constructed from a single instance of LanguageResource, only + * one language pairing will exist in the newly-constructed KMPMetadata instance. + * + * Use of KMPResource.hasMatchingMetadata may help to de-duplicate resources during + * the migration process. + */ + internal init(from resource: AnyLanguageResource, packageId: String? = nil) { + // First, the standard defaults. + options = KMPOptions() + keyboards = nil + lexicalModels = nil + + // If we're constructing one from scratch, set to the absolute minimal version. + // This will automatically signal that the 'package' needs to be updated. + info = KMPInfo(version: KMPInfo.AUTOGEN_VERSION) + + // Now to process the resource. + var fileSet = [ KMPFile(resource.sourceFilename) ] + resource.fonts.forEach {font in + fileSet.append(KMPFile(font.source[0])) + } + files = fileSet + + if let keyboard = resource as? InstallableKeyboard { + keyboards = [KMPKeyboard(from: keyboard)!] + keyboards![0].packageId = packageId + system = KMPSystem(forPackageType: .Keyboard)! + } else if let lexicalModel = resource as? InstallableLexicalModel { + lexicalModels = [KMPLexicalModel(from: lexicalModel)!] + lexicalModels![0].packageId = packageId + system = KMPSystem(forPackageType: .LexicalModel)! + } else { + fatalError("Cannot utilize unexpected subclass of LanguageResource") + } + } + + var isValid: Bool { + if keyboards != nil && lexicalModels != nil { + return false + } + + if keyboards == nil && lexicalModels == nil { + return false + } + + return true + } + + var packageType: PackageType { + if !isValid { + return .Unsupported + } else if keyboards != nil { + return .Keyboard + } else if lexicalModels != nil { + return .LexicalModel + } else { + return .Unsupported + } + } + + var version: String? { + return self.info?.version?.description + } + + /** + * Notes whether or not this KMPMetadata was autogenerated by KeymanEngine as part of + * a version migration op. + */ + var isAutogeneratedWrapper: Bool { + return version == KMPInfo.AUTOGEN_VERSION.description + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPOptions.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPOptions.swift new file mode 100644 index 0000000000000000000000000000000000000000..4fe70f3d2c5fd76b46f1e51408f108d57fd3ae8e --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPOptions.swift @@ -0,0 +1,21 @@ +// +// KMPOptions.swift +// KeymanEngine +// +// Created by Joshua Horton on 6/1/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +struct KMPOptions: Codable { + public var readmeFile: String? = nil + public var graphicFile: String? = nil + + // We do this so that we can safely ignore any other entries. + // iOS cares not for .msis or 'executeProgram'. + enum CodingKeys: String, CodingKey { + case readmeFile + case graphicFile + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPResource.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPResource.swift new file mode 100644 index 0000000000000000000000000000000000000000..a81d609481943a3b1fa6171bd24713c2be61b7ec --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPResource.swift @@ -0,0 +1,37 @@ +// +// KMPResource.swift +// KeymanEngine +// +// Created by Joshua Horton on 6/3/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +internal protocol AnyKMPResource { + // Returns the represented resource's ID. + var id: String { get } + var languages: [KMPLanguage] { get set } // set is for adding languages during 13.0 -> 14.0 migration + var installableResources: [AnyLanguageResource] { get } +} + +protocol KMPResource: AnyKMPResource { + associatedtype LanguageResourceType: KMPInitializableLanguageResource where LanguageResourceType.Metadata == Self + + // Used to convert old cloud resources into the extracted KMP format for 14.0+ file management. + init?(from resource: LanguageResourceType) + + var typedInstallableResources: [LanguageResourceType] { get } + + /** + * Designed to facilitate de-duplication of KMPResources when migrating cloud resources into the extracted KMP format + * for 14.0+ file management. + */ + func hasMatchingMetadata(for resource: LanguageResourceType, ignoreLanguage: Bool, ignoreVersion: Bool) -> Bool +} + +extension KMPResource { + var installableResources: [AnyLanguageResource] { + return typedInstallableResources + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPSystem.swift b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPSystem.swift new file mode 100644 index 0000000000000000000000000000000000000000..34c11bef8bb7fbcddc6427de6462ec96d5d49cc5 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPSystem.swift @@ -0,0 +1,34 @@ +// +// KMPSystem.swift +// KeymanEngine +// +// Created by Joshua Horton on 6/1/20. +// Copyright © 2020 SIL International. All rights reserved. +// + +import Foundation + +struct KMPSystem: Codable { + public var keymanDeveloperVersion: String? + public var fileVersion: String + + enum CodingKeys: String, CodingKey { + case keymanDeveloperVersion + case fileVersion + } + + init?(forPackageType packageType: KMPMetadata.PackageType) { + keymanDeveloperVersion = nil + + switch packageType { + case .Keyboard: + fileVersion = "7.0" + return + case .LexicalModel: + fileVersion = "12.0" + return + default: + return nil + } + } +} diff --git a/ios/engine/KMEI/KeymanEngine/Info.plist b/ios/engine/KMEI/KeymanEngine/Info.plist index 60771e899bfe9b32bde2b724aaddfb5a4c28aadb..44bc2c4e4e717d530ab07ea78cde90a625bc254c 100644 --- a/ios/engine/KMEI/KeymanEngine/Info.plist +++ b/ios/engine/KMEI/KeymanEngine/Info.plist @@ -4,6 +4,8 @@ KeymanVersionWithTag 10.0.0-local + KeymanVersionEnvironment + local CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleDisplayName diff --git a/ios/engine/KMEI/KeymanEngine/en.lproj/Localizable.strings b/ios/engine/KMEI/KeymanEngine/en.lproj/Localizable.strings new file mode 100644 index 0000000000000000000000000000000000000000..0b930d2121070ba143cfea5c0903e418f4f14546 Binary files /dev/null and b/ios/engine/KMEI/KeymanEngine/en.lproj/Localizable.strings differ diff --git a/ios/engine/KMEI/KeymanEngine/en.lproj/Localizable.stringsdict b/ios/engine/KMEI/KeymanEngine/en.lproj/Localizable.stringsdict new file mode 100644 index 0000000000000000000000000000000000000000..17aa9c21d2d738e5f2c986971180f5a3432e97f0 --- /dev/null +++ b/ios/engine/KMEI/KeymanEngine/en.lproj/Localizable.stringsdict @@ -0,0 +1,128 @@ + + + + + menu-langsettings-lexical-model-count + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + u + zero + No dictionaries installed + one + %u dictionary installed + other + %u dictionaries installed + + + notification-update-failed + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + u + one + %u update failed + other + %u updates failed + + + notification-update-success + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + u + one + %u update successful + other + %u updates successful + + + settings-keyboards-installed-count + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + u + zero + No keyboards installed + one + %u keyboard installed + other + %u keyboards installed + + + settings-languages-installed-count + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + u + zero + No languages installed + one + %u language installed + other + %u languages installed + + + package-default-found-keyboards + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + u + zero + Found no keyboards in package + one + Found %u keyboard in package: + other + Found %u keyboards in package: + + + package-default-found-lexical-models + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + u + zero + Found no dictionaries in package + one + Found %u dictionary in package: + other + Found %u dictionaries in package: + + + + diff --git a/ios/engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/keyboard.html b/ios/engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/keyboard.html index f5cfc852c3f9e1acc550a6f1f106ede47b338d0b..bd180bb558a966ff52e03d1c8e1b96a136c52a25 100644 --- a/ios/engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/keyboard.html +++ b/ios/engine/KMEI/KeymanEngine/resources/Keyman.bundle/Contents/Resources/keyboard.html @@ -4,6 +4,7 @@ Keyman + @@ -65,8 +65,8 @@

-
-
+
+
- +
+ + back + 1 + + javascript:goBack() + 70px + +
- + keyman:footer_cancel 70px diff --git a/windows/src/desktop/kmshell/xml/elements.xsl b/windows/src/desktop/kmshell/xml/elements.xsl index b9bb85b073049ca56b57d0602ee3a40e36fabf79..2e70d5da33cd5bcbdde6146618215c37b89d3192 100644 --- a/windows/src/desktop/kmshell/xml/elements.xsl +++ b/windows/src/desktop/kmshell/xml/elements.xsl @@ -6,22 +6,23 @@ - + + - + - - - - + @@ -61,6 +62,7 @@ + @@ -73,21 +75,20 @@ button + disabled button_ location.href=""; font-size: 12px; - height: 25px; + height: 25px; display: inline-block; text-align: center; width: ; margin-right: 8px; vertical-align: top; - - shield.png - + @@ -99,6 +100,7 @@ button + disabled button_ location.href=""; @@ -115,7 +117,7 @@ - - + @@ -182,5 +184,5 @@ - + diff --git a/windows/src/desktop/kmshell/xml/globe.png b/windows/src/desktop/kmshell/xml/globe.png new file mode 100644 index 0000000000000000000000000000000000000000..ceb2d60db1bcfe6e126d00b35c8c4aec962abacb Binary files /dev/null and b/windows/src/desktop/kmshell/xml/globe.png differ diff --git a/windows/src/desktop/kmshell/xml/help.xsl b/windows/src/desktop/kmshell/xml/help.xsl index d29ad6bdca2e2bee6d74cff8790d33139ed53cc9..d3287a455708f216e8089e110b6a1cc70cd8e7e1 100644 --- a/windows/src/desktop/kmshell/xml/help.xsl +++ b/windows/src/desktop/kmshell/xml/help.xsl @@ -4,23 +4,23 @@ - + - - - <xsl:value-of select="$locale/String[@Id='S_HelpTitle']" /> - config.css + + + <xsl:value-of select="$locale/string[@name='S_HelpTitle']" /> + @@ -53,14 +53,9 @@
@@ -71,20 +66,20 @@