From efdb1c24bb549f3b50f0827360ff5ee5963a54ab Mon Sep 17 00:00:00 2001 From: nicolas Date: Sat, 21 Nov 2026 02:13:02 +0100 Subject: [PATCH] feat: dictionary downloads via external Dictionnary app + next-word prediction The keyboard app keeps no INTERNET permission: a new :dictionnary module (org.fossify.dictionnary) downloads word frequency lists (HermitDave/ FrequencyWords, converted on the fly to wordfreq JSON) and shares them through an exported ContentProvider guarded by a signature permission. The keyboard copies the files locally into filesDir/dictionaries and the SpellChecker loads them from that local copy. - keyboard language now follows the system locale by default; at launch the app proposes to download the dictionary of the current language, or to install the Dictionnary app when it is missing - SettingsActivity: propose/install Dictionnary when enabling suggestions or auto-correct, avoid relaunching a failed download in a loop - DictionaryProvider: also match files/*/* URIs so copying a dictionary file through its content URI works - fix direct-boot crash: theme colors are read through the device-protected storage context - after a space, the most probable next words are shown in the suggestion strip before the first letter is typed, and chain after each applied suggestion (the applied word is excluded) Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- app/src/main/AndroidManifest.xml | 13 + .../keyboard/activities/MainActivity.kt | 58 ++++ .../keyboard/activities/SettingsActivity.kt | 147 ++++++++++ .../keyboard/extensions/KeyboardThemeExt.kt | 8 +- .../org/fossify/keyboard/helpers/Config.kt | 49 +++- .../org/fossify/keyboard/helpers/Constants.kt | 17 ++ .../keyboard/helpers/DictionaryLanguages.kt | 44 +++ .../keyboard/helpers/DictionnaryClient.kt | 253 ++++++++++++++++++ .../fossify/keyboard/helpers/SpellChecker.kt | 201 ++++++++++++++ .../keyboard/services/SimpleKeyboardIME.kt | 237 +++++++++++++++- app/src/main/res/layout/activity_settings.xml | 53 ++++ .../res/layout/keyboard_view_keyboard.xml | 59 +++- app/src/main/res/values/strings.xml | 13 + dictionnary/.gitignore | 1 + dictionnary/build.gradle.kts | 56 ++++ dictionnary/proguard-rules.pro | 3 + dictionnary/src/debug/AndroidManifest.xml | 14 + dictionnary/src/main/AndroidManifest.xml | 42 +++ .../kotlin/org/fossify/dictionnary/App.kt | 15 ++ .../dictionnary/activities/MainActivity.kt | 110 ++++++++ .../fossify/dictionnary/helpers/Constants.kt | 87 ++++++ .../helpers/DictionaryDownloader.kt | 135 ++++++++++ .../providers/DictionaryProvider.kt | 153 +++++++++++ .../src/main/res/layout/activity_main.xml | 41 +++ dictionnary/src/main/res/values/strings.xml | 10 + settings.gradle.kts | 1 + 26 files changed, 1806 insertions(+), 14 deletions(-) create mode 100644 app/src/main/kotlin/org/fossify/keyboard/helpers/DictionaryLanguages.kt create mode 100644 app/src/main/kotlin/org/fossify/keyboard/helpers/DictionnaryClient.kt create mode 100644 app/src/main/kotlin/org/fossify/keyboard/helpers/SpellChecker.kt create mode 100644 dictionnary/.gitignore create mode 100644 dictionnary/build.gradle.kts create mode 100644 dictionnary/proguard-rules.pro create mode 100644 dictionnary/src/debug/AndroidManifest.xml create mode 100644 dictionnary/src/main/AndroidManifest.xml create mode 100644 dictionnary/src/main/kotlin/org/fossify/dictionnary/App.kt create mode 100644 dictionnary/src/main/kotlin/org/fossify/dictionnary/activities/MainActivity.kt create mode 100644 dictionnary/src/main/kotlin/org/fossify/dictionnary/helpers/Constants.kt create mode 100644 dictionnary/src/main/kotlin/org/fossify/dictionnary/helpers/DictionaryDownloader.kt create mode 100644 dictionnary/src/main/kotlin/org/fossify/dictionnary/providers/DictionaryProvider.kt create mode 100644 dictionnary/src/main/res/layout/activity_main.xml create mode 100644 dictionnary/src/main/res/values/strings.xml diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index dff7fb103..cf09db0dd 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -11,6 +11,19 @@ android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" /> + + + + + + + + + + + + { + val lang = resultData?.getStringExtra(DICTIONNARY_EXTRA_LANG) + val file = DictionnaryClient.handleDownloadResult(this, resultCode, resultData) + if (file != null) { + toast(getString(R.string.dictionary_downloaded_ok, lang.orEmpty())) + } else if (lang != null) { + toast(getString(R.string.dictionary_download_failed, lang)) + } + } + + REQUEST_PICK_DICTIONNARY_APK -> { + if (resultCode == RESULT_OK) { + resultData?.data?.let { DictionnaryClient.installApkFromUri(this, it) } + } + } + } + } + private fun setupOptionsMenu() { binding.mainToolbar.setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { diff --git a/app/src/main/kotlin/org/fossify/keyboard/activities/SettingsActivity.kt b/app/src/main/kotlin/org/fossify/keyboard/activities/SettingsActivity.kt index 3d0576450..b41eaa3b0 100644 --- a/app/src/main/kotlin/org/fossify/keyboard/activities/SettingsActivity.kt +++ b/app/src/main/kotlin/org/fossify/keyboard/activities/SettingsActivity.kt @@ -24,18 +24,33 @@ import org.fossify.keyboard.helpers.KEYBOARD_HEIGHT_100_PERCENT import org.fossify.keyboard.helpers.KEYBOARD_HEIGHT_120_PERCENT import org.fossify.keyboard.helpers.KEYBOARD_HEIGHT_140_PERCENT import org.fossify.keyboard.helpers.KEYBOARD_HEIGHT_160_PERCENT +import org.fossify.keyboard.helpers.DEFAULT_DICTIONARY_LANG +import org.fossify.keyboard.helpers.DICTIONNARY_EXTRA_LANG +import org.fossify.keyboard.helpers.DictionnaryClient import org.fossify.keyboard.helpers.KEYBOARD_HEIGHT_70_PERCENT import org.fossify.keyboard.helpers.KEYBOARD_HEIGHT_80_PERCENT import org.fossify.keyboard.helpers.KEYBOARD_HEIGHT_90_PERCENT import org.fossify.keyboard.helpers.SOUND_ALWAYS import org.fossify.keyboard.helpers.SOUND_NONE import org.fossify.keyboard.helpers.SOUND_SYSTEM +import org.fossify.keyboard.helpers.dictionaryLangForKeyboardLanguage import java.util.Locale import kotlin.system.exitProcess class SettingsActivity : SimpleActivity() { private val binding by viewBinding(ActivitySettingsBinding::inflate) + companion object { + private const val REQUEST_DOWNLOAD_DICTIONARY = 1001 + private val REQUEST_PICK_DICTIONNARY_APK = DictionnaryClient.REQUEST_PICK_DICTIONNARY_APK + } + + private var installProposalShown = false + + // languages a download was already attempted for during this settings visit, so a failing + // download is not relaunched in a loop from onActivityResult + private val dictionaryDownloadAttempts = mutableSetOf() + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) @@ -66,7 +81,11 @@ class SettingsActivity : SimpleActivity() { setupShowClipboardContent() setupSentencesCapitalization() setupShowNumbersRow() + setupShowSuggestions() + setupAutoCorrect() + setupDictionnaryStatus() setupVoiceInputMethod() + maybeProposeDictionnaryInstall() binding.apply { updateTextColors(settingsNestedScrollview) @@ -186,11 +205,113 @@ class SettingsActivity : SimpleActivity() { settingsManageKeyboardLanguagesHolder.setOnClickListener { ManageKeyboardLanguagesDialog(this@SettingsActivity) { settingsKeyboardLanguage.text = getKeyboardLanguageText(config.keyboardLanguage) + ensureDictionariesForSelectedLanguages() } } } } + /** + * For every selected keyboard language that has a dictionary but no local copy yet, + * launches the Dictionnary app to download it (or proposes to install that app). + */ + private fun ensureDictionariesForSelectedLanguages() { + val missingLangs = config.selectedLanguages + .mapNotNull { dictionaryLangForKeyboardLanguage(it) } + .distinct() + .filter { !DictionnaryClient.isLocalDictionaryAvailable(this, it) } + if (missingLangs.isNotEmpty()) { + ensureDictionary(missingLangs.first()) + } + } + + private fun ensureDictionaryForCurrentLanguage() { + val lang = dictionaryLangForKeyboardLanguage(config.keyboardLanguage) ?: return + if (!DictionnaryClient.isLocalDictionaryAvailable(this, lang)) { + ensureDictionary(lang) + } + } + + private fun ensureDictionary(lang: String) { + if (!dictionaryDownloadAttempts.add(lang)) { + return + } + if (DictionnaryClient.isDictionnaryInstalled(this)) { + DictionnaryClient.launchDictionaryDownload(this, lang, REQUEST_DOWNLOAD_DICTIONARY) + } else { + DictionnaryClient.proposeInstallDictionnary(this, lang, REQUEST_PICK_DICTIONNARY_APK) + } + } + + /** settings row showing whether the Dictionnary app is installed, tap to install/open it */ + private fun setupDictionnaryStatus() { + binding.apply { + val installed = DictionnaryClient.isDictionnaryInstalled(this@SettingsActivity) + settingsDictionnaryValue.text = getString( + if (installed) R.string.dictionnary_installed else R.string.dictionnary_not_installed + ) + settingsDictionnaryHolder.setOnClickListener { + val lang = dictionaryLangForKeyboardLanguage(config.keyboardLanguage) + when { + !installed -> { + if (lang != null) { + DictionnaryClient.proposeInstallDictionnary(this@SettingsActivity, lang, REQUEST_PICK_DICTIONNARY_APK) + } else { + DictionnaryClient.proposeInstallDictionnary(this@SettingsActivity, DEFAULT_DICTIONARY_LANG, REQUEST_PICK_DICTIONNARY_APK) + } + } + + lang != null && !DictionnaryClient.isLocalDictionaryAvailable(this@SettingsActivity, lang) -> + ensureDictionary(lang) + + else -> DictionnaryClient.openDictionnaryApp(this@SettingsActivity) + } + } + } + } + + /** + * If suggestions or auto-correct are enabled but the dictionary is missing and the + * Dictionnary app is not installed, propose to install it (once per settings visit). + */ + private fun maybeProposeDictionnaryInstall() { + if (installProposalShown) { + return + } + if (!config.showSuggestions && !config.autoCorrectOnSpace) { + return + } + val lang = dictionaryLangForKeyboardLanguage(config.keyboardLanguage) ?: return + if (DictionnaryClient.isLocalDictionaryAvailable(this, lang)) { + return + } + if (DictionnaryClient.isDictionnaryInstalled(this)) { + return + } + installProposalShown = true + DictionnaryClient.proposeInstallDictionnary(this, lang, REQUEST_PICK_DICTIONNARY_APK) + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { + super.onActivityResult(requestCode, resultCode, resultData) + if (requestCode == REQUEST_DOWNLOAD_DICTIONARY) { + val lang = resultData?.getStringExtra(DICTIONNARY_EXTRA_LANG) + val file = DictionnaryClient.handleDownloadResult(this, resultCode, resultData) + if (file != null) { + toast(getString(R.string.dictionary_downloaded_ok, lang.orEmpty())) + } else if (lang != null) { + toast(getString(R.string.dictionary_download_failed, lang)) + } + // continue with the other missing languages, if any + ensureDictionariesForSelectedLanguages() + } else if (requestCode == REQUEST_PICK_DICTIONNARY_APK && resultCode == RESULT_OK) { + resultData?.data?.let { + // hand the picked APK to the system package installer + DictionnaryClient.installApkFromUri(this, it) + } + } + } + private fun setupKeyboardLanguage() { binding.apply { settingsKeyboardLanguage.text = getKeyboardLanguageText(config.keyboardLanguage) @@ -310,6 +431,32 @@ class SettingsActivity : SimpleActivity() { } } + private fun setupShowSuggestions() { + binding.apply { + settingsShowSuggestions.isChecked = config.showSuggestions + settingsShowSuggestionsHolder.setOnClickListener { + settingsShowSuggestions.toggle() + config.showSuggestions = settingsShowSuggestions.isChecked + if (settingsShowSuggestions.isChecked) { + ensureDictionaryForCurrentLanguage() + } + } + } + } + + private fun setupAutoCorrect() { + binding.apply { + settingsAutoCorrect.isChecked = config.autoCorrectOnSpace + settingsAutoCorrectHolder.setOnClickListener { + settingsAutoCorrect.toggle() + config.autoCorrectOnSpace = settingsAutoCorrect.isChecked + if (settingsAutoCorrect.isChecked) { + ensureDictionaryForCurrentLanguage() + } + } + } + } + private fun setupVoiceInputMethod() { binding.apply { settingsVoiceInputMethodValue.text = diff --git a/app/src/main/kotlin/org/fossify/keyboard/extensions/KeyboardThemeExt.kt b/app/src/main/kotlin/org/fossify/keyboard/extensions/KeyboardThemeExt.kt index 3a0abb892..808a27f1a 100644 --- a/app/src/main/kotlin/org/fossify/keyboard/extensions/KeyboardThemeExt.kt +++ b/app/src/main/kotlin/org/fossify/keyboard/extensions/KeyboardThemeExt.kt @@ -10,10 +10,12 @@ import org.fossify.commons.extensions.lightenColor import org.fossify.keyboard.R fun Context.getKeyboardBackgroundColor(): Int { - val color = if (isDynamicTheme()) { + // use safeStorageContext: these helpers also run inside the directBootAware IME service, + // where credential encrypted SharedPreferences are not available before user unlock + val color = if (safeStorageContext.isDynamicTheme()) { resources.getColor(R.color.you_keyboard_background_color, theme) } else { - getProperBackgroundColor().darkenColor(2) + safeStorageContext.getProperBackgroundColor().darkenColor(2) } // use darker background color when key borders are enabled @@ -30,7 +32,7 @@ fun Context.getKeyboardBackgroundColor(): Int { } fun Context.getStrokeColor(): Int { - return if (isDynamicTheme()) { + return if (safeStorageContext.isDynamicTheme()) { if (isSystemInDarkMode()) { resources.getColor(R.color.md_grey_800, theme) } else { diff --git a/app/src/main/kotlin/org/fossify/keyboard/helpers/Config.kt b/app/src/main/kotlin/org/fossify/keyboard/helpers/Config.kt index 46003b5ce..1a1c3f7b0 100644 --- a/app/src/main/kotlin/org/fossify/keyboard/helpers/Config.kt +++ b/app/src/main/kotlin/org/fossify/keyboard/helpers/Config.kt @@ -78,15 +78,52 @@ class Config(context: Context) : BaseConfig(context) { prefs.edit().putStringSet(SELECTED_LANGUAGES, stringSet).apply() } - fun getDefaultLanguage(): Int { - val conf = context.resources.configuration - return if (conf.locale.toString().lowercase(Locale.getDefault()).startsWith("ru_")) { - LANGUAGE_RUSSIAN - } else { - LANGUAGE_ENGLISH_QWERTY + fun getDefaultLanguage(): Int = languageForLocale(context.resources.configuration.locale) + + /** maps the system locale to the closest supported keyboard language (English QWERTY as fallback) */ + private fun languageForLocale(locale: Locale): Int { + val country = locale.country.uppercase(Locale.getDefault()) + return when (locale.language.lowercase(Locale.getDefault())) { + "fr" -> LANGUAGE_FRENCH_AZERTY + "de" -> if (country == "DE") LANGUAGE_GERMAN else LANGUAGE_GERMAN_QWERTZ + "es" -> LANGUAGE_SPANISH + "it" -> LANGUAGE_ITALIAN + "pt" -> LANGUAGE_PORTUGUESE + "nl" -> LANGUAGE_DUTCH + "pl" -> LANGUAGE_POLISH + "sv" -> LANGUAGE_SWEDISH + "da" -> LANGUAGE_DANISH + "nb", "no" -> LANGUAGE_NORWEGIAN + "ru" -> LANGUAGE_RUSSIAN + "uk" -> LANGUAGE_UKRAINIAN + "cs" -> LANGUAGE_CZECH_QWERTY + "tr" -> LANGUAGE_TURKISH + "el" -> LANGUAGE_GREEK + "he" -> LANGUAGE_HEBREW + "ar" -> LANGUAGE_ARABIC + "bn" -> LANGUAGE_BENGALI + "lv" -> LANGUAGE_LATVIAN + "lt" -> LANGUAGE_LITHUANIAN + "ro" -> LANGUAGE_ROMANIAN + "sl" -> LANGUAGE_SLOVENIAN + "bg" -> LANGUAGE_BULGARIAN + "eo" -> LANGUAGE_ESPERANTO + else -> LANGUAGE_ENGLISH_QWERTY } } + var wasDictionaryLanguageProposed: Boolean + get() = prefs.getBoolean(DICTIONARY_LANGUAGE_PROPOSED, false) + set(wasDictionaryLanguageProposed) = prefs.edit().putBoolean(DICTIONARY_LANGUAGE_PROPOSED, wasDictionaryLanguageProposed).apply() + + var showSuggestions: Boolean + get() = prefs.getBoolean(SHOW_SUGGESTIONS, false) + set(showSuggestions) = prefs.edit().putBoolean(SHOW_SUGGESTIONS, showSuggestions).apply() + + var autoCorrectOnSpace: Boolean + get() = prefs.getBoolean(AUTO_CORRECT_ON_SPACE, false) + set(autoCorrectOnSpace) = prefs.edit().putBoolean(AUTO_CORRECT_ON_SPACE, autoCorrectOnSpace).apply() + var recentlyUsedEmojis: List get() = prefs.getString(RECENTLY_USED_EMOJIS, "\uD83D\uDC30")!!.split("|").filter { it.isNotEmpty() } set(recentlyUsedEmojis) = prefs.edit().putString( diff --git a/app/src/main/kotlin/org/fossify/keyboard/helpers/Constants.kt b/app/src/main/kotlin/org/fossify/keyboard/helpers/Constants.kt index c31276dbd..9194c7fc1 100644 --- a/app/src/main/kotlin/org/fossify/keyboard/helpers/Constants.kt +++ b/app/src/main/kotlin/org/fossify/keyboard/helpers/Constants.kt @@ -31,6 +31,23 @@ const val SHOW_NUMBERS_ROW = "show_numbers_row" const val SELECTED_LANGUAGES = "selected_languages" const val VOICE_INPUT_METHOD = "voice_input_method" const val RECENTLY_USED_EMOJIS = "recently_used_emojis" +const val SHOW_SUGGESTIONS = "show_suggestions" +const val AUTO_CORRECT_ON_SPACE = "auto_correct_on_space" +const val DICTIONARY_LANGUAGE_PROPOSED = "dictionnary_language_proposed" + +// the keyboard app has no internet permission: the external Dictionnary app downloads the +// language files of the auto-correct and shares them through this content provider authority +const val DICTIONNARY_AUTHORITY = "org.fossify.dictionnary.provider" +const val DICTIONNARY_ACCESS_PERMISSION = "org.fossify.dictionnary.ACCESS_DICTIONARIES" +const val DEFAULT_DICTIONARY_LANG = "en_US" + +// intent used to launch the Dictionnary app so it downloads a dictionary and hands the result back +const val DICTIONNARY_ACTION_DOWNLOAD = "org.fossify.dictionnary.action.DOWNLOAD_DICTIONARY" +const val DICTIONNARY_EXTRA_LANG = "lang" +const val DICTIONNARY_EXTRA_CALLING_PACKAGE = "calling_package" +const val DICTIONNARY_EXTRA_RESULT_URI = "result_uri" +const val DICTIONNARY_EXTRA_ERROR = "error" +const val DICTIONNARY_PACKAGE = "org.fossify.dictionnary" // differentiate current and pinned clips at the keyboards' Clipboard section const val ITEM_SECTION_LABEL = 0 diff --git a/app/src/main/kotlin/org/fossify/keyboard/helpers/DictionaryLanguages.kt b/app/src/main/kotlin/org/fossify/keyboard/helpers/DictionaryLanguages.kt new file mode 100644 index 000000000..78f11108f --- /dev/null +++ b/app/src/main/kotlin/org/fossify/keyboard/helpers/DictionaryLanguages.kt @@ -0,0 +1,44 @@ +package org.fossify.keyboard.helpers + +/** + * Maps a keyboard language (see LANGUAGE_* constants) to the dictionary language code + * (".json") served by the external Dictionnary app. Returns null when no dictionary + * exists for that keyboard language. + */ +fun dictionaryLangForKeyboardLanguage(language: Int): String? = when (language) { + LANGUAGE_ENGLISH_QWERTY, + LANGUAGE_ENGLISH_QWERTZ, + LANGUAGE_ENGLISH_DVORAK, + LANGUAGE_ENGLISH_ASSET, + LANGUAGE_ENGLISH_COLEMAK, + LANGUAGE_ENGLISH_COLEMAKDH, + LANGUAGE_ENGLISH_NIRO, + LANGUAGE_ENGLISH_SOUL, + LANGUAGE_ENGLISH_WORKMAN -> "en_US" + + LANGUAGE_FRENCH_AZERTY, LANGUAGE_FRENCH_BEPO, LANGUAGE_KABYLE_AZERTY -> "fr_FR" + LANGUAGE_GERMAN, LANGUAGE_GERMAN_QWERTZ -> "de_DE" + LANGUAGE_SPANISH -> "es_ES" + LANGUAGE_ITALIAN -> "it_IT" + LANGUAGE_PORTUGUESE, LANGUAGE_PORTUGUESE_HCESAR -> "pt_PT" + LANGUAGE_DUTCH -> "nl_NL" + LANGUAGE_POLISH -> "pl_PL" + LANGUAGE_SWEDISH -> "sv_SE" + LANGUAGE_DANISH -> "da_DK" + LANGUAGE_NORWEGIAN -> "nb_NO" + LANGUAGE_RUSSIAN -> "ru_RU" + LANGUAGE_UKRAINIAN -> "uk_UA" + LANGUAGE_CZECH_QWERTY, LANGUAGE_CZECH_QWERTZ -> "cs_CZ" + LANGUAGE_TURKISH, LANGUAGE_TURKISH_Q -> "tr_TR" + LANGUAGE_GREEK -> "el_GR" + LANGUAGE_HEBREW -> "he_IL" + LANGUAGE_ARABIC -> "ar_AR" + LANGUAGE_BENGALI -> "bn_BD" + LANGUAGE_LATVIAN -> "lv_LV" + LANGUAGE_LITHUANIAN -> "lt_LT" + LANGUAGE_ROMANIAN -> "ro_RO" + LANGUAGE_SLOVENIAN -> "sl_SI" + LANGUAGE_BULGARIAN -> "bg_BG" + LANGUAGE_ESPERANTO -> "eo" + else -> null +} diff --git a/app/src/main/kotlin/org/fossify/keyboard/helpers/DictionnaryClient.kt b/app/src/main/kotlin/org/fossify/keyboard/helpers/DictionnaryClient.kt new file mode 100644 index 000000000..6828081f7 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/keyboard/helpers/DictionnaryClient.kt @@ -0,0 +1,253 @@ +package org.fossify.keyboard.helpers + +import android.app.Activity +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.Uri +import org.fossify.commons.extensions.getAlertDialogBuilder +import org.fossify.commons.helpers.ensureBackgroundThread +import org.fossify.keyboard.R +import org.fossify.keyboard.extensions.safeStorageContext +import java.io.File + +/** + * Client for the external Dictionnary app (org.fossify.dictionnary). + * + * The keyboard app itself has no internet permission: the Dictionnary app downloads the + * dictionary files and serves them through a content provider. Here we can: + * - ask that provider for the content URI of a file, open the URI and keep a local copy + * of the downloaded file in our own files dir (see [copyDictionaryToLocal]), + * - or explicitly launch the Dictionnary app with [DICTIONNARY_ACTION_DOWNLOAD] so it + * downloads a language and hands the result (and a read grant on the file URI) back + * to us via startActivityForResult (see [launchDictionaryDownload] / [handleDownloadResult]). + */ +object DictionnaryClient { + /** request code used when picking the Dictionnary APK file with the system picker */ + const val REQUEST_PICK_DICTIONNARY_APK = 1002 + + private const val PATH_DICTIONARIES = "dictionaries" + private const val PATH_FILES = "files" + private const val METHOD_DOWNLOAD = "download" + private const val COLUMN_DOWNLOADED = "downloaded" + private const val POLL_INTERVAL_MS = 500L + private const val MAX_POLLS = 60 + + fun dictionaryUri(lang: String): Uri = + Uri.parse("content://$DICTIONNARY_AUTHORITY/$PATH_DICTIONARIES/$lang") + + fun dictionaryFileUri(lang: String): Uri = + Uri.parse("content://$DICTIONNARY_AUTHORITY/$PATH_FILES/$PATH_DICTIONARIES/$lang.json") + + /** local copy of the dictionary inside the keyboard app's own storage */ + fun localDictionaryFile(context: Context, lang: String): File = + File(context.safeStorageContext.filesDir, "$PATH_DICTIONARIES/$lang.json") + + fun isLocalDictionaryAvailable(context: Context, lang: String): Boolean { + val file = localDictionaryFile(context, lang) + return file.isFile && file.length() > 0 + } + + /** package name of the installed Dictionnary app (release or debug), null if not installed */ + fun dictionnaryPackageName(context: Context): String? { + val packageManager = context.packageManager + return listOf(DICTIONNARY_PACKAGE, "$DICTIONNARY_PACKAGE.debug").firstOrNull { packageName -> + try { + packageManager.getLaunchIntentForPackage(packageName) != null + } catch (_: Exception) { + false + } + } + } + + fun isDictionnaryInstalled(context: Context): Boolean = dictionnaryPackageName(context) != null + + /** asks the Dictionnary app's provider to (re)download the given language */ + fun requestDownload(context: Context, lang: String) { + try { + context.contentResolver.call(DICTIONNARY_AUTHORITY, METHOD_DOWNLOAD, lang, null) + } catch (_: Exception) { + } + } + + /** whether the Dictionnary app already has the file, as reported by its provider */ + fun isDownloadedRemotely(context: Context, lang: String): Boolean = try { + context.contentResolver.query(dictionaryUri(lang), null, null, null, null)?.use { cursor -> + cursor.moveToFirst() && cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_DOWNLOADED)) == 1 + } ?: false + } catch (_: Exception) { + false + } + + /** + * Makes sure a local copy of the dictionary exists in the keyboard app. If there is none, + * the Dictionnary app is asked to download it, we wait for the download to finish, then the + * file exposed at its content URI is opened and copied into our own files dir. + * + * Blocking, must be called from a background thread. Returns the local file or null. + */ + fun copyDictionaryToLocal(context: Context, lang: String): File? { + val localFile = localDictionaryFile(context, lang) + if (localFile.isFile && localFile.length() > 0) { + return localFile + } + + if (!isDictionnaryInstalled(context)) { + return null + } + + requestDownload(context, lang) + var downloaded = isDownloadedRemotely(context, lang) + var polls = 0 + while (!downloaded && polls < MAX_POLLS) { + Thread.sleep(POLL_INTERVAL_MS) + downloaded = isDownloadedRemotely(context, lang) + polls++ + } + if (!downloaded) { + return null + } + + return copyFromUri(context, dictionaryFileUri(lang), lang) + } + + /** asynchronous variant of [copyDictionaryToLocal] */ + fun ensureLocalDictionary(context: Context, lang: String, onReady: (File?) -> Unit) { + ensureBackgroundThread { + onReady(copyDictionaryToLocal(context, lang)) + } + } + + /** copies the file exposed at the given content URI into our local dictionaries dir */ + fun copyFromUri(context: Context, uri: Uri, lang: String): File? { + val localFile = localDictionaryFile(context, lang) + return try { + context.contentResolver.openInputStream(uri)?.use { input -> + localFile.parentFile?.mkdirs() + val tmpFile = File(localFile.parentFile, localFile.name + ".tmp") + tmpFile.outputStream().use { output -> input.copyTo(output) } + if (tmpFile.isFile && tmpFile.length() > 0) { + if (localFile.exists()) { + localFile.delete() + } + tmpFile.renameTo(localFile) + localFile + } else { + tmpFile.delete() + null + } + } + } catch (e: Exception) { + null + } + } + + /** intent launching the Dictionnary app to download [lang] and report back via activity result */ + fun downloadIntent(context: Context, lang: String): Intent = + Intent(DICTIONNARY_ACTION_DOWNLOAD).apply { + addCategory(Intent.CATEGORY_DEFAULT) + putExtra(DICTIONNARY_EXTRA_LANG, lang) + putExtra(DICTIONNARY_EXTRA_CALLING_PACKAGE, context.packageName) + } + + /** + * Launches the Dictionnary app so it downloads the dictionary for [lang]. The result comes + * back in onActivityResult: RESULT_OK with [DICTIONNARY_EXTRA_RESULT_URI] pointing to the + * downloaded file (the Dictionnary app grants us read access to that URI). + */ + fun launchDictionaryDownload(activity: Activity, lang: String, requestCode: Int) { + try { + activity.startActivityForResult(downloadIntent(activity, lang), requestCode) + } catch (_: Exception) { + proposeInstallDictionnary(activity, lang) + } + } + + /** same as [proposeInstallDictionnary] but without the lang-specific message context */ + private fun proposeInstallDictionnary(activity: Activity, lang: String) = + proposeInstallDictionnary(activity, lang, REQUEST_PICK_DICTIONNARY_APK) + + /** + * Handles the activity result of [launchDictionaryDownload]: copies the file the Dictionnary + * app exposed (and granted us) into our local storage. Returns the local file or null. + */ + fun handleDownloadResult(context: Context, resultCode: Int, data: Intent?): File? { + if (resultCode != Activity.RESULT_OK || data == null) { + return null + } + val lang = data.getStringExtra(DICTIONNARY_EXTRA_LANG) ?: return null + val uriString = data.getStringExtra(DICTIONNARY_EXTRA_RESULT_URI) + val uri = uriString?.let { Uri.parse(it) } ?: dictionaryFileUri(lang) + return copyFromUri(context, uri, lang) + } + + /** opens the launcher activity of the installed Dictionnary app, if any */ + fun openDictionnaryApp(activity: Activity): Boolean { + val packageName = dictionnaryPackageName(activity) ?: return false + val launchIntent = activity.packageManager.getLaunchIntentForPackage(packageName) ?: return false + return try { + activity.startActivity(launchIntent) + true + } catch (_: Exception) { + false + } + } + + /** lets the user pick the Dictionnary APK file with the system file picker */ + fun pickDictionnaryApk(activity: Activity, requestCode: Int) { + val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = "application/vnd.android.package-archive" + } + try { + activity.startActivityForResult(intent, requestCode) + } catch (_: Exception) { + } + } + + /** hands the picked APK content URI to the system package installer */ + fun installApkFromUri(activity: Activity, uri: Uri) { + val intent = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + try { + activity.startActivity(intent) + } catch (_: Exception) { + } + } + + /** + * Shows a dialog proposing to install the Dictionnary app (it is not installed yet): + * either by picking its APK file (system file picker → package installer, works without + * any store), or by opening its Play Store page. + */ + fun proposeInstallDictionnary(activity: Activity, lang: String, pickRequestCode: Int) { + activity.getAlertDialogBuilder() + .setTitle(R.string.install_dictionnary_title) + .setMessage(activity.getString(R.string.install_dictionnary_message, lang)) + .setPositiveButton(R.string.install_dictionnary_pick_apk) { _, _ -> + pickDictionnaryApk(activity, pickRequestCode) + } + .setNeutralButton(R.string.open_play_store) { _, _ -> + openDictionnaryStorePage(activity) + } + .setNegativeButton(R.string.cancel, null) + .show() + } + + private fun openDictionnaryStorePage(activity: Activity) { + val marketIntent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$DICTIONNARY_PACKAGE")) + try { + activity.startActivity(marketIntent) + } catch (_: ActivityNotFoundException) { + activity.startActivity( + Intent( + Intent.ACTION_VIEW, + Uri.parse("https://play.google.com/store/apps/details?id=$DICTIONNARY_PACKAGE") + ) + ) + } + } +} diff --git a/app/src/main/kotlin/org/fossify/keyboard/helpers/SpellChecker.kt b/app/src/main/kotlin/org/fossify/keyboard/helpers/SpellChecker.kt new file mode 100644 index 000000000..cda3869ae --- /dev/null +++ b/app/src/main/kotlin/org/fossify/keyboard/helpers/SpellChecker.kt @@ -0,0 +1,201 @@ +package org.fossify.keyboard.helpers + +import android.content.Context +import android.os.Handler +import android.os.Looper +import org.fossify.commons.helpers.ensureBackgroundThread +import org.json.JSONArray +import org.json.JSONException +import java.io.IOException +import java.util.Collections +import kotlin.math.abs +import kotlin.math.min + +private const val DEBOUNCE_DELAY_MS = 100L +private const val MAX_SUGGESTIONS = 3 +private const val MAX_LENGTH_DIFF = 2 +private const val MAX_EDIT_DISTANCE = 2 +private const val MIN_WORD_LENGTH = 2 +private const val CACHE_SIZE = 20 + +/** + * Dictionary based spell checker used for word suggestions and auto-correct. + * + * The dictionary file is not bundled with the keyboard and the keyboard app has no internet + * permission: the file is provided by the external Dictionnary app through a content URI + * (see [DictionnaryClient]), copied locally, and loaded from that local copy. + */ +class SpellChecker(context: Context, private val dictionaryLang: String = DEFAULT_DICTIONARY_LANG) { + private val appContext = context.applicationContext + @Volatile + private var dictionary: HashMap? = null + private val mainHandler = Handler(Looper.getMainLooper()) + private var pendingRunnable: Runnable? = null + @Suppress("MagicNumber") + private val cache: MutableMap> = Collections.synchronizedMap( + object : LinkedHashMap>(CACHE_SIZE, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry>) = size > CACHE_SIZE + } + ) + + var onSuggestionsReady: ((List) -> Unit)? = null + var onDictionaryLoaded: (() -> Unit)? = null + + init { + ensureBackgroundThread { + loadDictionaryFromLocalCopy() + mainHandler.post { onDictionaryLoaded?.invoke() } + } + } + + fun checkWord(word: String) { + pendingRunnable?.let { mainHandler.removeCallbacks(it) } + + pendingRunnable = Runnable { + ensureBackgroundThread { + val suggestions = findSuggestions(word) + mainHandler.post { + onSuggestionsReady?.invoke(suggestions) + } + } + } + + mainHandler.postDelayed(pendingRunnable!!, DEBOUNCE_DELAY_MS) + } + + fun clear() { + pendingRunnable?.let { mainHandler.removeCallbacks(it) } + mainHandler.post { + onSuggestionsReady?.invoke(emptyList()) + } + } + + fun isValidWord(word: String): Boolean { + return dictionary?.containsKey(word.lowercase()) ?: true + } + + /** + * The most frequent words of the dictionary, used to predict the word following a space + * before the user types its first letter. The dictionary holds unigram frequencies only, + * so the most probable next word is simply the most frequent one (optionally excluding + * the word that was just typed). + */ + fun nextWordSuggestions(exclude: String? = null): List { + val dict = dictionary ?: return emptyList() + val excluded = exclude?.lowercase() + return dict.entries + .asSequence() + .filter { it.key != excluded } + .sortedByDescending { it.value } + .take(MAX_SUGGESTIONS) + .map { it.key } + .toList() + } + + fun destroy() { + pendingRunnable?.let { mainHandler.removeCallbacks(it) } + onSuggestionsReady = null + onDictionaryLoaded = null + } + + /** reloads the dictionary, fetching it from the Dictionnary app first if needed */ + fun reload() { + ensureBackgroundThread { + loadDictionaryFromLocalCopy() + mainHandler.post { onDictionaryLoaded?.invoke() } + } + } + + private fun loadDictionaryFromLocalCopy() { + dictionary = loadDictionary() + if (dictionary?.isEmpty() == true) { + // no local copy yet: get the file from the Dictionnary app via its content + // URI, keep a local copy of it, then load it + DictionnaryClient.copyDictionaryToLocal(appContext, dictionaryLang) + dictionary = loadDictionary() + } + } + + private fun loadDictionary(): HashMap { + val map = HashMap() + try { + val file = DictionnaryClient.localDictionaryFile(appContext, dictionaryLang) + if (!file.isFile) { + return map + } + val jsonString = file.bufferedReader().use { it.readText() } + val jsonArray = JSONArray(jsonString) + + for (i in 0 until jsonArray.length()) { + val entry = jsonArray.getJSONArray(i) + val word = entry.getString(0) + val rank = jsonArray.length() - i + map[word] = rank + } + } catch (_: IOException) { + } catch (_: JSONException) { + } + return map + } + + private fun findSuggestions(input: String): List { + val dict = dictionary ?: return emptyList() + if (input.length < MIN_WORD_LENGTH) return emptyList() + + val inputLower = input.lowercase() + + cache[inputLower]?.let { return it } + + val prefixMatches = dict.keys + .filter { word -> word.startsWith(inputLower) && word != inputLower } + .sortedByDescending { dict[it] ?: 0 } + .take(MAX_SUGGESTIONS) + + if (prefixMatches.isNotEmpty()) { + cache[inputLower] = prefixMatches + return prefixMatches + } + + val firstChar = inputLower[0] + val inputLen = inputLower.length + + val levenshteinMatches = dict.keys + .filter { word -> + word[0] == firstChar && abs(word.length - inputLen) <= MAX_LENGTH_DIFF + } + .map { word -> + word to levenshteinDistance(inputLower, word) + } + .filter { it.second <= MAX_EDIT_DISTANCE } + .sortedWith(compareBy({ it.second }, { -(dict[it.first] ?: 0) })) + .take(MAX_SUGGESTIONS) + .map { it.first } + + cache[inputLower] = levenshteinMatches + return levenshteinMatches + } + + private fun levenshteinDistance(a: String, b: String, maxDistance: Int = MAX_EDIT_DISTANCE): Int { + val m = a.length + val n = b.length + val dp = Array(m + 1) { IntArray(n + 1) } + + for (i in 0..m) dp[i][0] = i + for (j in 0..n) dp[0][j] = j + + for (i in 1..m) { + var rowMin = Int.MAX_VALUE + for (j in 1..n) { + val cost = if (a[i - 1] == b[j - 1]) 0 else 1 + dp[i][j] = min( + min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), + dp[i - 1][j - 1] + cost + ) + rowMin = min(rowMin, dp[i][j]) + } + if (rowMin > maxDistance) return maxDistance + 1 + } + + return dp[m][n] + } +} diff --git a/app/src/main/kotlin/org/fossify/keyboard/services/SimpleKeyboardIME.kt b/app/src/main/kotlin/org/fossify/keyboard/services/SimpleKeyboardIME.kt index 73472a469..03626d8fe 100644 --- a/app/src/main/kotlin/org/fossify/keyboard/services/SimpleKeyboardIME.kt +++ b/app/src/main/kotlin/org/fossify/keyboard/services/SimpleKeyboardIME.kt @@ -19,6 +19,10 @@ import android.text.InputType.TYPE_CLASS_TEXT import android.text.InputType.TYPE_MASK_CLASS import android.text.InputType.TYPE_MASK_VARIATION import android.text.InputType.TYPE_NULL +import android.text.InputType.TYPE_NUMBER_VARIATION_PASSWORD +import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD +import android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD +import android.text.InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD import android.text.TextUtils import android.util.Size import android.view.KeyEvent @@ -47,7 +51,11 @@ import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat.Type import androidx.core.view.updatePadding +import org.fossify.commons.extensions.adjustAlpha import org.fossify.commons.extensions.applyColorFilter +import org.fossify.commons.extensions.beGone +import org.fossify.commons.extensions.beVisible +import org.fossify.commons.extensions.beVisibleIf import org.fossify.commons.extensions.getProperBackgroundColor import org.fossify.commons.extensions.getProperTextColor import org.fossify.commons.extensions.getSharedPrefs @@ -117,10 +125,15 @@ import org.fossify.keyboard.helpers.LANGUAGE_SWEDISH import org.fossify.keyboard.helpers.LANGUAGE_TURKISH import org.fossify.keyboard.helpers.LANGUAGE_TURKISH_Q import org.fossify.keyboard.helpers.LANGUAGE_UKRAINIAN +import org.fossify.keyboard.helpers.AUTO_CORRECT_ON_SPACE +import org.fossify.keyboard.helpers.DEFAULT_DICTIONARY_LANG import org.fossify.keyboard.helpers.MyKeyboard import org.fossify.keyboard.helpers.SHOW_KEY_BORDERS +import org.fossify.keyboard.helpers.SHOW_SUGGESTIONS import org.fossify.keyboard.helpers.SHOW_NUMBERS_ROW import org.fossify.keyboard.helpers.ShiftState +import org.fossify.keyboard.helpers.SpellChecker +import org.fossify.keyboard.helpers.dictionaryLangForKeyboardLanguage import org.fossify.keyboard.helpers.VOICE_INPUT_METHOD import org.fossify.keyboard.helpers.cachedVNTelexData import org.fossify.keyboard.interfaces.OnKeyboardActionListener @@ -134,6 +147,7 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared companion object { // How quickly do we have to double tap shift to enable permanent caps lock private var SHIFT_PERM_TOGGLE_SPEED = 500 + private const val DIVIDER_ALPHA = 0.3f // Keyboard modes const val KEYBOARD_LETTERS = 0 @@ -153,6 +167,11 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared private var enterKeyType = IME_ACTION_NONE private var switchToLetters = false private var breakIterator: BreakIterator? = null + private var spellChecker: SpellChecker? = null + private val wordBuffer = StringBuilder() + private var currentSuggestions: List = emptyList() + // last suggestion applied by tapping the strip, excluded from the next-word predictions + private var lastAppliedSuggestion: String? = null private lateinit var binding: KeyboardViewKeyboardBinding @@ -161,6 +180,13 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared safeStorageContext.getSharedPrefs().registerOnSharedPreferenceChangeListener(this) } + override fun onDestroy() { + super.onDestroy() + spellChecker?.destroy() + spellChecker = null + safeStorageContext.getSharedPrefs().unregisterOnSharedPreferenceChangeListener(this) + } + override fun onCreateInputView(): View { binding = KeyboardViewKeyboardBinding.inflate(layoutInflater) keyboardView = binding.keyboardView.apply { @@ -171,9 +197,40 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared mOnKeyboardActionListener = this@SimpleKeyboardIME } + setupSpellChecker() + return binding.root } + private fun setupSpellChecker() { + spellChecker?.destroy() + spellChecker = null + if (!config.showSuggestions && !config.autoCorrectOnSpace) { + return + } + val dictionaryLang = dictionaryLangForKeyboardLanguage(config.keyboardLanguage) ?: DEFAULT_DICTIONARY_LANG + spellChecker = SpellChecker(this, dictionaryLang) + spellChecker?.onSuggestionsReady = { suggestions -> + if (isPasswordField()) { + clearSpellSuggestions() + } else { + currentSuggestions = suggestions + if (config.showSuggestions) { + showSpellSuggestions(suggestions) + } + } + } + spellChecker?.onDictionaryLoaded = { + if (wordBuffer.isNotEmpty()) { + triggerSpellCheck() + } else if (endsWithSpaceBeforeCursor()) { + // the dictionary finished loading while the cursor sits right after a + // space: propose the most probable next words + showNextWordSuggestions() + } + } + } + override fun onStartInputView(editorInfo: EditorInfo?, restarting: Boolean) { super.onStartInputView(editorInfo, restarting) updateBackgroundColors() @@ -200,6 +257,8 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared breakIterator = BreakIterator.getCharacterInstance(ULocale.getDefault()) } updateShiftKeyState() + wordBuffer.clear() + clearSpellSuggestions() } private fun updateShiftKeyState() { @@ -270,6 +329,16 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared } else { inputConnection.commitText("", 1) } + if (wordBuffer.isNotEmpty()) wordBuffer.deleteAt(wordBuffer.length - 1) + if (wordBuffer.isEmpty()) { + if (endsWithSpaceBeforeCursor()) { + showNextWordSuggestions() + } else { + clearSpellSuggestions() + } + } else { + triggerSpellCheck() + } } MyKeyboard.KEYCODE_SHIFT -> { @@ -374,6 +443,9 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared if (originalText != newText) { switchToLetters = keyboardMode != KEYBOARD_SYMBOLS_ALT } + } else if (code == MyKeyboard.KEYCODE_SPACE) { + handleAutoCorrectSpace() + updateShiftKeyState() } else { when { !originalText.isNullOrEmpty() && cachedVNTelexData.isNotEmpty() -> { @@ -405,6 +477,15 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared updateShiftKeyState() } } + + if (Character.isLetter(codeChar)) { + wordBuffer.append(codeChar.lowercaseChar()) + lastAppliedSuggestion = null + triggerSpellCheck() + } else { + wordBuffer.clear() + clearSpellSuggestions() + } } } } @@ -505,6 +586,19 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared if (newSelStart == newSelEnd) { keyboardView?.closeClipboardManager() } + + val expectedPosition = oldSelEnd + 1 + if (newSelStart != expectedPosition || newSelStart != newSelEnd) { + wordBuffer.clear() + if (newSelStart == newSelEnd && endsWithSpaceBeforeCursor()) { + // cursor moved right after a space (or a suggestion was just applied): + // propose the most probable next words + showNextWordSuggestions(afterWord = lastAppliedSuggestion) + } else { + clearSpellSuggestions() + } + } + updateShiftKeyState() } @@ -598,8 +692,8 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared val rippleBg = resources.getDrawable(R.drawable.clipboard_background, theme) as RippleDrawable val layerDrawable = rippleBg.findDrawableByLayerId(R.id.clipboard_background_holder) as LayerDrawable - layerDrawable.findDrawableByLayerId(R.id.clipboard_background_stroke).applyColorFilter(getStrokeColor()) - layerDrawable.findDrawableByLayerId(R.id.clipboard_background_shape).applyColorFilter(getProperBackgroundColor()) + layerDrawable.findDrawableByLayerId(R.id.clipboard_background_stroke).applyColorFilter(safeStorageContext.getStrokeColor()) + layerDrawable.findDrawableByLayerId(R.id.clipboard_background_shape).applyColorFilter(safeStorageContext.getProperBackgroundColor()) val maxWidth = resources.getDimensionPixelSize(R.dimen.suggestion_max_width) val height = resources.getDimensionPixelSize(R.dimen.label_text_size) + verticalPadding * 2 @@ -623,13 +717,13 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared .setTitleStyle( TextViewStyle.Builder() .setLayoutMargin(0, 0, horizontalPadding, 0) - .setTextColor(getProperTextColor()) + .setTextColor(safeStorageContext.getProperTextColor()) .setTextSize(textSize) .build() ) .setSubtitleStyle( TextViewStyle.Builder() - .setTextColor(getProperTextColor()) + .setTextColor(safeStorageContext.getProperTextColor()) .setTextSize(textSize) .build() ) @@ -639,6 +733,11 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { + if (key == KEYBOARD_LANGUAGE || key == SHOW_SUGGESTIONS || key == AUTO_CORRECT_ON_SPACE) { + // (re)create or tear down the spell checker depending on whether suggestions or + // auto-correct are enabled, and reload the dictionary of the newly selected language + setupSpellChecker() + } if (key != null && key in arrayOf( SHOW_KEY_BORDERS, KEYBOARD_LANGUAGE, HEIGHT_PERCENTAGE, SHOW_NUMBERS_ROW, VOICE_INPUT_METHOD, TEXT_COLOR, BACKGROUND_COLOR, PRIMARY_COLOR, ACCENT_COLOR, CUSTOM_TEXT_COLOR, CUSTOM_BACKGROUND_COLOR, @@ -732,4 +831,134 @@ class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, Shared } return keyboard } + + private fun showSpellSuggestions(suggestions: List) { + if (suggestions.isEmpty()) { + binding.spellSuggestionsHolder.beGone() + binding.clipboardValue.beVisibleIf(config.showClipboardContent) + return + } + + binding.clipboardValue.beGone() + binding.spellSuggestionsHolder.beVisible() + + val textColor = safeStorageContext.getProperTextColor() + val dividerColor = textColor.adjustAlpha(DIVIDER_ALPHA) + + val slot0 = suggestions.getOrNull(1) + val slot1 = suggestions.getOrNull(0) // best candidate in middle + val slot2 = suggestions.getOrNull(2) + + binding.suggestionSlot0.apply { + text = slot0 ?: "" + setTextColor(textColor) + setOnClickListener { slot0?.let { applySuggestion(it) } } + } + binding.suggestionDivider0.setTextColor(dividerColor) + + binding.suggestionSlot1.apply { + text = slot1 ?: "" + setTextColor(textColor) + setOnClickListener { slot1?.let { applySuggestion(it) } } + } + binding.suggestionDivider1.setTextColor(dividerColor) + + binding.suggestionSlot2.apply { + text = slot2 ?: "" + setTextColor(textColor) + setOnClickListener { slot2?.let { applySuggestion(it) } } + } + } + + private fun clearSpellSuggestions() { + currentSuggestions = emptyList() + if (::binding.isInitialized) { + binding.spellSuggestionsHolder.beGone() + binding.clipboardValue.beVisibleIf(config.showClipboardContent) + } + } + + private fun applySuggestion(word: String) { + val currentWord = wordBuffer.toString() + if (currentWord.isNotEmpty()) { + currentInputConnection?.deleteSurroundingText(currentWord.length, 0) + } + currentInputConnection?.commitText("$word ", 1) + wordBuffer.clear() + // the suggestion is committed with a trailing space: predict the next word + lastAppliedSuggestion = word + showNextWordSuggestions(afterWord = word) + } + + private fun isPasswordField(): Boolean { + return inputTypeClassVariation == TYPE_TEXT_VARIATION_PASSWORD || + inputTypeClassVariation == TYPE_TEXT_VARIATION_VISIBLE_PASSWORD || + inputTypeClassVariation == TYPE_TEXT_VARIATION_WEB_PASSWORD || + inputTypeClassVariation == TYPE_NUMBER_VARIATION_PASSWORD + } + + private fun triggerSpellCheck() { + if (isPasswordField()) { + clearSpellSuggestions() + return + } + + if (!config.showSuggestions && !config.autoCorrectOnSpace) { + clearSpellSuggestions() + return + } + + if (wordBuffer.length >= 2) { + spellChecker?.checkWord(wordBuffer.toString()) + } else { + clearSpellSuggestions() + } + } + + private fun handleAutoCorrectSpace() { + val currentWord = wordBuffer.toString() + val topSuggestion = currentSuggestions.firstOrNull() + + val shouldAutoCorrect = config.autoCorrectOnSpace && + !isPasswordField() && + topSuggestion != null && + currentWord.isNotEmpty() && + spellChecker?.isValidWord(currentWord) == false + + if (shouldAutoCorrect) { + currentInputConnection?.deleteSurroundingText(currentWord.length, 0) + currentInputConnection?.commitText("$topSuggestion ", 1) + } else { + currentInputConnection?.commitText(" ", 1) + } + + wordBuffer.clear() + // the cursor now sits right after a space: propose the most probable next + // words so one can be picked before its first letter is typed + lastAppliedSuggestion = if (shouldAutoCorrect) topSuggestion else currentWord + showNextWordSuggestions(afterWord = lastAppliedSuggestion) + } + + /** + * Shows the most probable words following the current word (used after a space, before + * the first letter of the next word is typed). Tapping one inserts it followed by a space. + */ + private fun showNextWordSuggestions(afterWord: String? = null) { + if (!config.showSuggestions || isPasswordField()) { + clearSpellSuggestions() + return + } + val suggestions = spellChecker?.nextWordSuggestions(exclude = afterWord).orEmpty() + currentSuggestions = suggestions + if (suggestions.isEmpty()) { + clearSpellSuggestions() + } else { + showSpellSuggestions(suggestions) + } + } + + private fun endsWithSpaceBeforeCursor(): Boolean { + val before = currentInputConnection?.getTextBeforeCursor(1, 0)?.toString() ?: return false + return before.isNotEmpty() && before.last().isWhitespace() + } } diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml index f1706073d..c515811b1 100644 --- a/app/src/main/res/layout/activity_settings.xml +++ b/app/src/main/res/layout/activity_settings.xml @@ -334,6 +334,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Start sentences with a capital letter Show emoji key Show language switch key + Show word suggestions + Auto-correct on space + Install the Dictionnary app to download the language dictionaries used for suggestions and auto-correct + Install + Dictionnary (dictionaries) + installed + not installed, tap to install + Dictionnary app required + The %1$s dictionary used for word suggestions and auto-correct is downloaded by the separate Dictionnary app (this keyboard has no internet permission). Install Dictionnary to get it? + Choose APK file… + Open Play Store + Dictionary %1$s downloaded + Could not download the %1$s dictionary Emojis Recently used diff --git a/dictionnary/.gitignore b/dictionnary/.gitignore new file mode 100644 index 000000000..796b96d1c --- /dev/null +++ b/dictionnary/.gitignore @@ -0,0 +1 @@ +/build diff --git a/dictionnary/build.gradle.kts b/dictionnary/build.gradle.kts new file mode 100644 index 000000000..c73995451 --- /dev/null +++ b/dictionnary/build.gradle.kts @@ -0,0 +1,56 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + alias(libs.plugins.android) +} + +android { + compileSdk = project.libs.versions.app.build.compileSDKVersion.get().toInt() + + namespace = "org.fossify.dictionnary" + + defaultConfig { + applicationId = "org.fossify.dictionnary" + minSdk = project.libs.versions.app.build.minimumSDK.get().toInt() + targetSdk = project.libs.versions.app.build.targetSDK.get().toInt() + versionCode = 1 + versionName = "1.0" + vectorDrawables.useSupportLibrary = true + } + + buildTypes { + debug { + applicationIdSuffix = ".debug" + } + release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + + sourceSets { + getByName("main").java.directories.add("src/main/kotlin") + } + + compileOptions { + val currentJavaVersionFromLibs = JavaVersion.valueOf(libs.versions.app.build.javaVersion.get()) + sourceCompatibility = currentJavaVersionFromLibs + targetCompatibility = currentJavaVersionFromLibs + } + + tasks.withType { + compilerOptions.jvmTarget.set( + JvmTarget.fromTarget(project.libs.versions.app.build.kotlinJVMTarget.get()) + ) + } + + lint { + checkReleaseBuilds = false + abortOnError = false + } +} diff --git a/dictionnary/proguard-rules.pro b/dictionnary/proguard-rules.pro new file mode 100644 index 000000000..29136202f --- /dev/null +++ b/dictionnary/proguard-rules.pro @@ -0,0 +1,3 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. diff --git a/dictionnary/src/debug/AndroidManifest.xml b/dictionnary/src/debug/AndroidManifest.xml new file mode 100644 index 000000000..72f42b4a7 --- /dev/null +++ b/dictionnary/src/debug/AndroidManifest.xml @@ -0,0 +1,14 @@ + + + + + + diff --git a/dictionnary/src/main/AndroidManifest.xml b/dictionnary/src/main/AndroidManifest.xml new file mode 100644 index 000000000..aa8089c58 --- /dev/null +++ b/dictionnary/src/main/AndroidManifest.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dictionnary/src/main/kotlin/org/fossify/dictionnary/App.kt b/dictionnary/src/main/kotlin/org/fossify/dictionnary/App.kt new file mode 100644 index 000000000..cd42b6877 --- /dev/null +++ b/dictionnary/src/main/kotlin/org/fossify/dictionnary/App.kt @@ -0,0 +1,15 @@ +package org.fossify.dictionnary + +import android.app.Application +import org.fossify.dictionnary.helpers.AVAILABLE_DICTIONARIES +import org.fossify.dictionnary.helpers.DictionaryDownloader + +class App : Application() { + override fun onCreate() { + super.onCreate() + // pre-download every known dictionary so the keyboard can use them right away + AVAILABLE_DICTIONARIES.forEach { + DictionaryDownloader.enqueueDownload(this, it) + } + } +} diff --git a/dictionnary/src/main/kotlin/org/fossify/dictionnary/activities/MainActivity.kt b/dictionnary/src/main/kotlin/org/fossify/dictionnary/activities/MainActivity.kt new file mode 100644 index 000000000..c48460e9d --- /dev/null +++ b/dictionnary/src/main/kotlin/org/fossify/dictionnary/activities/MainActivity.kt @@ -0,0 +1,110 @@ +package org.fossify.dictionnary.activities + +import android.app.Activity +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.widget.Button +import android.widget.TextView +import org.fossify.dictionnary.R +import org.fossify.dictionnary.helpers.ACTION_DOWNLOAD_DICTIONARY +import org.fossify.dictionnary.helpers.AVAILABLE_DICTIONARIES +import org.fossify.dictionnary.helpers.DictionaryDownloader +import org.fossify.dictionnary.helpers.EXTRA_CALLING_PACKAGE +import org.fossify.dictionnary.helpers.EXTRA_ERROR +import org.fossify.dictionnary.helpers.EXTRA_LANG +import org.fossify.dictionnary.helpers.EXTRA_RESULT_URI +import org.fossify.dictionnary.helpers.dictionaryFileUri + +class MainActivity : Activity() { + private lateinit var status: TextView + private lateinit var downloadButton: Button + private val mainHandler = Handler(Looper.getMainLooper()) + + // language requested by the keyboard app through ACTION_DOWNLOAD_DICTIONARY, if any + private var requestedLang: String? = null + private var callingPackage: String? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + status = findViewById(R.id.dictionary_status) + downloadButton = findViewById(R.id.download_button) + downloadButton.setOnClickListener { + AVAILABLE_DICTIONARIES.forEach { + DictionaryDownloader.enqueueDownload(this, it) + } + refreshStatus() + } + handleIntent(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handleIntent(intent) + } + + override fun onResume() { + super.onResume() + refreshStatus() + } + + private fun handleIntent(intent: Intent?) { + if (intent?.action == ACTION_DOWNLOAD_DICTIONARY) { + requestedLang = intent.getStringExtra(EXTRA_LANG) + callingPackage = intent.getStringExtra(EXTRA_CALLING_PACKAGE) + val lang = requestedLang + if (lang != null) { + status.text = getString(R.string.downloading_dictionary, lang) + DictionaryDownloader.enqueueDownload(this, lang) { success -> + mainHandler.post { onRequestedDownloadFinished(lang, success) } + } + } + } + } + + private fun onRequestedDownloadFinished(lang: String, success: Boolean) { + refreshStatus() + if (success) { + // let the calling app (the keyboard) read the file through this content URI, + // even if it does not hold the provider read permission + val uri = Uri.parse(dictionaryFileUri(lang)) + callingPackage?.let { + try { + grantUriPermission(it, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) + } catch (_: Exception) { + } + } + setResult( + RESULT_OK, + Intent().putExtra(EXTRA_LANG, lang).putExtra(EXTRA_RESULT_URI, uri.toString()) + ) + } else { + setResult(RESULT_CANCELED, Intent().putExtra(EXTRA_LANG, lang).putExtra(EXTRA_ERROR, "download failed")) + } + // hand control back to the keyboard app + finish() + } + + private fun refreshStatus() { + val lines = AVAILABLE_DICTIONARIES.map { lang -> + val file = DictionaryDownloader.dictionaryFile(this, lang) + when { + DictionaryDownloader.isDownloaded(this, lang) -> + getString(R.string.dictionary_downloaded, lang, file.length() / 1024) + + DictionaryDownloader.isRunning(lang) -> + getString(R.string.downloading_dictionary, lang) + + else -> + getString(R.string.dictionary_missing, lang) + } + } + if (requestedLang == null || AVAILABLE_DICTIONARIES.isEmpty()) { + status.text = lines.joinToString("\n") + } + } +} diff --git a/dictionnary/src/main/kotlin/org/fossify/dictionnary/helpers/Constants.kt b/dictionnary/src/main/kotlin/org/fossify/dictionnary/helpers/Constants.kt new file mode 100644 index 000000000..6f3293445 --- /dev/null +++ b/dictionnary/src/main/kotlin/org/fossify/dictionnary/helpers/Constants.kt @@ -0,0 +1,87 @@ +package org.fossify.dictionnary.helpers + +// authority of the content provider used to share the downloaded dictionary files +const val AUTHORITY = "org.fossify.dictionnary.provider" + +// signature level permission, shared with the keyboard app when both are signed with the same key +const val ACCESS_PERMISSION = "org.fossify.dictionnary.ACCESS_DICTIONARIES" + +// base URL of the raw word frequency lists (OpenSubtitles 2018 by HermitDave/FrequencyWords, +// one "_50k.txt" file per language with "word count" per line). Only this app is +// allowed to reach the network; the lists are converted on the fly to the JSON format the +// keyboard expects (".json", wordfreq style: [ [word, log10(frequency)], ... ]). +const val DICTIONARY_BASE_URL = + "https://raw.githubusercontent.com/HermitDave/FrequencyWords/master/content/2018" + +// maps our dictionary codes (".json") to the language folder of the source lists +val DICTIONARY_SOURCE_CODES = mapOf( + "en_US" to "en", + "fr_FR" to "fr", + "de_DE" to "de", + "es_ES" to "es", + "it_IT" to "it", + "pt_PT" to "pt", + "nl_NL" to "nl", + "pl_PL" to "pl", + "sv_SE" to "sv", + "da_DK" to "da", + "nb_NO" to "no", + "ru_RU" to "ru", + "uk_UA" to "uk", + "cs_CZ" to "cs", + "tr_TR" to "tr", + "el_GR" to "el", + "he_IL" to "he", + "ar_AR" to "ar", + "bn_BD" to "bn", + "lv_LV" to "lv", + "lt_LT" to "lt", + "ro_RO" to "ro", + "sl_SI" to "sl", + "bg_BG" to "bg", + "eo" to "eo" +) + +// languages this app knows how to download and serve, the file name is ".json" +val AVAILABLE_DICTIONARIES = DICTIONARY_SOURCE_CODES.keys.toList() + +// raw "word count" list served for a dictionary language, null when the language is unknown +fun dictionarySourceUrl(lang: String): String? { + val code = DICTIONARY_SOURCE_CODES[lang] ?: return null + return "$DICTIONARY_BASE_URL/$code/${code}_50k.txt" +} + +// provider paths +const val PATH_DICTIONARIES = "dictionaries" +const val PATH_FILES = "files" + +// provider "call" methods +const val METHOD_DOWNLOAD = "download" +const val METHOD_LIST = "list" + +// activity action used by the keyboard app to ask for a download and get the result back +const val ACTION_DOWNLOAD_DICTIONARY = "org.fossify.dictionnary.action.DOWNLOAD_DICTIONARY" + +// intent extras +const val EXTRA_LANG = "lang" +const val EXTRA_STARTED = "started" +const val EXTRA_LANGUAGES = "languages" +const val EXTRA_CALLING_PACKAGE = "calling_package" +const val EXTRA_RESULT_URI = "result_uri" +const val EXTRA_ERROR = "error" + +// cursor columns returned by query() +const val COLUMN_ID = "_id" +const val COLUMN_LANG = "lang" +const val COLUMN_NAME = "name" +const val COLUMN_URI = "uri" +const val COLUMN_SIZE = "size" +const val COLUMN_DOWNLOADED = "downloaded" + +// uri matcher codes +const val CODE_DICTIONARIES = 1 +const val CODE_DICTIONARY = 2 +const val CODE_FILE = 3 + +fun dictionaryFileUri(lang: String): String = + "content://$AUTHORITY/$PATH_FILES/$PATH_DICTIONARIES/$lang.json" diff --git a/dictionnary/src/main/kotlin/org/fossify/dictionnary/helpers/DictionaryDownloader.kt b/dictionnary/src/main/kotlin/org/fossify/dictionnary/helpers/DictionaryDownloader.kt new file mode 100644 index 000000000..44d92df79 --- /dev/null +++ b/dictionnary/src/main/kotlin/org/fossify/dictionnary/helpers/DictionaryDownloader.kt @@ -0,0 +1,135 @@ +package org.fossify.dictionnary.helpers + +import android.content.Context +import org.json.JSONArray +import java.io.BufferedReader +import java.io.File +import java.io.OutputStream +import java.net.HttpURLConnection +import java.net.URL +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.Executors +import kotlin.math.log10 +import kotlin.math.roundToLong + +/** + * Downloads the dictionary files. This is the only place in the pair of apps where the + * network is used: the Dictionnary app holds the INTERNET permission, the keyboard app + * never touches the network and only reads the files through the content provider. + * + * The raw "word count" lists (see [DICTIONARY_BASE_URL]) are converted on the fly to the + * JSON format the keyboard loads: [ [word, log10(frequency)], ... ], most frequent first. + */ +object DictionaryDownloader { + // number of words kept per dictionary, same order of magnitude as the bundled en_US.json + private const val MAX_DICTIONARY_WORDS = 25000 + + private val executor = Executors.newCachedThreadPool() + private val running = ConcurrentHashMap() + private val listeners = ConcurrentHashMap Unit>>() + + fun dictionaryFile(context: Context, lang: String): File = + File(context.filesDir, "$PATH_DICTIONARIES/$lang.json") + + fun isDownloaded(context: Context, lang: String): Boolean { + val file = dictionaryFile(context, lang) + return file.isFile && file.length() > 0 + } + + fun isRunning(lang: String): Boolean = running.containsKey(lang) + + fun isValidLang(lang: String): Boolean = + lang.matches(Regex("[a-z]{2,3}(_[A-Za-z0-9]{2,8})*")) + + fun enqueueDownload(context: Context, lang: String, onComplete: ((Boolean) -> Unit)? = null) { + if (!isValidLang(lang) || dictionarySourceUrl(lang) == null) { + onComplete?.invoke(false) + return + } + if (isDownloaded(context, lang)) { + onComplete?.invoke(true) + return + } + if (onComplete != null) { + listeners.getOrPut(lang) { mutableListOf() }.add(onComplete) + } + if (running.putIfAbsent(lang, true) != null) { + return + } + val appContext = context.applicationContext + executor.execute { + val success = try { + downloadBlocking(appContext, lang) + } finally { + running.remove(lang) + } + val callbacks = listeners.remove(lang) ?: emptyList() + callbacks.forEach { it(success) } + } + } + + private fun downloadBlocking(context: Context, lang: String): Boolean { + val sourceUrl = dictionarySourceUrl(lang) ?: return false + val file = dictionaryFile(context, lang) + file.parentFile?.mkdirs() + val tmpFile = File(file.parentFile, file.name + ".tmp") + val connection = URL(sourceUrl).openConnection() as HttpURLConnection + connection.requestMethod = "GET" + connection.connectTimeout = 15000 + connection.readTimeout = 60000 + connection.instanceFollowRedirects = true + var success = false + try { + val entries = connection.inputStream.bufferedReader().use { reader -> + readFrequencyEntries(reader) + } + if (entries.isNotEmpty()) { + tmpFile.outputStream().use { output -> writeDictionaryJson(entries, output) } + success = tmpFile.isFile && tmpFile.length() > 0 + } + if (success) { + if (file.exists()) { + file.delete() + } + success = tmpFile.renameTo(file) + } + } catch (_: Exception) { + success = false + } finally { + if (!success) { + tmpFile.delete() + } + connection.disconnect() + } + return success + } + + /** reads "word count" lines from a raw frequency list, most frequent words first */ + private fun readFrequencyEntries(reader: BufferedReader): List> { + val entries = ArrayList>(MAX_DICTIONARY_WORDS) + while (entries.size < MAX_DICTIONARY_WORDS) { + val line = reader.readLine() ?: break + val separator = line.lastIndexOf(' ') + if (separator <= 0) { + continue + } + val count = line.substring(separator + 1).toLongOrNull() ?: continue + if (count <= 0) { + continue + } + entries.add(line.substring(0, separator) to count) + } + return entries + } + + /** writes the entries as wordfreq-style JSON: [ [word, log10(frequency)], ... ] */ + private fun writeDictionaryJson(entries: List>, output: OutputStream) { + val total = entries.sumOf { it.second }.toDouble() + val array = JSONArray() + for ((word, count) in entries) { + val logFrequency = (log10(count.toDouble() / total) * 10000).roundToLong() / 10000.0 + array.put(JSONArray().put(word).put(logFrequency)) + } + output.bufferedWriter().use { it.write(array.toString()) } + } +} diff --git a/dictionnary/src/main/kotlin/org/fossify/dictionnary/providers/DictionaryProvider.kt b/dictionnary/src/main/kotlin/org/fossify/dictionnary/providers/DictionaryProvider.kt new file mode 100644 index 000000000..c77c0d23e --- /dev/null +++ b/dictionnary/src/main/kotlin/org/fossify/dictionnary/providers/DictionaryProvider.kt @@ -0,0 +1,153 @@ +package org.fossify.dictionnary.providers + +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.content.UriMatcher +import android.database.Cursor +import android.database.MatrixCursor +import android.net.Uri +import android.os.Bundle +import android.os.ParcelFileDescriptor +import org.fossify.dictionnary.helpers.AUTHORITY +import org.fossify.dictionnary.helpers.AVAILABLE_DICTIONARIES +import org.fossify.dictionnary.helpers.CODE_DICTIONARIES +import org.fossify.dictionnary.helpers.CODE_DICTIONARY +import org.fossify.dictionnary.helpers.CODE_FILE +import org.fossify.dictionnary.helpers.COLUMN_DOWNLOADED +import org.fossify.dictionnary.helpers.COLUMN_ID +import org.fossify.dictionnary.helpers.COLUMN_LANG +import org.fossify.dictionnary.helpers.COLUMN_NAME +import org.fossify.dictionnary.helpers.COLUMN_SIZE +import org.fossify.dictionnary.helpers.COLUMN_URI +import org.fossify.dictionnary.helpers.DictionaryDownloader +import org.fossify.dictionnary.helpers.EXTRA_LANG +import org.fossify.dictionnary.helpers.EXTRA_LANGUAGES +import org.fossify.dictionnary.helpers.EXTRA_STARTED +import org.fossify.dictionnary.helpers.METHOD_DOWNLOAD +import org.fossify.dictionnary.helpers.METHOD_LIST +import org.fossify.dictionnary.helpers.PATH_DICTIONARIES +import org.fossify.dictionnary.helpers.PATH_FILES +import org.fossify.dictionnary.helpers.dictionaryFileUri +import java.io.File +import java.io.FileNotFoundException + +/** + * Shares the downloaded dictionary files with the keyboard app through content URIs. + * + * - content://AUTHORITY/dictionaries -> cursor with one row per dictionary + * - content://AUTHORITY/dictionaries/ -> cursor with a single row for + * - content://AUTHORITY/files/dictionaries/.json -> the file itself (openFile) + * + * Rows contain the columns _id, lang, name, uri, size and downloaded. Asking for a + * dictionary that is not downloaded yet automatically enqueues its download. + */ +class DictionaryProvider : ContentProvider() { + private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply { + addURI(AUTHORITY, PATH_DICTIONARIES, CODE_DICTIONARIES) + addURI(AUTHORITY, "$PATH_DICTIONARIES/*", CODE_DICTIONARY) + addURI(AUTHORITY, "$PATH_FILES/*", CODE_FILE) + addURI(AUTHORITY, "$PATH_FILES/*/*", CODE_FILE) + } + + override fun onCreate(): Boolean = true + + override fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String? + ): Cursor { + val context = requireProviderContext() + val cursor = MatrixCursor( + arrayOf(COLUMN_ID, COLUMN_LANG, COLUMN_NAME, COLUMN_URI, COLUMN_SIZE, COLUMN_DOWNLOADED) + ) + when (uriMatcher.match(uri)) { + CODE_DICTIONARIES -> AVAILABLE_DICTIONARIES.forEachIndexed { index, lang -> + cursor.addRow(dictionaryRow(context, index, lang)) + } + + CODE_DICTIONARY -> { + val lang = uri.lastPathSegment.orEmpty() + if (DictionaryDownloader.isValidLang(lang)) { + cursor.addRow(dictionaryRow(context, 0, lang)) + } + } + } + return cursor + } + + private fun dictionaryRow(context: Context, id: Int, lang: String): Array { + val file = DictionaryDownloader.dictionaryFile(context, lang) + val downloaded = DictionaryDownloader.isDownloaded(context, lang) + if (!downloaded) { + // make sure asking for a dictionary also starts its download + DictionaryDownloader.enqueueDownload(context, lang) + } + return arrayOf( + id, + lang, + "$lang.json", + dictionaryFileUri(lang), + file.length(), + if (downloaded) 1 else 0 + ) + } + + override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor { + if (uriMatcher.match(uri) != CODE_FILE) { + throw FileNotFoundException("unsupported uri: $uri") + } + val context = requireProviderContext() + val relativePath = uri.pathSegments.drop(1).joinToString("/") + val dictionariesRoot = File(context.filesDir, PATH_DICTIONARIES) + val file = File(context.filesDir, relativePath) + if (!file.canonicalPath.startsWith(dictionariesRoot.canonicalPath + File.separator)) { + throw FileNotFoundException("forbidden path: $relativePath") + } + val lang = file.name.removeSuffix(".json") + if (!DictionaryDownloader.isDownloaded(context, lang)) { + DictionaryDownloader.enqueueDownload(context, lang) + throw FileNotFoundException("dictionary '$lang' is not downloaded yet") + } + return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) + } + + override fun call(method: String, arg: String?, extras: Bundle?): Bundle { + val context = context ?: return Bundle() + val result = Bundle() + when (method) { + METHOD_DOWNLOAD -> { + val lang = arg ?: extras?.getString(EXTRA_LANG).orEmpty() + DictionaryDownloader.enqueueDownload(context, lang) + result.putString(EXTRA_LANG, lang) + result.putBoolean(EXTRA_STARTED, DictionaryDownloader.isValidLang(lang)) + } + + METHOD_LIST -> { + result.putStringArray(EXTRA_LANGUAGES, AVAILABLE_DICTIONARIES.toTypedArray()) + } + } + return result + } + + override fun getType(uri: Uri): String = when (uriMatcher.match(uri)) { + CODE_DICTIONARIES -> "vnd.android.cursor.dir/vnd.$AUTHORITY.dictionary" + CODE_DICTIONARY -> "vnd.android.cursor.item/vnd.$AUTHORITY.dictionary" + else -> "application/json" + } + + override fun insert(uri: Uri, values: ContentValues?): Uri? = null + + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = 0 + + override fun update( + uri: Uri, + values: ContentValues?, + selection: String?, + selectionArgs: Array? + ): Int = 0 + + private fun requireProviderContext(): Context = context ?: throw IllegalStateException("Provider not attached") +} diff --git a/dictionnary/src/main/res/layout/activity_main.xml b/dictionnary/src/main/res/layout/activity_main.xml new file mode 100644 index 000000000..1547f3d77 --- /dev/null +++ b/dictionnary/src/main/res/layout/activity_main.xml @@ -0,0 +1,41 @@ + + + + + + + + + +