diff --git a/app/src/main/java/helium314/keyboard/latin/ai/AiResultChecks.kt b/app/src/main/java/helium314/keyboard/latin/ai/AiResultChecks.kt new file mode 100644 index 000000000..761df941c --- /dev/null +++ b/app/src/main/java/helium314/keyboard/latin/ai/AiResultChecks.kt @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin.ai + +/** Checks on what an AI model returned, before it replaces the user's text */ +object AiResultChecks { + /** a corrected text keeps about its length */ + const val MIN_PROOFREAD_SHARE = 0.7 + /** a translation can be much shorter than its source, e.g. into Chinese */ + const val MIN_TRANSLATION_SHARE = 0.3 + + /** whether [result] is so much shorter than [input] that parts of it are most likely missing */ + fun isCutOff(result: String, input: String, minShare: Double): Boolean = + input.length > 20 && result.length < input.length * minShare + + // only at the start of the answer, and only with a colon: other lines belong to the translation + private val TRANSLATION_PREAMBLE = Regex( + "^(?:sure[,!.]\\s*(?=here))?" + + "(?:(?:here(?:'s|\\s+is)\\s+(?:the\\s+)?)?(?:translated\\s+text|translation)|text\\s+to\\s+translate|output|result|response)" + + "(?:\\s+(?:in|into|to)\\s+\\p{L}+)?\\s*:\\s*", + RegexOption.IGNORE_CASE + ) + + fun stripTranslationPreamble(text: String): String = text.replace(TRANSLATION_PREAMBLE, "").trim() +} diff --git a/app/src/main/java/helium314/keyboard/latin/ai/OfflineAiLoader.kt b/app/src/main/java/helium314/keyboard/latin/ai/OfflineAiLoader.kt index bda91e126..e05864df8 100644 --- a/app/src/main/java/helium314/keyboard/latin/ai/OfflineAiLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/ai/OfflineAiLoader.kt @@ -5,6 +5,7 @@ import android.content.Context import android.net.Uri import dalvik.system.DexClassLoader import helium314.keyboard.compat.contentLengthLongCompat +import helium314.keyboard.latin.utils.replaceFile import helium314.keyboard.latin.utils.Log import helium314.keyboard.latin.utils.prefs import java.io.File @@ -206,27 +207,29 @@ object OfflineAiLoader { } catch (_: Exception) {} val targetFile = File(context.filesDir, PLUGIN_FILENAME) - if (targetFile.exists()) targetFile.delete() + val success = replaceFile(targetFile, write = { + context.contentResolver.openInputStream(sourceUri)?.use { input -> + java.io.FileOutputStream(it).use { output -> + input.copyTo(output) + } + } ?: error("the file can't be opened") + }) { + targetFile.setReadOnly() + activeProvider?.cleanup() + activeProvider = null - context.contentResolver.openInputStream(sourceUri)?.use { input -> - java.io.FileOutputStream(targetFile).use { output -> - input.copyTo(output) + val provider = loadProviderInternal(context, targetFile) + val accepted = provider != null && provider.isAvailable() + if (accepted) { + activeProvider = provider } - } ?: return false - - targetFile.setReadOnly() - activeProvider?.cleanup() - activeProvider = null - - val provider = loadProviderInternal(context, targetFile) - val success = provider != null && provider.isAvailable() + accepted + } if (success) { - activeProvider = provider context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, true).apply() Log.i(TAG, "Plugin imported and registered successfully") } else { - targetFile.delete() - context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, false).apply() + context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, targetFile.exists()).apply() Log.w(TAG, "Plugin import verification failed") } success @@ -243,24 +246,27 @@ object OfflineAiLoader { } catch (_: Exception) {} val targetFile = File(context.filesDir, PLUGIN_FILENAME) - if (targetFile.exists()) targetFile.delete() + val success = replaceFile(targetFile, write = { + tempFile.copyTo(it, overwrite = true) + tempFile.delete() + }) { + targetFile.setReadOnly() - tempFile.copyTo(targetFile, overwrite = true) - tempFile.delete() - targetFile.setReadOnly() + activeProvider?.cleanup() + activeProvider = null - activeProvider?.cleanup() - activeProvider = null - - val provider = loadProviderInternal(context, targetFile) - val success = provider != null && provider.isAvailable() + val provider = loadProviderInternal(context, targetFile) + val accepted = provider != null && provider.isAvailable() + if (accepted) { + activeProvider = provider + } + accepted + } if (success) { - activeProvider = provider context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, true).apply() Log.i(TAG, "Plugin imported from temp file successfully") } else { - targetFile.delete() - context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, false).apply() + context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, targetFile.exists()).apply() Log.w(TAG, "Plugin temp file verification failed") } success @@ -289,11 +295,11 @@ object OfflineAiLoader { } } - @Volatile - var isBusy: Boolean = false + /** the number of requests that use the model */ + val busy = java.util.concurrent.atomic.AtomicInteger() fun onTrimMemory() { - if (isBusy) { + if (busy.get() > 0) { Log.i(TAG, "Skipping memory trim: offline AI is currently busy") return } diff --git a/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt b/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt index 2a52a59d6..537d08fa2 100644 --- a/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt @@ -5,6 +5,7 @@ import android.content.Context import android.net.Uri import android.os.Build import dalvik.system.DexClassLoader +import helium314.keyboard.latin.utils.replaceFile import helium314.keyboard.latin.BuildConfig import helium314.keyboard.latin.utils.Log import helium314.keyboard.latin.utils.prefs @@ -316,28 +317,30 @@ object CjkPluginLoader { } catch (_: Exception) {} val targetFile = File(context.filesDir, PLUGIN_FILENAME) - if (targetFile.exists()) targetFile.delete() - - context.contentResolver.openInputStream(sourceUri)?.use { input -> - java.io.FileOutputStream(targetFile).use { output -> - input.copyTo(output) + val success = replaceFile(targetFile, write = { + context.contentResolver.openInputStream(sourceUri)?.use { input -> + java.io.FileOutputStream(it).use { output -> + input.copyTo(output) + } + } ?: error("the file can't be opened") + }) { + targetFile.setReadOnly() + activeEngine?.cleanup() + activeEngine = null + + val engine = loadEngineInternal(context, targetFile) + val accepted = engine != null && isUsable(engine) + if (accepted) { + activeEngine = engine + lastApkModified = targetFile.lastModified() } - } ?: return false - - targetFile.setReadOnly() - activeEngine?.cleanup() - activeEngine = null - - val engine = loadEngineInternal(context, targetFile) - val success = engine != null && isUsable(engine) + accepted + } if (success) { - activeEngine = engine - lastApkModified = targetFile.lastModified() context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, true).apply() Log.i(TAG, "CJK plugin imported and verified successfully") } else { - targetFile.delete() - context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, false).apply() + context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, targetFile.exists()).apply() Log.w(TAG, "CJK plugin verification failed") } success @@ -355,25 +358,27 @@ object CjkPluginLoader { } catch (_: Exception) {} val targetFile = File(context.filesDir, PLUGIN_FILENAME) - if (targetFile.exists()) targetFile.delete() - - tempFile.copyTo(targetFile, overwrite = true) - tempFile.delete() - - targetFile.setReadOnly() - activeEngine?.cleanup() - activeEngine = null - - val engine = loadEngineInternal(context, targetFile) - val success = engine != null && isUsable(engine) + val success = replaceFile(targetFile, write = { + tempFile.copyTo(it, overwrite = true) + tempFile.delete() + }) { + targetFile.setReadOnly() + activeEngine?.cleanup() + activeEngine = null + + val engine = loadEngineInternal(context, targetFile) + val accepted = engine != null && isUsable(engine) + if (accepted) { + activeEngine = engine + lastApkModified = targetFile.lastModified() + } + accepted + } if (success) { - activeEngine = engine - lastApkModified = targetFile.lastModified() context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, true).apply() Log.i(TAG, "CJK plugin imported from temp file and verified successfully") } else { - targetFile.delete() - context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, false).apply() + context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, targetFile.exists()).apply() Log.w(TAG, "CJK plugin verification failed") } success diff --git a/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt b/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt index 4b01b0254..7b22259dc 100644 --- a/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt +++ b/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt @@ -22,6 +22,7 @@ import helium314.keyboard.compat.AppQuirksManager import helium314.keyboard.compat.isDeviceLocked import helium314.keyboard.event.Event import helium314.keyboard.event.InputTransaction +import helium314.keyboard.latin.ai.AiResultChecks import helium314.keyboard.latin.cjk.CjkInputManager import helium314.keyboard.keyboard.Keyboard import helium314.keyboard.keyboard.KeyboardActionListenerImpl @@ -687,6 +688,30 @@ class InputLogic( mLatinIME.onTextInput(clipboardContent) } + /** The text an AI action works on: the selection, or else the whole text. It is not selected for that. */ + private fun readAiInput(hasSelection: Boolean): String { + if (hasSelection) return mConnection.getSelectedText(0)?.toString() ?: "" + val maxChars = 60000 + var textBefore: CharSequence? = null + var textAfter: CharSequence? = null + try { + textBefore = mConnection.getTextBeforeCursor(maxChars, 0) + } catch (e: Exception) { + Log.e(TAG, "Failed to get text before cursor: $e") + } + try { + textAfter = mConnection.getTextAfterCursor(maxChars, 0) + } catch (e: Exception) { + Log.e(TAG, "Failed to get text after cursor: $e") + try { + textAfter = mConnection.getTextAfterCursor(2048, 0) + } catch (e2: Exception) { + Log.e(TAG, "Failed to get text after cursor (retry): $e2") + } + } + return (textBefore?.toString() ?: "") + (textAfter?.toString() ?: "") + } + private fun handleProofread() { Log.i(TAG, "handleProofread() called") if (ProofreadHelper.isOperationInProgress) { @@ -694,37 +719,8 @@ class InputLogic( ProofreadHelper.cancelCurrentOperation() return } - val textToProofread: String val hasSelection = mConnection.hasSelection() - - if (hasSelection) { - val selectedText = mConnection.getSelectedText(0) - textToProofread = selectedText?.toString() ?: "" - Log.i(TAG, "Proofreading selected text: ${textToProofread.length} chars") - } else { - val maxChars = 60000 - var textBefore: CharSequence? = null - var textAfter: CharSequence? = null - try { - textBefore = mConnection.getTextBeforeCursor(maxChars, 0) - } catch (e: Exception) { - Log.e(TAG, "Failed to get text before cursor: $e") - } - try { - textAfter = mConnection.getTextAfterCursor(maxChars, 0) - } catch (e: Exception) { - Log.e(TAG, "Failed to get text after cursor: $e") - try { - textAfter = mConnection.getTextAfterCursor(2048, 0) - } catch (e2: Exception) { - Log.e(TAG, "Failed to get text after cursor (retry): $e2") - } - } - val before = textBefore?.toString() ?: "" - val after = textAfter?.toString() ?: "" - textToProofread = before + after - mConnection.selectAll() - } + val textToProofread = readAiInput(hasSelection) mTextBeforeProofread = textToProofread val targetEditorInfo = getCurrentInputEditorInfo() @@ -747,25 +743,18 @@ class InputLogic( } val textBefore = mTextBeforeProofread if (proofreadText.isNotEmpty() && proofreadText != textBefore) { - if (textBefore != null && textBefore.length > 20 && proofreadText.length < textBefore.length * 0.3) { + // the user may have typed or moved while the AI was working: don't overwrite that + if (readAiInput(hasSelection) != textBefore) { + Log.w(TAG, "Text changed during proofread, ignoring result") + KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.ai_cancelled), true) + return@proofreadAsync + } + if (textBefore != null && AiResultChecks.isCutOff(proofreadText, textBefore, AiResultChecks.MIN_PROOFREAD_SHARE)) { Log.w(TAG, "Proofread result suspiciously short (${proofreadText.length} vs ${textBefore.length}), aborting replacement to prevent truncation data loss") KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.proofread_output_truncated), false) - if (!hasSelection) { - val len = textBefore.length - mConnection.setSelection(len, len) - } return@proofreadAsync } - if (hasSelection) { - mConnection.commitText(proofreadText, 1) - } else { - mConnection.replaceEntireText(proofreadText) - } - } else { - if (!hasSelection) { - val len = textBefore?.length ?: 0 - mConnection.setSelection(len, len) - } + insertCustomAiResult(proofreadText, false, hasSelection) } }, onError = { errorMessage -> @@ -781,38 +770,8 @@ class InputLogic( KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.ai_cancelled), true) return } - val textToTranslate: String val hasSelection = mConnection.hasSelection() - - if (hasSelection) { - val selectedText = mConnection.getSelectedText(0) - textToTranslate = selectedText?.toString() ?: "" - } else { - val maxChars = 60000 - var textBefore: CharSequence? = null - var textAfter: CharSequence? = null - try { - textBefore = mConnection.getTextBeforeCursor(maxChars, 0) - } catch (e: Exception) { - Log.e(TAG, "Failed to get text before cursor: $e") - } - try { - textAfter = mConnection.getTextAfterCursor(maxChars, 0) - } catch (e: Exception) { - Log.e(TAG, "Failed to get text after cursor: $e") - try { - textAfter = mConnection.getTextAfterCursor(2048, 0) - } catch (e2: Exception) { - Log.e(TAG, "Failed to get text after cursor (retry): $e2") - } - } - val before = textBefore?.toString() ?: "" - val after = textAfter?.toString() ?: "" - textToTranslate = before + after - if (textToTranslate.isNotBlank()) { - mConnection.selectAll() - } - } + val textToTranslate = readAiInput(hasSelection) if (textToTranslate.isBlank()) { KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.translate_no_text), false) @@ -840,28 +799,20 @@ class InputLogic( } val textBefore = mTextBeforeTranslate if (translatedText.isNotEmpty() && translatedText != textBefore) { - if (textBefore != null && textBefore.length > 20 && translatedText.length < textBefore.length * 0.3) { + // the user may have typed or moved while the AI was working: don't overwrite that + if (readAiInput(hasSelection) != textBefore) { + Log.w(TAG, "Text changed during translation, ignoring result") + KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.ai_cancelled), true) + return@translateAsync + } + if (textBefore != null && AiResultChecks.isCutOff(translatedText, textBefore, AiResultChecks.MIN_TRANSLATION_SHARE)) { Log.w(TAG, "Translation result suspiciously short (${translatedText.length} vs ${textBefore.length}), aborting replacement to prevent truncation data loss") KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.translation_output_truncated), false) - if (!hasSelection) { - val len = textBefore.length - mConnection.setSelection(len, len) - } return@translateAsync } - if (hasSelection) { - mConnection.commitText(translatedText, 1) - } else { - mConnection.replaceEntireText(translatedText) - } - } else { - if (!hasSelection) { - val len = textBefore?.length ?: 0 - mConnection.setSelection(len, len) - } - if (translatedText == textBefore) { - KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.translation_unchanged), false) - } + insertCustomAiResult(translatedText, false, hasSelection) + } else if (translatedText == textBefore) { + KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.translation_unchanged), false) } }, onError = { errorMessage -> diff --git a/app/src/main/java/helium314/keyboard/latin/ocr/OcrPluginLoader.kt b/app/src/main/java/helium314/keyboard/latin/ocr/OcrPluginLoader.kt index a165692f0..12ff62019 100644 --- a/app/src/main/java/helium314/keyboard/latin/ocr/OcrPluginLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/ocr/OcrPluginLoader.kt @@ -5,6 +5,7 @@ import android.content.Context import android.net.Uri import dalvik.system.DexClassLoader import helium314.keyboard.compat.contentLengthLongCompat +import helium314.keyboard.latin.utils.replaceFile import helium314.keyboard.latin.utils.Log import helium314.keyboard.latin.utils.prefs import java.io.File @@ -281,25 +282,26 @@ object OcrPluginLoader { } catch (_: Exception) {} val targetFile = File(context.filesDir, PLUGIN_FILENAME) - if (targetFile.exists()) targetFile.delete() - - context.contentResolver.openInputStream(uri)?.use { input -> - java.io.FileOutputStream(targetFile).use { output -> - input.copyTo(output) - } - } ?: return false - - targetFile.setReadOnly() - invalidateClassLoader() - - val recognizer = loadRecognizerInternal(context, targetFile) - val success = recognizer != null + val success = replaceFile(targetFile, write = { + context.contentResolver.openInputStream(uri)?.use { input -> + java.io.FileOutputStream(it).use { output -> + input.copyTo(output) + } + } ?: error("the file can't be opened") + }) { + targetFile.setReadOnly() + invalidateClassLoader() + + val recognizer = loadRecognizerInternal(context, targetFile) + val accepted = recognizer != null + accepted + } if (success) { context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, true).apply() Log.i(TAG, "OCR plugin imported and verified successfully") } else { - targetFile.delete() - context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, false).apply() + invalidateClassLoader() // of the rejected file + context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, targetFile.exists()).apply() Log.w(TAG, "OCR plugin verification failed") } success @@ -316,22 +318,24 @@ object OcrPluginLoader { } catch (_: Exception) {} val targetFile = File(context.filesDir, PLUGIN_FILENAME) - if (targetFile.exists()) targetFile.delete() + val success = replaceFile(targetFile, write = { + tempFile.copyTo(it, overwrite = true) + tempFile.delete() + }) { + targetFile.setReadOnly() - tempFile.copyTo(targetFile, overwrite = true) - tempFile.delete() - targetFile.setReadOnly() + invalidateClassLoader() - invalidateClassLoader() - - val recognizer = loadRecognizerInternal(context, targetFile) - val success = recognizer != null + val recognizer = loadRecognizerInternal(context, targetFile) + val accepted = recognizer != null + accepted + } if (success) { context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, true).apply() Log.i(TAG, "OCR plugin imported from temp file successfully") } else { - targetFile.delete() - context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, false).apply() + invalidateClassLoader() // of the rejected file + context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, targetFile.exists()).apply() Log.w(TAG, "OCR plugin temp file verification failed") } success diff --git a/app/src/main/java/helium314/keyboard/latin/utils/ReplaceFile.kt b/app/src/main/java/helium314/keyboard/latin/utils/ReplaceFile.kt new file mode 100644 index 000000000..f2e688595 --- /dev/null +++ b/app/src/main/java/helium314/keyboard/latin/utils/ReplaceFile.kt @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin.utils + +import java.io.File + +/** + * Replaces [target] with what [write] puts there, and keeps it only if [verify] accepts it. Otherwise, also if one of + * them throws, the previous file is back. + */ +fun replaceFile(target: File, write: (File) -> Unit, verify: () -> Boolean): Boolean { + val previous = File(target.path + ".old") + previous.delete() + if (target.exists() && !target.renameTo(previous)) return false + val success = try { + write(target) + verify() + } catch (e: Throwable) { + Log.e("replaceFile", "could not replace ${target.name}", e) + false + } + if (success) previous.delete() + else { + target.delete() + if (previous.exists()) previous.renameTo(target) + } + return success +} diff --git a/app/src/main/java/helium314/keyboard/settings/preferences/BackupRestorePreference.kt b/app/src/main/java/helium314/keyboard/settings/preferences/BackupRestorePreference.kt index 35a93ce6c..abfd4e846 100644 --- a/app/src/main/java/helium314/keyboard/settings/preferences/BackupRestorePreference.kt +++ b/app/src/main/java/helium314/keyboard/settings/preferences/BackupRestorePreference.kt @@ -55,6 +55,7 @@ import helium314.keyboard.settings.dialogs.InfoDialog import helium314.keyboard.settings.filePicker import kotlinx.serialization.json.Json import java.io.File +import java.io.InputStream import java.io.FileInputStream import java.io.OutputStream import java.text.SimpleDateFormat @@ -325,6 +326,11 @@ private fun restoreLauncher( val restoredDb = ctx.getDatabasePath(Database.NAME + "_restored") ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD).execute { try { + // read the whole file before anything is deleted, and only replace what it contains + val contained = ctx.getActivity()?.contentResolver?.openInputStream(uri)?.use { categoriesInBackup(it) } + ?: return@execute + val replaced = selectedCategories.intersect(contained) + restoredDb.delete() // from an earlier restore that failed ctx.getActivity()?.contentResolver?.openInputStream(uri)?.use { inputStream -> ZipInputStream(inputStream).use { zip -> var entry: ZipEntry? = zip.nextEntry @@ -334,35 +340,35 @@ private fun restoreLauncher( var protectedPreferenceLines: List? = null // Targeted deletion based on selected categories - if (selectedCategories.contains(BackupCategory.LAYOUTS)) { + if (replaced.contains(BackupCategory.LAYOUTS)) { File(filesDir, "layouts").deleteRecursively() } - if (selectedCategories.contains(BackupCategory.DICTIONARIES)) { + if (replaced.contains(BackupCategory.DICTIONARIES)) { File(filesDir, "dicts").deleteRecursively() File(filesDir, "blacklists").deleteRecursively() File(deviceProtectedFilesDir, "blacklists").deleteRecursively() } - if (selectedCategories.contains(BackupCategory.TEXT_EXPANDER)) { + if (replaced.contains(BackupCategory.TEXT_EXPANDER)) { File(filesDir, "text_expander_images").deleteRecursively() File(deviceProtectedFilesDir, "text_expander_images").deleteRecursively() helium314.keyboard.latin.utils.TextExpanderImageUtils.clearCache() } - if (selectedCategories.contains(BackupCategory.TYPING_HISTORY)) { + if (replaced.contains(BackupCategory.TYPING_HISTORY)) { filesDir.listFiles()?.forEach { if (it.name.startsWith("UserHistoryDictionary")) it.delete() } } - if (selectedCategories.contains(BackupCategory.API_KEYS)) { + if (replaced.contains(BackupCategory.API_KEYS)) { ProofreadService(ctx).clearSecureSettings() } - if (selectedCategories.contains(BackupCategory.THEME_APPEARANCE)) { + if (replaced.contains(BackupCategory.THEME_APPEARANCE)) { File(filesDir, "custom_font").delete() File(filesDir, "custom_emoji_font").delete() deviceProtectedFilesDir.listFiles()?.forEach { if (it.name.startsWith("custom_background_image")) it.delete() } } - if (selectedCategories.contains(BackupCategory.CLIPBOARD)) { + if (replaced.contains(BackupCategory.CLIPBOARD)) { ClipboardDao.closeInstance() Database.closeInstance() ctx.deleteDatabase(Database.NAME) @@ -428,7 +434,7 @@ private fun restoreLauncher( ) } } - if (selectedCategories.contains(BackupCategory.CLIPBOARD)) { + if (replaced.contains(BackupCategory.CLIPBOARD)) { Database.copyFromDb(restoredDb, ctx) } Handler(Looper.getMainLooper()).post { @@ -672,6 +678,30 @@ internal fun getCategoryForPrefKey(key: String): BackupCategory { return BackupCategory.GENERAL_SETTINGS } +/** + * The categories the backup in [input] has files for. Reads every entry completely, so a damaged file fails here. + * Throws if there is nothing of a backup in it, e.g. because it's not a zip file. + */ +internal fun categoriesInBackup(input: InputStream): Set { + val names = mutableListOf() + ZipInputStream(input).use { zip -> + val buffer = ByteArray(8192) + var entry = zip.nextEntry + while (entry != null) { + names.add(entry.name.removePrefix("unprotected/")) + while (zip.read(buffer) >= 0) { /* checks the content */ } + entry = zip.nextEntry + } + } + require(names.any { name -> + name == PREFS_FILE_NAME || name == PROTECTED_PREFS_FILE_NAME || name == API_KEYS_FILE_NAME || name == Database.NAME + || name == PersonalDictionaryTransfer.BACKUP_ENTRY_NAME || name.endsWith("preferences.json") + || backupFilePatterns.any { name.matches(it) } + }) { "not a backup file" } + // the floating keyboard preferences are in the theme category, but are no reason to delete theme files + return names.filter { it != FLOATING_KEYBOARD_PREFS_FILE_NAME }.mapNotNullTo(mutableSetOf(), ::getCategoryForFilePath) +} + internal fun getCategoryForFilePath(path: String): BackupCategory? { if (path.startsWith("layouts${File.separator}") || path.contains("layouts/")) { return BackupCategory.LAYOUTS diff --git a/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt b/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt index f84f813d1..f6f1f5f8f 100644 --- a/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt +++ b/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt @@ -46,6 +46,8 @@ object ProofreadHelper { val service = ProofreadService(context) val modelPath = service.getModelPath() if (modelPath.isNullOrBlank()) return + // the last load never finished, e.g. the model doesn't fit in memory: only load it when asked to + if (context.prefs().getBoolean(ProofreadService.KEY_LOAD_UNFINISHED, false)) return if (isPreloaded.compareAndSet(false, true)) { scope.launch { ProofreadService.ModelHolder.loadModel(context, modelPath) diff --git a/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt b/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt index 346c37b1c..52dd5f00e 100644 --- a/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt +++ b/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt @@ -4,6 +4,7 @@ */ package helium314.keyboard.latin.utils +import androidx.core.content.edit import android.content.Context import android.content.SharedPreferences import android.net.Uri @@ -118,7 +119,13 @@ class ProofreadService(private val context: Context) { val threads = if (cores <= 4) cores else 4 Log.i(TAG, "Loading GGUF model via AI Plugin: path=$modelPath threads=$threads") - val success = provider.loadModel(context, modelPath, threads, 4096) + // stays set if Android kills the keyboard while loading, then the model is not preloaded again + context.prefs().edit(commit = true) { putBoolean(KEY_LOAD_UNFINISHED, true) } + val success = try { + provider.loadModel(context, modelPath, threads, 4096) + } finally { + context.prefs().edit { remove(KEY_LOAD_UNFINISHED) } + } if (success) { currentModelPath = modelPath isModelLoaded = true @@ -183,7 +190,8 @@ class ProofreadService(private val context: Context) { } apply() } - ModelHolder.unloadModel() + context.prefs().edit { remove(KEY_LOAD_UNFINISHED) } // another model gets a new chance + ModelHolder.unloadModel(context) } // Decoder path (kept for API compatibility, not used with llamacpp) @@ -319,7 +327,7 @@ class ProofreadService(private val context: Context) { Result.failure(Exception("Online voice transcription is not supported in offline flavor")) fun unloadModel() { - ModelHolder.unloadModel() + ModelHolder.unloadModel(context) } /** @@ -340,6 +348,21 @@ class ProofreadService(private val context: Context) { overridePrompt: String? = null, showThinking: Boolean? = null, targetLanguage: String? = null + ): Result { + // busy from before loading until the answer is back: a memory warning must not unload the model in between + OfflineAiLoader.busy.incrementAndGet() + try { + return generate(text, overridePrompt, showThinking, targetLanguage) + } finally { + OfflineAiLoader.busy.decrementAndGet() + } + } + + private suspend fun generate( + text: String, + overridePrompt: String?, + showThinking: Boolean?, + targetLanguage: String? ): Result = withContext(Dispatchers.IO) { if (text.length > 12000) { return@withContext Result.failure(ProofreadException("Text is too long for offline model (${text.length} characters). Please select a shorter passage.")) @@ -425,19 +448,13 @@ class ProofreadService(private val context: Context) { ModelHolder.scheduleUnload(context) return@withContext Result.failure(ProofreadException("Cancelled")) } - // set and cleared inside the lock: a waiting request can't clear it while another one runs - OfflineAiLoader.isBusy = true - try { - provider.generate(fullPrompt, mapOf( - "temperature" to temp.toDouble(), - "top_p" to topP.toDouble(), - "top_k" to topK, - "min_p" to minP.toDouble(), - "max_tokens" to effectiveMaxTokens - )) - } finally { - OfflineAiLoader.isBusy = false - } + provider.generate(fullPrompt, mapOf( + "temperature" to temp.toDouble(), + "top_p" to topP.toDouble(), + "top_k" to topK, + "min_p" to minP.toDouble(), + "max_tokens" to effectiveMaxTokens + )) } // Schedule unload after work is done @@ -555,14 +572,7 @@ class ProofreadService(private val context: Context) { } // 3. Strip conversational preambles and section prefixes (e.g., "Translation:", "Output:") - val prefixRegex = Regex( - "^(?i)(?:sure[,!.]?\\s*(?:here(?:'s|\\s+is)\\s+(?:the\\s+)?(?:translated\\s+text|translation)[^:\n]*:?)?|" + - "(?:here(?:'s|\\s+is)\\s+(?:the\\s+)?(?:translated\\s+text|translation)[^:\n]*:?)|" + - "(?:translated\\s+text|translation|output|result|response)[^:\n]*:?|" + - "text\\s+to\\s+translate:?)\\s*", - RegexOption.MULTILINE - ) - cleaned = cleaned.replace(prefixRegex, "").trim() + cleaned = helium314.keyboard.latin.ai.AiResultChecks.stripTranslationPreamble(cleaned) // 4. Remove markdown code fences if wrapped in ```...``` if (cleaned.startsWith("```") && cleaned.endsWith("```") && cleaned.length >= 6) { @@ -742,6 +752,7 @@ class ProofreadService(private val context: Context) { companion object { private const val TAG = "LlamaProofreadService" private const val KEY_MODEL_PATH = "offline_model_path" + internal const val KEY_LOAD_UNFINISHED = "offline_model_load_unfinished" private const val KEY_DECODER_PATH = "offline_decoder_path" private const val KEY_TOKENIZER_PATH = "offline_tokenizer_path" val AVAILABLE_MODELS = listOf("GGUF Model (Local)") diff --git a/app/src/standard/java/helium314/keyboard/latin/utils/ProofreadService.kt b/app/src/standard/java/helium314/keyboard/latin/utils/ProofreadService.kt index 92e8413a8..2d7cba2cf 100644 --- a/app/src/standard/java/helium314/keyboard/latin/utils/ProofreadService.kt +++ b/app/src/standard/java/helium314/keyboard/latin/utils/ProofreadService.kt @@ -1170,14 +1170,7 @@ Text to proofread: } // 2. Strip leading conversational preambles and section prefixes - val prefixRegex = Regex( - "^(?i)(?:sure[,!.]?\\s*(?:here(?:'s|\\s+is)\\s+(?:the\\s+)?(?:translated\\s+text|translation)[^:\n]*:?)?|" + - "(?:here(?:'s|\\s+is)\\s+(?:the\\s+)?(?:translated\\s+text|translation)[^:\n]*:?)|" + - "(?:translated\\s+text|translation)[^:\n]*:?|" + - "text\\s+to\\s+translate:?)\\s*", - RegexOption.MULTILINE - ) - cleaned = cleaned.replace(prefixRegex, "").trim() + cleaned = helium314.keyboard.latin.ai.AiResultChecks.stripTranslationPreamble(cleaned) // 3. Remove markdown code blocks if wrapped in ```...``` if (cleaned.startsWith("```") && cleaned.endsWith("```") && cleaned.length >= 6) { diff --git a/app/src/test/java/helium314/keyboard/latin/AiResultChecksTest.kt b/app/src/test/java/helium314/keyboard/latin/AiResultChecksTest.kt new file mode 100644 index 000000000..da6b33956 --- /dev/null +++ b/app/src/test/java/helium314/keyboard/latin/AiResultChecksTest.kt @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin + +import helium314.keyboard.latin.ai.AiResultChecks +import helium314.keyboard.latin.ai.AiResultChecks.isCutOff +import helium314.keyboard.latin.ai.AiResultChecks.stripTranslationPreamble +import kotlin.test.Test +import kotlin.test.assertEquals + +class AiResultChecksTest { + @Test fun `a proofread result missing most of the text is cut off`() { + val input = "x".repeat(286) + assertEquals(true, isCutOff("x".repeat(101), input, AiResultChecks.MIN_PROOFREAD_SHARE)) + assertEquals(false, isCutOff("x".repeat(270), input, AiResultChecks.MIN_PROOFREAD_SHARE)) + assertEquals(false, isCutOff("x".repeat(101), input, AiResultChecks.MIN_TRANSLATION_SHARE)) + assertEquals(false, isCutOff("ok", "okkkkkk", AiResultChecks.MIN_PROOFREAD_SHARE)) // short texts + } + + @Test fun `only a preamble at the start with a colon is removed`() { + assertEquals("Bonjour", stripTranslationPreamble("Translation: Bonjour")) + assertEquals("Bonjour", stripTranslationPreamble("Sure! Here is the translation in French:\nBonjour")) + assertEquals("Bonjour", stripTranslationPreamble("Output:\nBonjour")) + for (text in listOf("Results are in: we won", "Hello\nResults are in", "Hello\nOutput: 5", "Surely you jest", + "Translation is hard")) + assertEquals(text, stripTranslationPreamble(text)) + } +} diff --git a/app/src/test/java/helium314/keyboard/latin/ReplaceFileTest.kt b/app/src/test/java/helium314/keyboard/latin/ReplaceFileTest.kt new file mode 100644 index 000000000..4f643e4bc --- /dev/null +++ b/app/src/test/java/helium314/keyboard/latin/ReplaceFileTest.kt @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin + +import helium314.keyboard.latin.utils.replaceFile +import java.io.File +import kotlin.io.path.createTempDirectory +import kotlin.test.Test +import kotlin.test.assertEquals +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) // the failure is logged +class ReplaceFileTest { + private val target = File(createTempDirectory().toFile(), "plugin.apk").apply { writeText("working") } + + @Test fun `an accepted file replaces the previous one`() { + assertEquals(true, replaceFile(target, { it.writeText("new") }) { true }) + assertEquals("new", target.readText()) + assertEquals(listOf("plugin.apk"), target.parentFile!!.list()!!.toList()) + } + + @Test fun `the previous file stays when the new one is rejected or can't be written`() { + assertEquals(false, replaceFile(target, { it.writeText("broken") }) { false }) + assertEquals("working", target.readText()) + assertEquals(false, replaceFile(target, { error("no input") }) { true }) + assertEquals("working", target.readText()) + } +} diff --git a/app/src/test/java/helium314/keyboard/settings/BackupContentsTest.kt b/app/src/test/java/helium314/keyboard/settings/BackupContentsTest.kt new file mode 100644 index 000000000..0ab991aa4 --- /dev/null +++ b/app/src/test/java/helium314/keyboard/settings/BackupContentsTest.kt @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.settings + +import helium314.keyboard.settings.preferences.BackupCategory +import helium314.keyboard.settings.preferences.categoriesInBackup +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFails + +class BackupContentsTest { + private fun zip(vararg names: String): ByteArray { + val bytes = ByteArrayOutputStream() + ZipOutputStream(bytes).use { zip -> + for (name in names) { + zip.putNextEntry(ZipEntry(name)) + zip.write("content of $name".repeat(100).toByteArray()) + zip.closeEntry() + } + } + return bytes.toByteArray() + } + + @Test fun `only the categories with files in the backup are replaced`() { + val backup = zip("preferences.json", "layouts/custom.main.txt", "api_keys.json") + assertEquals(setOf(BackupCategory.LAYOUTS, BackupCategory.API_KEYS), categoriesInBackup(ByteArrayInputStream(backup))) + } + + @Test fun `a wrong or damaged file is refused`() { + assertFails { categoriesInBackup(ByteArrayInputStream("not a zip at all".toByteArray())) } + assertFails { categoriesInBackup(ByteArrayInputStream(zip("photo.jpg"))) } + val backup = zip("preferences.json", "layouts/custom.main.txt") + assertFails { categoriesInBackup(ByteArrayInputStream(backup.copyOf(60))) } + } +}