diff --git a/CHANGELOG.md b/CHANGELOG.md index 9be6589ef..4e0d8c1a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,7 +53,7 @@ Emojis for the following are chosen based on [gitmoji](https://gitmoji.dev/). - Vibrate on keypress and key click functionalities are included ([#405](https://github.com/scribe-org/Scribe-Android/issues/405), [#406](https://github.com/scribe-org/Scribe-Android/issues/406)). - An in-app tutorial is provided to detail functionalities of the application ([#602](https://github.com/scribe-org/Scribe-Android/issues/602), [#615](https://github.com/scribe-org/Scribe-Android/issues/615), [#616](https://github.com/scribe-org/Scribe-Android/issues/616)). - The user is able to easily rate the application, with installer-aware routing to the appropriate store ([#165](https://github.com/scribe-org/Scribe-Android/issues/165), [#640](https://github.com/scribe-org/Scribe-Android/issues/640)). - +- Declension of words within an interactive UI for Russian and German keyboards. ([#276](https://github.com/scribe-org/Scribe-Android/issues/276)) ### 🗃️ Data - SQLite databases have been set up for all data needed for the keyboards ([#87](https://github.com/scribe-org/Scribe-Android/issues/87)). diff --git a/app/src/androidTestKeyboards/kotlin/be/scri/helpers/KeyboardTest.kt b/app/src/androidTestKeyboards/kotlin/be/scri/helpers/KeyboardTest.kt deleted file mode 100644 index 3f248a8e4..000000000 --- a/app/src/androidTestKeyboards/kotlin/be/scri/helpers/KeyboardTest.kt +++ /dev/null @@ -1,113 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -package be.scri.helpers - -import android.view.KeyEvent -import android.view.inputmethod.InputConnection -import android.widget.Button -import androidx.test.ext.junit.runners.AndroidJUnit4 -import be.scri.models.ScribeState -import be.scri.services.GeneralKeyboardIME -import io.mockk.every -import io.mockk.mockk -import io.mockk.verify -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith - -@RunWith(AndroidJUnit4::class) -class KeyboardTest { - private lateinit var mockIME: GeneralKeyboardIME - private lateinit var mockInputConnection: InputConnection - private lateinit var keyHandler: KeyHandler - private lateinit var suggestionHandler: SuggestionHandler - private lateinit var translateBtn: Button - private lateinit var conjugateBtn: Button - private lateinit var pluralBtn: Button - - @Before - fun setUp() { - mockIME = mockk(relaxed = true) - mockInputConnection = mockk(relaxed = true) - - every { mockIME.currentInputConnection } returns mockInputConnection - every { mockIME.keyboard } returns mockk(relaxed = true) - every { mockIME.currentState } returns ScribeState.IDLE - every { mockIME.language } returns "German" - - keyHandler = KeyHandler(mockIME) - suggestionHandler = SuggestionHandler(mockIME) - translateBtn = mockk(relaxed = true) - conjugateBtn = mockk(relaxed = true) - pluralBtn = mockk(relaxed = true) - every { mockIME.binding.translateBtn } returns translateBtn - every { mockIME.binding.conjugateBtn } returns conjugateBtn - every { mockIME.binding.pluralBtn } returns pluralBtn - } - - @Test - fun testBackspaceReducesStringLengthByOne() { - val initialText = "Hello World" - var currentText = initialText - - every { mockIME.currentState } returns ScribeState.IDLE - every { mockInputConnection.getTextBeforeCursor(any(), any()) } returns currentText - every { mockIME.handleDelete(false) } answers { - if (currentText.isNotEmpty()) { - currentText = currentText.dropLast(1) - } - mockInputConnection.deleteSurroundingText(1, 0) - } - every { mockInputConnection.deleteSurroundingText(1, 0) } returns true - - keyHandler.handleKey(KeyboardBase.Companion.KEYCODE_DELETE, "en") - - assert(currentText.length == initialText.length - 1) { - "Expected length ${initialText.length - 1}, but got ${currentText.length}" - } - assert(currentText == "Hello Worl") { - "Expected 'Hello Worl', but got '$currentText'" - } - - verify(exactly = 1) { mockIME.handleDelete(false) } - verify(exactly = 1) { mockInputConnection.deleteSurroundingText(1, 0) } - } - - @Test - fun testEnterKeyInsertsNewLine() { - every { mockIME.currentState } returns ScribeState.IDLE - // Simulate the IME behavior for Enter key: sending ACTION_DOWN and ACTION_UP events. - every { mockIME.handleKeycodeEnter() } answers { - mockInputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)) - mockInputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)) - } - - keyHandler.handleKey(KeyboardBase.Companion.KEYCODE_ENTER, "en") - - verify(exactly = 1) { mockIME.handleKeycodeEnter() } - verify(exactly = 1) { - mockInputConnection.sendKeyEvent(match { it.action == KeyEvent.ACTION_DOWN && it.keyCode == KeyEvent.KEYCODE_ENTER }) - } - verify(exactly = 1) { - mockInputConnection.sendKeyEvent(match { it.action == KeyEvent.ACTION_UP && it.keyCode == KeyEvent.KEYCODE_ENTER }) - } - } - - @Test - fun processSuggestions() { - every { mockIME.findGenderForLastWord(any(), "in") } returns listOf("Neuter") - every { mockIME.findWhetherWordIsPlural(any(), "in") } returns false - every { mockIME.getCaseAnnotationForPreposition(any(), "in") } returns null - - every { mockIME.updateAutoSuggestText(any(), any(), any()) } answers { - conjugateBtn.text = "der" - pluralBtn.text = "den" - translateBtn.text = "die" - } - - suggestionHandler.processLinguisticSuggestions("in") - - verify(timeout = 2000) { conjugateBtn.text = match { it.isNotEmpty() } } - verify(timeout = 2000) { pluralBtn.text = match { it.isNotEmpty() } } - verify(timeout = 2000) { translateBtn.text = match { it.isNotEmpty() } } - } -} diff --git a/app/src/keyboards/java/be/scri/helpers/KeyHandler.kt b/app/src/keyboards/java/be/scri/helpers/KeyHandler.kt index b649a4ef8..164954b92 100644 --- a/app/src/keyboards/java/be/scri/helpers/KeyHandler.kt +++ b/app/src/keyboards/java/be/scri/helpers/KeyHandler.kt @@ -330,18 +330,19 @@ class KeyHandler( ) { val sharedPreferences = context.getSharedPreferences("keyboard_preferences", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() - var currentValue = sharedPreferences.getInt("conjugate_index", 0) + val preferenceKey = if (ime.currentState == ScribeState.SELECT_DECLENSION) "declension_index" else "conjugate_index" + var currentValue = sharedPreferences.getInt(preferenceKey, 0) if (code == KeyboardBase.DISPLAY_RIGHT) { currentValue-- } else if (code == KeyboardBase.DISPLAY_LEFT) { currentValue++ } - editor.putInt("conjugate_index", currentValue) + editor.putInt(preferenceKey, currentValue) editor.apply() ime.updateUI() - Log.d(TAG, "New conjugate_index: $currentValue") + Log.d(TAG, "New $preferenceKey: $currentValue") } /** diff --git a/app/src/keyboards/java/be/scri/helpers/KeyboardDataHandler.kt b/app/src/keyboards/java/be/scri/helpers/KeyboardDataHandler.kt index d1c31e37a..3ebb045b2 100644 --- a/app/src/keyboards/java/be/scri/helpers/KeyboardDataHandler.kt +++ b/app/src/keyboards/java/be/scri/helpers/KeyboardDataHandler.kt @@ -3,6 +3,7 @@ package be.scri.helpers import DataContract +import DeclensionNode import android.content.Context import android.database.sqlite.SQLiteException import android.util.Log @@ -52,6 +53,9 @@ class KeyboardDataHandler { var conjugateLabels: Set = emptySet() internal set + var declensions: LinkedHashMap>? = null + internal set + val isInitialized: Boolean get() = this::dbManagers.isInitialized @@ -92,6 +96,8 @@ class KeyboardDataHandler { val tempConjugateOutput = dbManagers.conjugateDataManager.getStructuredConjugations(languageAlias, dataContract, "describe") conjugateOutput = if (tempConjugateOutput?.isEmpty() == true) null else tempConjugateOutput conjugateLabels = dbManagers.conjugateDataManager.extractConjugateHeadings(dataContract, "coacha") + + declensions = dbManagers.declensionManager.getDeclensions(languageAlias, dataContract) } /** diff --git a/app/src/keyboards/java/be/scri/helpers/SuggestionHandler.kt b/app/src/keyboards/java/be/scri/helpers/SuggestionHandler.kt index 6bab98d4a..9f90d5af5 100644 --- a/app/src/keyboards/java/be/scri/helpers/SuggestionHandler.kt +++ b/app/src/keyboards/java/be/scri/helpers/SuggestionHandler.kt @@ -14,8 +14,8 @@ import be.scri.models.ScribeState */ class SuggestionHandler( private val ime: KeyboardIMEContext, + private val handler: Handler = Handler(Looper.getMainLooper()), ) { - private val handler = Handler(Looper.getMainLooper()) private var emojiSuggestionRunnable: Runnable? = null private var linguisticSuggestionRunnable: Runnable? = null private var wordSuggestionRunnable: Runnable? = null diff --git a/app/src/keyboards/java/be/scri/helpers/ui/HintUtils.kt b/app/src/keyboards/java/be/scri/helpers/ui/HintUtils.kt index 243cbde97..4c0e329a6 100644 --- a/app/src/keyboards/java/be/scri/helpers/ui/HintUtils.kt +++ b/app/src/keyboards/java/be/scri/helpers/ui/HintUtils.kt @@ -50,9 +50,11 @@ object HintUtils { currentState: ScribeState, language: String, word: String?, + declensionSectionTitle: String?, ): String = when (currentState) { ScribeState.SELECT_VERB_CONJUNCTION -> word ?: "" + ScribeState.SELECT_DECLENSION -> declensionSectionTitle ?: "" else -> getHintForState(currentState)[language] ?: "" } @@ -351,9 +353,23 @@ object HintUtils { ScribeState.CONJUGATE -> getConjugationPrompt(language) ScribeState.PLURAL -> getPluralPrompt(language) ScribeState.SELECT_VERB_CONJUNCTION -> text ?: "" + ScribeState.SELECT_DECLENSION -> getDeclensionPrompt(language) else -> "" } + private fun getDeclensionPrompt(language: String): String = + when (language) { + "English" -> "Decline: " + "French" -> "Décliner: " + "German" -> "Deklinieren: " + "Italian" -> "Declinare: " + "Portuguese" -> "Declinar: " + "Russian" -> "Склонение: " + "Spanish" -> "Declinar: " + "Swedish" -> "Deklinera: " + else -> "Decline: " + } + /** * Retrieves the translation prompt text for the given language. * diff --git a/app/src/keyboards/java/be/scri/helpers/ui/KeyboardThemeManager.kt b/app/src/keyboards/java/be/scri/helpers/ui/KeyboardThemeManager.kt index 788ef0f94..7d8d2a74a 100644 --- a/app/src/keyboards/java/be/scri/helpers/ui/KeyboardThemeManager.kt +++ b/app/src/keyboards/java/be/scri/helpers/ui/KeyboardThemeManager.kt @@ -206,22 +206,39 @@ class KeyboardThemeManager { colorRes: Int, buttonText: String, textSizeSp: Float? = null, + type: String?, ) { button.visibility = View.VISIBLE button.text = buttonText if (textSizeSp != null) { button.textSize = textSizeSp } - button.isClickable = false - button.setOnClickListener(null) + when (type) { + "preposition" -> { + button.isClickable = true + } + else -> { + button.isClickable = false + button.setOnClickListener(null) + } + } + val isUserDarkMode = getIsDarkModeOrNot(context) if (colorRes != R.color.transparent) { button.background = ContextCompat.getDrawable(context, R.drawable.button_background_rounded) button.backgroundTintList = ContextCompat.getColorStateList(context, colorRes) - button.setTextColor(ContextCompat.getColor(context, R.color.white)) + button.setTextColor( + ContextCompat.getColor( + context, + if (colorRes == R.color.annotateDeclension && isUserDarkMode) { + android.R.color.black + } else { + R.color.white + }, + ), + ) } else { button.background = null - val isUserDarkMode = getIsDarkModeOrNot(context) button.backgroundTintList = ContextCompat.getColorStateList(context, R.color.transparent) button.setTextColor(ContextCompat.getColor(context, if (isUserDarkMode) R.color.white else android.R.color.black)) } diff --git a/app/src/keyboards/java/be/scri/helpers/ui/KeyboardUIManager.kt b/app/src/keyboards/java/be/scri/helpers/ui/KeyboardUIManager.kt index 8d6155576..6cda72fd1 100644 --- a/app/src/keyboards/java/be/scri/helpers/ui/KeyboardUIManager.kt +++ b/app/src/keyboards/java/be/scri/helpers/ui/KeyboardUIManager.kt @@ -2,6 +2,7 @@ package be.scri.helpers.ui +import DeclensionNode import android.annotation.SuppressLint import android.content.Context import android.content.res.ColorStateList @@ -49,7 +50,6 @@ import be.scri.helpers.english.ENInterfaceVariables.ALREADY_PLURAL_MSG import be.scri.helpers.getCategoryIconRes import be.scri.helpers.getRecentEmojis import be.scri.helpers.parseRawEmojiSpecsFile -import be.scri.models.ScribeLanguage import be.scri.models.ScribeState import be.scri.services.GeneralKeyboardIME import be.scri.views.KeyboardView @@ -113,6 +113,12 @@ class KeyboardUIManager( fun getKeyboardWidth(): Int fun onClipboardSuggestionClicked() + + fun onConjugationCategoryClicked(category: String) + + fun onDeclensionNodeClicked(node: DeclensionNode) + + fun onGridPageChanged() } var keyboardView: KeyboardView = binding.keyboardView @@ -211,6 +217,8 @@ class KeyboardUIManager( selectedConjugationSubCategory: String?, currentVerbForConjugation: String?, invalidCommandSource: ScribeState = ScribeState.IDLE, + declensionOutput: Map>? = null, + currentDeclensionSubNodes: List? = null, ) { val isUserDarkMode = getIsDarkModeOrNot(context) @@ -232,18 +240,44 @@ class KeyboardUIManager( } ScribeState.TRANSLATE -> { - setupToolbarView(currentState, language, conjugateOutput, conjugateLabels, selectedConjugationSubCategory, currentVerbForConjugation) + setupToolbarView( + currentState, + language, + conjugateOutput, + conjugateLabels, + selectedConjugationSubCategory, + currentVerbForConjugation, + declensionOutput, + currentDeclensionSubNodes, + ) binding.translateBtn.text = translatePlaceholder[getLanguageAlias(language)] ?: "Translate" binding.translateBtn.visibility = View.VISIBLE } ScribeState.CONJUGATE, ScribeState.SELECT_VERB_CONJUNCTION, ScribeState.PLURAL -> { - setupToolbarView(currentState, language, conjugateOutput, conjugateLabels, selectedConjugationSubCategory, currentVerbForConjugation) - } - - ScribeState.ALREADY_PLURAL -> { - setupAlreadyPluralView() + setupToolbarView( + currentState, + language, + conjugateOutput, + conjugateLabels, + selectedConjugationSubCategory, + currentVerbForConjugation, + declensionOutput, + currentDeclensionSubNodes, + ) } + ScribeState.ALREADY_PLURAL -> setupAlreadyPluralView() + ScribeState.SELECT_DECLENSION -> + setupToolbarView( + currentState, + language, + conjugateOutput, + conjugateLabels, + selectedConjugationSubCategory, + currentVerbForConjugation, + declensionOutput, + currentDeclensionSubNodes, + ) } updateEnterKeyColor(isUserDarkMode, currentState) @@ -393,6 +427,164 @@ class KeyboardUIManager( binding.scribeKeyOptions.foreground = AppCompatResources.getDrawable(context, R.drawable.close) } + // setupToolbarView defined below + + private fun extractConjugateForms( + title: String?, + conjugateOutput: Map>>>?, + selectedConjugationSubCategory: String?, + isDarkMode: Boolean, + ): List { + val gridItems = mutableListOf() + val groupData = conjugateOutput?.get(title) ?: return emptyList() + + if (selectedConjugationSubCategory != null) { + val pairs = groupData[selectedConjugationSubCategory] + pairs?.forEach { (label, form) -> + val hasLabel = label.isNotEmpty() && label != "all" + val text = formatButtonText(label, form, isDarkMode) + gridItems.add(GridItem(label = text, rawForm = form, commitValue = "$form ", hasLabel = hasLabel)) + } + } else if (groupData.containsKey(title) && groupData.size == 1) { + val pairs = groupData[title] + pairs?.forEach { (label, form) -> + val hasLabel = label.isNotEmpty() && label != "all" + val text = formatButtonText(label, form, isDarkMode) + gridItems.add(GridItem(label = text, rawForm = form, commitValue = "$form ", hasLabel = hasLabel)) + } + } else { + groupData.forEach { (categoryTitle, pairs) -> + if (pairs.size == 1) { + val (label, form) = pairs.first() + val hasLabel = label.isNotEmpty() && label != "all" + val text = formatButtonText(label, form, isDarkMode) + gridItems.add(GridItem(label = text, rawForm = form, commitValue = "$form ", hasLabel = hasLabel)) + } else { + val formsPreview = pairs.map { it.second.trim() }.filter { it.isNotBlank() }.joinToString(" / ") + val hasLabel = categoryTitle.isNotEmpty() + val text = formatButtonText(categoryTitle, formsPreview, isDarkMode) + gridItems.add(GridItem(label = text, categoryToOpen = categoryTitle, hasLabel = hasLabel)) + } + } + } + + return gridItems + } + + private fun extractDeclensionForms( + title: String?, + declensionOutput: Map>?, + subNodes: List?, + ): List { + val gridItems = mutableListOf() + + val nodes = subNodes ?: declensionOutput?.get(title) ?: return emptyList() + + nodes.forEach { node -> + val hasSubNodes = !node.declensionForms?.values.isNullOrEmpty() + val textToCommit = node.value ?: node.label + gridItems.add( + GridItem( + label = node.displayValue ?: node.label ?: "", + commitValue = if (!hasSubNodes && textToCommit != null) "$textToCommit " else null, + nodeToOpen = if (hasSubNodes) node else null, + ), + ) + } + + return gridItems + } + + private fun renderGrid( + title: String?, + items: List, + isDarkMode: Boolean, + selectedConjugationSubCategory: String?, + prefIndexName: String, + ): String? { + binding.conjugateGridContainer.visibility = View.VISIBLE + binding.keyboardView.visibility = View.GONE + + binding.conjugateGridContainer.setBackgroundColor( + ContextCompat.getColor( + context, + if (isDarkMode) R.color.dark_keyboard_bg_color else R.color.light_keyboard_bg_color, + ), + ) + + val grid = binding.conjugateGrid + grid.removeAllViews() + + val isSubSelection = + if (prefIndexName == "declension_index") { + (listener as? GeneralKeyboardIME)?.currentDeclensionSubNodes != null + } else { + selectedConjugationSubCategory != null || items.any { it.commitValue != null } + } + val count = items.size + + val layoutResId = + when { + count <= MAX_FORM_COUNT_2X1 -> R.layout.conjugate_grid_2x1 + count == FORM_COUNT_3X1 -> R.layout.conjugate_grid_3x1 + count <= MAX_FORM_COUNT_2X2 -> R.layout.conjugate_grid_2x2 + else -> R.layout.conjugate_grid_3x2 + } + + val layoutInflater = LayoutInflater.from(context) + val gridContent = layoutInflater.inflate(layoutResId, grid, false) as LinearLayout + grid.addView(gridContent) + + val buttonIds = + listOf( + R.id.conjugate_btn_1, + R.id.conjugate_btn_2, + R.id.conjugate_btn_3, + R.id.conjugate_btn_4, + R.id.conjugate_btn_5, + R.id.conjugate_btn_6, + ) + + buttonIds.forEachIndexed { i, btnId -> + val item = items.getOrNull(i) + val btn = gridContent.findViewById(btnId) + if (btn != null && item != null) { + btn.visibility = View.VISIBLE + applyButtonLayout(btn, item.hasLabel) + btn.text = item.label + btn.backgroundTintList = + ContextCompat.getColorStateList( + context, + if (isDarkMode) R.color.dark_key_color else R.color.light_key_color, + ) + btn.setTextColor(if (isDarkMode) Color.WHITE else Color.BLACK) + btn.setOnClickListener { + when { + item.commitValue != null -> { + listener.commitText(item.commitValue) + val formToSuggest = item.rawForm ?: item.label.toString().trim() + listener.processLinguisticSuggestions(formToSuggest) + } + item.categoryToOpen != null -> { + listener.onConjugationSubCategorySelected(item.categoryToOpen) + } + item.nodeToOpen != null -> { + listener.onDeclensionNodeClicked(item.nodeToOpen) + } + } + } + } else { + btn?.visibility = View.INVISIBLE + btn?.setOnClickListener(null) + } + } + + setupArrows(gridContent, context, isSubSelection, prefIndexName) + + val promptText = if (isSubSelection) selectedConjugationSubCategory else (title ?: "___") + return promptText + } + /** * Configures the UI for command modes (`TRANSLATE`, `CONJUGATE`, etc.), showing the command bar and toolbar. */ @@ -404,6 +596,8 @@ class KeyboardUIManager( conjugateLabels: Set?, selectedConjugationSubCategory: String?, currentVerbForConjugation: String?, + declensionOutput: Map>? = null, + currentDeclensionSubNodes: List? = null, ) { binding.commandOptionsBar.visibility = View.GONE binding.toolbarBar.visibility = View.VISIBLE @@ -421,101 +615,34 @@ class KeyboardUIManager( var hintWord: String? = null var promptText: String? = null - if (currentState == ScribeState.SELECT_VERB_CONJUNCTION) { - binding.conjugateGridContainer.visibility = View.VISIBLE - binding.keyboardView.visibility = View.GONE + var declensionSectionTitle: String? = null - binding.conjugateGridContainer.setBackgroundColor( - ContextCompat.getColor( - context, - if (isDarkMode) R.color.dark_keyboard_bg_color else R.color.light_keyboard_bg_color, - ), - ) - - val grid = binding.conjugateGrid - grid.removeAllViews() - - val conjugateIndex = getValidatedConjugateIndex(conjugateOutput) - val title = conjugateOutput?.keys?.elementAtOrNull(conjugateIndex) - val languageOutput = title?.let { conjugateOutput[it] } - - val isSubSelection = selectedConjugationSubCategory != null - val showCategories = !isSubSelection && (languageOutput?.containsKey(title) != true) - - val scribeLanguage = ScribeLanguage.fromDisplayName(language) - val layoutResId = - when { - isSubSelection -> { - val subPairs = languageOutput?.get(selectedConjugationSubCategory) ?: emptyList() - when { - subPairs.size <= MAX_FORM_COUNT_2X1 -> R.layout.conjugate_grid_2x1 - subPairs.size == FORM_COUNT_3X1 -> R.layout.conjugate_grid_3x1 - subPairs.size <= MAX_FORM_COUNT_2X2 -> R.layout.conjugate_grid_2x2 - else -> R.layout.conjugate_grid_3x2 - } - } - else -> { - val formsCount = - if (showCategories) { - languageOutput?.size ?: 0 - } else { - languageOutput?.get(title)?.size ?: 0 - } - val isSmallFormLanguage = - scribeLanguage == ScribeLanguage.ENGLISH || - scribeLanguage == ScribeLanguage.RUSSIAN || - scribeLanguage == ScribeLanguage.SWEDISH - when { - formsCount <= MAX_FORM_COUNT_2X1 -> R.layout.conjugate_grid_2x1 - formsCount == FORM_COUNT_3X1 -> R.layout.conjugate_grid_3x1 - isSmallFormLanguage && formsCount <= MAX_FORM_COUNT_2X2 -> R.layout.conjugate_grid_2x2 - formsCount > MAX_FORM_COUNT_2X2 -> R.layout.conjugate_grid_3x2 - else -> R.layout.conjugate_grid_2x2 - } - } - } - - val layoutInflater = LayoutInflater.from(context) - val gridContent = layoutInflater.inflate(layoutResId, grid, false) as LinearLayout - grid.addView(gridContent) - - when { - isSubSelection -> { - val subPairs = languageOutput?.get(selectedConjugationSubCategory) ?: emptyList() - populateSubSelectionButtons(gridContent, subPairs, isDarkMode) - } - showCategories -> { - val categoryEntries = languageOutput?.entries?.toList() ?: emptyList() - populateCategoryButtons(gridContent, categoryEntries, isDarkMode) - } - else -> { - val directPairs = languageOutput?.get(title) ?: emptyList() - populateDirectButtons(gridContent, directPairs, isDarkMode) - } + when (currentState) { + ScribeState.SELECT_VERB_CONJUNCTION -> { + val prefIndexName = "conjugate_index" + val index = getValidatedIndex(prefIndexName, conjugateOutput?.size ?: 0) + val title = conjugateOutput?.keys?.elementAtOrNull(index) + val items = extractConjugateForms(title, conjugateOutput, selectedConjugationSubCategory, isDarkMode) + promptText = renderGrid(title, items, isDarkMode, selectedConjugationSubCategory, prefIndexName) + hintWord = conjugateLabels?.lastOrNull() + } + ScribeState.SELECT_DECLENSION -> { + val prefIndexName = "declension_index" + val output = declensionOutput ?: (listener as? GeneralKeyboardIME)?.dataHandler?.declensions + val index = getValidatedIndex(prefIndexName, output?.size ?: 0) + declensionSectionTitle = output?.keys?.elementAtOrNull(index) + val items = extractDeclensionForms(declensionSectionTitle, output, currentDeclensionSubNodes) + promptText = renderGrid(declensionSectionTitle, items, isDarkMode, null, prefIndexName) + } + else -> { + binding.conjugateGridContainer.visibility = View.GONE + binding.keyboardView.visibility = View.VISIBLE } - - setupConjugateArrows(gridContent, context, isSubSelection) - - promptText = if (isSubSelection) selectedConjugationSubCategory else (title ?: "___") - hintWord = conjugateLabels?.lastOrNull() - } else { - binding.conjugateGridContainer.visibility = View.GONE - binding.keyboardView.visibility = View.VISIBLE } - updateCommandBarHintAndPrompt(currentState, language, promptText, isDarkMode, hintWord, currentVerbForConjugation) + updateCommandBarHintAndPrompt(currentState, language, promptText, isDarkMode, hintWord, currentVerbForConjugation, declensionSectionTitle) } - private val buttonIds = - listOf( - R.id.conjugate_btn_1, - R.id.conjugate_btn_2, - R.id.conjugate_btn_3, - R.id.conjugate_btn_4, - R.id.conjugate_btn_5, - R.id.conjugate_btn_6, - ) - private fun formatButtonText( label: String, form: String, @@ -581,110 +708,14 @@ class KeyboardUIManager( } } - private fun populateSubSelectionButtons( - gridContent: View, - subPairs: List>, - isDarkMode: Boolean, - ) { - buttonIds.forEachIndexed { i, btnId -> - val btn = gridContent.findViewById(btnId) ?: return@forEachIndexed - if (i < subPairs.size) { - val (label, form) = subPairs[i] - btn.visibility = View.VISIBLE - btn.backgroundTintList = - ContextCompat.getColorStateList( - context, - if (isDarkMode) R.color.dark_key_color else R.color.light_key_color, - ) - btn.setTextColor(if (isDarkMode) Color.WHITE else Color.BLACK) - val hasLabel = label.isNotEmpty() && label != "all" - applyButtonLayout(btn, hasLabel) - btn.text = formatButtonText(label, form, isDarkMode) - btn.setOnClickListener { - listener.commitText("$form ") - listener.processLinguisticSuggestions(form) - } - } else { - btn.visibility = View.INVISIBLE - btn.setOnClickListener(null) - } - } - } - - private fun populateCategoryButtons( - gridContent: View, - categoryEntries: List>>>, - isDarkMode: Boolean, - ) { - buttonIds.forEachIndexed { i, btnId -> - val btn = gridContent.findViewById(btnId) ?: return@forEachIndexed - if (i < categoryEntries.size) { - val (categoryTitle, pairs) = categoryEntries[i] - btn.visibility = View.VISIBLE - btn.backgroundTintList = - ContextCompat.getColorStateList( - context, - if (isDarkMode) R.color.dark_key_color else R.color.light_key_color, - ) - btn.setTextColor(if (isDarkMode) Color.WHITE else Color.BLACK) - val formsPreview = pairs.map { it.second.trim() }.filter { it.isNotBlank() }.joinToString(" / ") - applyButtonLayout(btn, categoryTitle.isNotEmpty()) - btn.text = formatButtonText(categoryTitle, formsPreview, isDarkMode) - if (pairs.size == 1) { - val (_, form) = pairs.first() - btn.setOnClickListener { - listener.commitText("$form ") - listener.processLinguisticSuggestions(form) - } - } else { - btn.setOnClickListener { - listener.onConjugationSubCategorySelected(categoryTitle) - } - } - } else { - btn.visibility = View.INVISIBLE - btn.setOnClickListener(null) - } - } - } - - private fun populateDirectButtons( - gridContent: View, - directPairs: List>, - isDarkMode: Boolean, - ) { - buttonIds.forEachIndexed { i, btnId -> - val btn = gridContent.findViewById(btnId) ?: return@forEachIndexed - if (i < directPairs.size) { - val (label, form) = directPairs[i] - btn.visibility = View.VISIBLE - btn.backgroundTintList = - ContextCompat.getColorStateList( - context, - if (isDarkMode) R.color.dark_key_color else R.color.light_key_color, - ) - btn.setTextColor(if (isDarkMode) Color.WHITE else Color.BLACK) - val hasLabel = label.isNotEmpty() && label != "all" - applyButtonLayout(btn, hasLabel) - btn.text = formatButtonText(label, form, isDarkMode) - btn.setOnClickListener { - listener.commitText("$form ") - listener.processLinguisticSuggestions(form) - } - } else { - btn.visibility = View.INVISIBLE - btn.setOnClickListener(null) - } - } - } - /** - * Sets up the navigation arrow buttons for the conjugation grid view. + * Sets up the navigation arrow buttons for the grid view. */ - private fun setupConjugateArrows( + private fun setupArrows( gridContent: View, context: Context, isSubSelection: Boolean, + prefIndexName: String, ) { val isDarkMode = getIsDarkModeOrNot(context) val arrowButtonIds = @@ -719,11 +750,15 @@ class KeyboardUIManager( } else { val isLeft = arrowBtnName.contains("left") val prefs = context.getSharedPreferences("keyboard_preferences", Context.MODE_PRIVATE) - val current = prefs.getInt("conjugate_index", 0) + val current = prefs.getInt(prefIndexName, 0) val newValue = if (isLeft) current - 1 else current + 1 - prefs.edit { putInt("conjugate_index", newValue) } + prefs.edit { putInt(prefIndexName, newValue) } - listener.onConjugateClicked() + if (prefIndexName == "declension_index") { + listener.onGridPageChanged() + } else { + listener.onConjugateClicked() + } } } } @@ -805,6 +840,7 @@ class KeyboardUIManager( isUserDarkMode: Boolean? = null, word: String? = null, currentVerbForConjugation: String? = null, + currentDeclensionSectionTitle: String? = null, ) { val resolvedIsDarkMode = isUserDarkMode ?: getIsDarkModeOrNot(context) val commandBarEditText = binding.commandBar @@ -820,19 +856,29 @@ class KeyboardUIManager( promptTextView.setTextColor(commandBarTextColor) promptTextView.setBackgroundColor(context.getColor(backgroundColor)) - if (currentState == ScribeState.SELECT_VERB_CONJUNCTION) { - val verbInfinitive = currentVerbForConjugation ?: "" - commandBarEditText.setText(": $verbInfinitive") - commandBarEditText.setTextColor(commandBarTextColor) - commandBarEditText.isFocusable = false - commandBarEditText.isFocusableInTouchMode = false - } else { - currentCommandBarHint = HintUtils.getCommandBarHint(currentState, language, word) - commandBarEditText.isFocusable = true - commandBarEditText.isFocusableInTouchMode = true - commandBarEditText.setTextColor(commandBarHintColor) - setCommandBarTextWithCursor(currentCommandBarHint, cursorAtStart = true) - commandBarEditText.requestFocus() + with(commandBarEditText) { + when (currentState) { + ScribeState.SELECT_VERB_CONJUNCTION -> { + setText(": ${currentVerbForConjugation.orEmpty()}") + setTextColor(commandBarTextColor) + isFocusable = false + isFocusableInTouchMode = false + } + ScribeState.SELECT_DECLENSION -> { + setText(HintUtils.getCommandBarHint(currentState, language, word, currentDeclensionSectionTitle)) + setTextColor(commandBarHintColor) + isFocusable = false + isFocusableInTouchMode = false + } + else -> { + currentCommandBarHint = HintUtils.getCommandBarHint(currentState, language, word, currentDeclensionSectionTitle) + isFocusable = true + isFocusableInTouchMode = true + setTextColor(commandBarHintColor) + setCommandBarTextWithCursor(currentCommandBarHint, cursorAtStart = true) + requestFocus() + } + } } } @@ -864,15 +910,18 @@ class KeyboardUIManager( } /** - * Retrieves and validates the stored index for the current conjugation view. - * Ensures the index is within the bounds of available conjugation types. + * Retrieves and validates the stored index for the current view. + * Ensures the index is within the bounds of available types. */ - internal fun getValidatedConjugateIndex(conjugateOutput: Map?): Int { + internal fun getValidatedIndex( + prefKey: String, + size: Int, + ): Int { val prefs = context.getSharedPreferences("keyboard_preferences", Context.MODE_PRIVATE) - var index = prefs.getInt("conjugate_index", 0) - val maxIndex = conjugateOutput?.keys?.count()?.minus(1) ?: -1 + var index = prefs.getInt(prefKey, 0) + val maxIndex = size.minus(1) index = if (maxIndex >= 0) index.coerceIn(0, maxIndex) else 0 - prefs.edit { putInt("conjugate_index", index) } + prefs.edit { putInt(prefKey, index) } return index } @@ -1513,4 +1562,13 @@ class KeyboardUIManager( binding.invalidInfoBar.visibility = View.GONE binding.conjugateGridContainer.visibility = View.GONE } + + data class GridItem( + val label: CharSequence, + val rawForm: String? = null, + val commitValue: String? = null, + val categoryToOpen: String? = null, + val nodeToOpen: DeclensionNode? = null, + val hasLabel: Boolean = false, + ) } diff --git a/app/src/keyboards/java/be/scri/helpers/ui/SuggestionUIHandler.kt b/app/src/keyboards/java/be/scri/helpers/ui/SuggestionUIHandler.kt index 0ad3a7160..f2fc6f401 100644 --- a/app/src/keyboards/java/be/scri/helpers/ui/SuggestionUIHandler.kt +++ b/app/src/keyboards/java/be/scri/helpers/ui/SuggestionUIHandler.kt @@ -9,6 +9,7 @@ import be.scri.helpers.AnnotationTextUtils.handleColorAndTextForNounType import be.scri.helpers.AnnotationTextUtils.handleTextForCaseAnnotation import be.scri.helpers.KeyboardIMEContext import be.scri.models.ScribeState +import be.scri.services.GeneralKeyboardIME import be.scri.services.GeneralKeyboardIME.Companion.SUGGESTION_SIZE /** @@ -74,15 +75,15 @@ class SuggestionUIHandler( true } - handleSingleNounSuggestion(nounTypeSuggestion) -> { + handleMultipleCases(caseAnnotationSuggestion) -> { true } - handleMultipleCases(caseAnnotationSuggestion) -> { + handleSingleCaseSuggestion(caseAnnotationSuggestion) -> { true } - handleSingleCaseSuggestion(caseAnnotationSuggestion) -> { + handleSingleNounSuggestion(nounTypeSuggestion) -> { true } @@ -115,6 +116,7 @@ class SuggestionUIHandler( colorRes = R.color.annotateOrange, buttonText = "PL", textSizeSp = NOUN_TYPE_SIZE, + type = null, ) return true } @@ -205,7 +207,7 @@ class SuggestionUIHandler( */ private fun handleSingleType( singleTypeSuggestion: List?, - type: String? = null, + type: String, ) { val suggestionText = singleTypeSuggestion?.getOrNull(0).toString() val (colorRes, buttonText) = @@ -215,6 +217,14 @@ class SuggestionUIHandler( else -> Pair(R.color.transparent, "") } + if (type == "preposition") { + uiManager.binding.translateBtn.setOnClickListener { + if (ime is GeneralKeyboardIME) { + ime.onPrepositionClicked(suggestionText) + } + } + } + uiManager.genderSuggestionLeft?.visibility = View.INVISIBLE uiManager.genderSuggestionRight?.visibility = View.INVISIBLE @@ -224,6 +234,7 @@ class SuggestionUIHandler( colorRes = colorRes, buttonText = buttonText, textSizeSp = NOUN_TYPE_SIZE, + type = type, ) } @@ -280,6 +291,16 @@ class SuggestionUIHandler( leftSuggestion.second, R.drawable.gender_suggestion_button_left_background, ) + if (type == "preposition") { + val rawCaseText = multipleTypeSuggestion?.getOrNull(0) + if (rawCaseText != null) { + it.setOnClickListener { + if (ime is GeneralKeyboardIME) { + ime.onPrepositionClicked(rawCaseText) + } + } + } + } } uiManager.genderSuggestionRight?.let { @@ -289,6 +310,16 @@ class SuggestionUIHandler( rightSuggestion.second, R.drawable.gender_suggestion_button_right_background, ) + if (type == "preposition") { + val rawCaseText = multipleTypeSuggestion?.getOrNull(1) + if (rawCaseText != null) { + it.setOnClickListener { + if (ime is GeneralKeyboardIME) { + ime.onPrepositionClicked(rawCaseText) + } + } + } + } } } diff --git a/app/src/keyboards/java/be/scri/services/GeneralKeyboardIME.kt b/app/src/keyboards/java/be/scri/services/GeneralKeyboardIME.kt index f849cc7c6..7a52d1d73 100644 --- a/app/src/keyboards/java/be/scri/services/GeneralKeyboardIME.kt +++ b/app/src/keyboards/java/be/scri/services/GeneralKeyboardIME.kt @@ -3,6 +3,7 @@ package be.scri.services import DataContract +import DeclensionNode import android.app.Dialog import android.content.Context import android.content.Intent @@ -22,6 +23,7 @@ import android.widget.TextView import be.scri.R import be.scri.activities.MainActivity import be.scri.databinding.InputMethodViewBinding +import be.scri.helpers.AnnotationTextUtils import be.scri.helpers.AutocompletionHandler import be.scri.helpers.BackspaceHandler import be.scri.helpers.CommandHandler @@ -181,6 +183,10 @@ abstract class GeneralKeyboardIME( dataHandler.conjugateOutput = value } + var declensionOutput: Map>? = null + var currentDeclensionSubNodes: List? = null + private val declensionStack = mutableListOf>() + internal var conjugateLabels: Set get() = dataHandler.conjugateLabels set(value) { @@ -660,6 +666,8 @@ abstract class GeneralKeyboardIME( emojiAutoSuggestionEnabled = emojiAutoSuggestionEnabled, autoSuggestEmojis = autoSuggestEmojis, conjugateOutput = conjugateOutput, + declensionOutput = declensionOutput, + currentDeclensionSubNodes = currentDeclensionSubNodes, conjugateLabels = conjugateLabels, selectedConjugationSubCategory = selectedConjugationSubCategory, currentVerbForConjugation = currentVerbForConjugation, @@ -676,6 +684,9 @@ abstract class GeneralKeyboardIME( saveConjugateModeType("none") currentVerbForConjugation = null selectedConjugationSubCategory = null + declensionOutput = null + currentDeclensionSubNodes = null + declensionStack.clear() if (this::uiManager.isInitialized) refreshUI() } @@ -780,6 +791,11 @@ abstract class GeneralKeyboardIME( override fun onConjugationSubCategoryDismissed() { selectedConjugationSubCategory = null + if (declensionStack.isNotEmpty()) { + currentDeclensionSubNodes = declensionStack.removeAt(declensionStack.lastIndex) + } else { + currentDeclensionSubNodes = null + } refreshUI() } @@ -787,8 +803,11 @@ abstract class GeneralKeyboardIME( currentInputConnection?.commitText(text, 1) suggestionHandler.processLinguisticSuggestions(text.trim()) - if (currentState == ScribeState.SELECT_VERB_CONJUNCTION) { + if (currentState == ScribeState.SELECT_VERB_CONJUNCTION || currentState == ScribeState.SELECT_DECLENSION) { selectedConjugationSubCategory = null + currentDeclensionSubNodes = null + declensionStack.clear() + declensionOutput = null moveToIdleState() } } @@ -1136,13 +1155,42 @@ abstract class GeneralKeyboardIME( // MARK: Suggestion UI Logic + override fun onConjugationCategoryClicked(category: String) { + selectedConjugationSubCategory = category + refreshUI() + } + + override fun onDeclensionNodeClicked(node: DeclensionNode) { + val children = node.declensionForms?.values?.toList() + if (!children.isNullOrEmpty()) { + currentDeclensionSubNodes?.let { declensionStack.add(it) } + currentDeclensionSubNodes = children + refreshUI() + } + } + + override fun onGridPageChanged() { + refreshUI() + } + + fun onPrepositionClicked(suggestionText: String) { + declensionOutput = + dataHandler.declensions?.filter { (title, _) -> + title.contains( + AnnotationTextUtils.getLocalizedKeyword( + language, + suggestionText, + ), + ignoreCase = true, + ) + } + stateManager.moveToState(ScribeState.SELECT_DECLENSION) + refreshUI() + } + /** - * The main dispatcher for displaying linguistic auto-suggestions (gender, case, plurality). - * Delegated to [SuggestionUIHandler]. + * Displays word prediction suggestions on the command buttons. * - * @param nounTypeSuggestion The detected gender(s) of the last word. - * @param isPlural true if the last word is plural. - * @param caseAnnotationSuggestion The detected case(s) required by the last word. * @param wordSuggestions The list of predicted words to display. */ override fun updateAutoSuggestText( diff --git a/app/src/main/java/be/scri/helpers/AnnotationTextUtils.kt b/app/src/main/java/be/scri/helpers/AnnotationTextUtils.kt index 1505386f5..54bf26115 100644 --- a/app/src/main/java/be/scri/helpers/AnnotationTextUtils.kt +++ b/app/src/main/java/be/scri/helpers/AnnotationTextUtils.kt @@ -27,17 +27,17 @@ object AnnotationTextUtils { language: String, context: Context, ): Pair { - val color = R.color.annotateOrange + val color = R.color.annotateDeclension val suggestionMap = mapOf( "genitive case" to Pair(color, processValuesForPreposition(language, "Gen")), "accusative case" to Pair(color, processValuesForPreposition(language, "Acc")), "dative case" to Pair(color, processValuesForPreposition(language, "Dat")), "locative case" to Pair(color, processValuesForPreposition(language, "Loc")), - "Prepositional case" to Pair(color, processValuesForPreposition(language, "Pre")), - "Instrumental case" to Pair(color, processValuesForPreposition(language, "Ins")), + "prepositional case" to Pair(color, processValuesForPreposition(language, "Pre")), + "instrumental case" to Pair(color, processValuesForPreposition(language, "Ins")), ) - return suggestionMap[nounType] ?: Pair(R.color.transparent, context.getString(R.string.i18n_app_keyboard_suggestion)) + return suggestionMap[nounType.lowercase()] ?: Pair(R.color.transparent, context.getString(R.string.i18n_app_keyboard_suggestion)) } /** @@ -54,14 +54,14 @@ object AnnotationTextUtils { ): Pair { val suggestionMap = mapOf( - "PL" to Pair(R.color.annotateOrange, "PL"), + "pl" to Pair(R.color.annotateOrange, "PL"), "neuter" to Pair(R.color.annotateGreen, processValueForNouns(language, "N")), "common of two genders" to Pair(R.color.annotatePurple, processValueForNouns(language, "C")), "common" to Pair(R.color.annotatePurple, processValueForNouns(language, "C")), "masculine" to Pair(R.color.annotateBlue, processValueForNouns(language, "M")), "feminine" to Pair(R.color.annotateRed, processValueForNouns(language, "F")), ) - return suggestionMap[nounType] ?: Pair(R.color.transparent, context.getString(R.string.i18n_app_keyboard_suggestion)) + return suggestionMap[nounType.lowercase()] ?: Pair(R.color.transparent, context.getString(R.string.i18n_app_keyboard_suggestion)) } /** @@ -92,4 +92,33 @@ object AnnotationTextUtils { language: String, text: String, ): String = prepAnnotationConversionDict[language]?.get(text) ?: text + + /** + * Converts a raw case annotation string into a localized keyword for data filtering. + * + * This function first maps internal system strings (e.g., "accusative case") to standard + * abbreviations (e.g., "Acc"), and then translates those abbreviations based on the + * provided language (e.g., returning "Akk" for German). This is primarily used to + * filter declension sections in the language's data contract. + * + * @param language The current keyboard language. + * @param annotationText The raw annotation string to convert. + * @return A localized abbreviation suitable for matching against declension titles. + */ + fun getLocalizedKeyword( + language: String, + annotationText: String, + ): String { + val keyword = + when (annotationText.lowercase()) { + "accusative case" -> "Acc" + "dative case" -> "Dat" + "genitive case" -> "Gen" + "locative case" -> "Loc" + "prepositional case" -> "Pre" + "instrumental case" -> "Ins" + else -> "" + } + return processValuesForPreposition(language, keyword) + } } diff --git a/app/src/main/java/be/scri/helpers/DatabaseManagers.kt b/app/src/main/java/be/scri/helpers/DatabaseManagers.kt index 491220110..bf811ba24 100644 --- a/app/src/main/java/be/scri/helpers/DatabaseManagers.kt +++ b/app/src/main/java/be/scri/helpers/DatabaseManagers.kt @@ -7,6 +7,7 @@ import be.scri.helpers.data.AutoSuggestionDataManager import be.scri.helpers.data.AutocompletionDataManager import be.scri.helpers.data.ConjugateDataManager import be.scri.helpers.data.ContractDataLoader +import be.scri.helpers.data.DeclensionDataManager import be.scri.helpers.data.EmojiDataManager import be.scri.helpers.data.GenderDataManager import be.scri.helpers.data.PluralFormsManager @@ -37,6 +38,8 @@ class DatabaseManagers( val suggestionManager = AutoSuggestionDataManager(fileManager) val autocompletionManager = AutocompletionDataManager(fileManager) + val declensionManager = DeclensionDataManager() + /** * A facade method to load the data contract for a given language. * It delegates the loading and parsing logic to the [ContractDataLoader]. diff --git a/app/src/main/java/be/scri/helpers/data/DeclensionDataManager.kt b/app/src/main/java/be/scri/helpers/data/DeclensionDataManager.kt new file mode 100644 index 000000000..fcaae0bf2 --- /dev/null +++ b/app/src/main/java/be/scri/helpers/data/DeclensionDataManager.kt @@ -0,0 +1,47 @@ +package be.scri.helpers.data + +import DataContract +import DeclensionNode +import be.scri.latin.utils.Log + +class DeclensionDataManager { + fun getDeclensions( + language: String, + yamlData: DataContract?, + ): LinkedHashMap> { + Log.d(TAG, "Loading declensions for language $language") + val returnCases = mutableMapOf>() + + val declensionsDictionary = yamlData?.declensions ?: return LinkedHashMap(returnCases) + + val sortedDeclensionKeys = declensionsDictionary.keys.sorted() + + for (key in sortedDeclensionKeys) { + val declension = declensionsDictionary[key] + val title = declension?.title ?: declension?.sectionTitle + val forms = declension?.declensionForms + + if (title != null && forms != null) { + val options = parseForms(forms) + returnCases[title] = options + } + } + + return LinkedHashMap(returnCases) + } + + private fun parseForms(forms: Map): List { + val options = mutableListOf() + for (key in forms.keys.sorted()) { + val node = forms[key] ?: continue + if (node.value != null || !node.declensionForms.isNullOrEmpty()) { + options.add(node) + } + } + return options + } + + companion object { + const val TAG = "DeclensionManager" + } +} diff --git a/app/src/main/java/be/scri/helpers/data/PrepositionDataManager.kt b/app/src/main/java/be/scri/helpers/data/PrepositionDataManager.kt index 884216de5..24ee55ef3 100644 --- a/app/src/main/java/be/scri/helpers/data/PrepositionDataManager.kt +++ b/app/src/main/java/be/scri/helpers/data/PrepositionDataManager.kt @@ -57,7 +57,10 @@ class PrepositionDataManager( val case = cursor.getString(caseIndex) if (prep != null && case != null) { - result.getOrPut(prep) { mutableListOf() }.add(case) + val cases = case.split("|").map { it.trim() }.filter { it.isNotEmpty() } + for (c in cases) { + result.getOrPut(prep.lowercase().trim()) { mutableListOf() }.add(c) + } } } while (cursor.moveToNext()) diff --git a/app/src/main/java/be/scri/models/DataContract.kt b/app/src/main/java/be/scri/models/DataContract.kt index f6ce93c97..a4b856d65 100644 --- a/app/src/main/java/be/scri/models/DataContract.kt +++ b/app/src/main/java/be/scri/models/DataContract.kt @@ -15,6 +15,7 @@ data class DataContract( val nouns: Nouns, val verbs: Verbs, val translations: Translations, + val declensions: Map = emptyMap(), ) /** @@ -73,6 +74,28 @@ data class ConjugationCategory( val tenseForms: Map, ) +/** + * Represents the structure of declensions for a language. + */ +@Serializable +data class Declensions( + val title: String? = null, + val sectionTitle: String? = null, + val declensionForms: Map? = null, +) + +/** + * Represents a node in the declension tree. + */ +@Serializable +data class DeclensionNode( + val label: String? = null, + val value: String? = null, + val displayValue: String? = null, + val title: String? = null, + val declensionForms: Map? = null, +) + @Serializable data class TenseForm( val label: String, diff --git a/app/src/main/java/be/scri/models/ScribeState.kt b/app/src/main/java/be/scri/models/ScribeState.kt index 83782d670..ee5a170a6 100644 --- a/app/src/main/java/be/scri/models/ScribeState.kt +++ b/app/src/main/java/be/scri/models/ScribeState.kt @@ -13,4 +13,5 @@ enum class ScribeState { SELECT_VERB_CONJUNCTION, INVALID, ALREADY_PLURAL, + SELECT_DECLENSION, } diff --git a/app/src/main/java/be/scri/views/KeyboardView.kt b/app/src/main/java/be/scri/views/KeyboardView.kt index 6ceb257bc..b1845ca89 100644 --- a/app/src/main/java/be/scri/views/KeyboardView.kt +++ b/app/src/main/java/be/scri/views/KeyboardView.kt @@ -31,7 +31,6 @@ import android.view.accessibility.AccessibilityManager import android.view.inputmethod.EditorInfo import android.widget.PopupWindow import android.widget.TextView -import androidx.core.content.edit import androidx.core.graphics.createBitmap import androidx.core.graphics.withSave import be.scri.R @@ -944,21 +943,6 @@ class KeyboardView val shadowOffsetY = SHADOW_OFFSET_Y if ((code == DISPLAY_LEFT) || (code == DISPLAY_RIGHT)) { - val sharedPreferences = - context.getSharedPreferences( - "keyboard_preferences", - Context.MODE_PRIVATE, - ) - sharedPreferences.edit(commit = true) { - val currentValue = sharedPreferences.getInt("conjugate_index", 0) - val newValue = - when (code) { - DISPLAY_LEFT -> currentValue + 1 - DISPLAY_RIGHT -> currentValue - 1 - else -> currentValue - } - putInt("conjugate_index", newValue) - } val density = context.resources.displayMetrics.density key.height = (KEY_HEIGHT * density).toInt() + LEFT_RIGHT_CONJUGATE_KEY_EXTRA_HEIGHT } diff --git a/app/src/main/res/values-night/colors.xml b/app/src/main/res/values-night/colors.xml index 0587b35ce..e46036a7f 100644 --- a/app/src/main/res/values-night/colors.xml +++ b/app/src/main/res/values-night/colors.xml @@ -43,6 +43,7 @@ @color/light_scribe_color #000000 #FB5F6C + @color/white #339EEB #AC6DEC #85C26F diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index fa8f0c45f..31c2e5e88 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -808,6 +808,7 @@ #3D7946 #F85A39 + #FF000000 @color/light_keyboard_bg_color diff --git a/app/src/test/kotlin/be/scri/helpers/AnnotationTextUtilsTest.kt b/app/src/test/kotlin/be/scri/helpers/AnnotationTextUtilsTest.kt new file mode 100644 index 000000000..71458c51a --- /dev/null +++ b/app/src/test/kotlin/be/scri/helpers/AnnotationTextUtilsTest.kt @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +package be.scri.helpers + +import android.content.Context +import be.scri.R +import io.mockk.every +import io.mockk.mockk +import org.junit.Assert.assertEquals +import org.junit.Test + +class AnnotationTextUtilsTest { + private val context = mockk() + + @Test + fun testGetLocalizedKeywordCaseInsensitivity() { + assertEquals("Acc", AnnotationTextUtils.getLocalizedKeyword("English", "accusative case")) + assertEquals("Acc", AnnotationTextUtils.getLocalizedKeyword("English", "Accusative Case")) + assertEquals("Acc", AnnotationTextUtils.getLocalizedKeyword("English", "ACCUSATIVE CASE")) + assertEquals("Dat", AnnotationTextUtils.getLocalizedKeyword("English", "dative case")) + assertEquals("Gen", AnnotationTextUtils.getLocalizedKeyword("English", "genitive case")) + } + + @Test + fun testGetLocalizedKeywordRussianConversions() { + // prepAnnotationConversionDict mapping for Russian: + // "Acc" to "Вин", "Dat" to "Дат", "Gen" to "Род", "Loc" to "Мес", "Pre" to "Пре", "Ins" to "Инс" + assertEquals("Вин", AnnotationTextUtils.getLocalizedKeyword("Russian", "accusative case")) + assertEquals("Дат", AnnotationTextUtils.getLocalizedKeyword("Russian", "dative case")) + assertEquals("Род", AnnotationTextUtils.getLocalizedKeyword("Russian", "genitive case")) + assertEquals("Мес", AnnotationTextUtils.getLocalizedKeyword("Russian", "locative case")) + assertEquals("Пре", AnnotationTextUtils.getLocalizedKeyword("Russian", "prepositional case")) + assertEquals("Инс", AnnotationTextUtils.getLocalizedKeyword("Russian", "instrumental case")) + } + + @Test + fun testHandleTextForCaseAnnotation() { + every { context.getString(R.string.i18n_app_keyboard_suggestion) } returns "Suggestion" + val result = AnnotationTextUtils.handleTextForCaseAnnotation("dative case", "English", context) + assertEquals(R.color.annotateDeclension, result.first) + assertEquals("Dat", result.second) + + val resultGerman = AnnotationTextUtils.handleTextForCaseAnnotation("accusative case", "German", context) + assertEquals(R.color.annotateDeclension, resultGerman.first) + assertEquals("Akk", resultGerman.second) + } + + @Test + fun testHandleColorAndTextForNounType() { + every { context.getString(R.string.i18n_app_keyboard_suggestion) } returns "Suggestion" + + val resultPlural = AnnotationTextUtils.handleColorAndTextForNounType("PL", "English", context) + assertEquals(R.color.annotateOrange, resultPlural.first) + assertEquals("PL", resultPlural.second) + + val resultMasc = AnnotationTextUtils.handleColorAndTextForNounType("masculine", "English", context) + assertEquals(R.color.annotateBlue, resultMasc.first) + assertEquals("M", resultMasc.second) + + val resultMascRu = AnnotationTextUtils.handleColorAndTextForNounType("Masculine", "Russian", context) + assertEquals(R.color.annotateBlue, resultMascRu.first) + assertEquals("М", resultMascRu.second) + } +} diff --git a/app/src/testKeyboards/kotlin/be/scri/helpers/KeyboardTest.kt b/app/src/testKeyboards/kotlin/be/scri/helpers/KeyboardTest.kt new file mode 100644 index 000000000..6c8d76a18 --- /dev/null +++ b/app/src/testKeyboards/kotlin/be/scri/helpers/KeyboardTest.kt @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +package be.scri.helpers + +import android.content.Context +import android.os.Handler +import android.view.KeyEvent +import android.view.LayoutInflater +import android.view.inputmethod.InputConnection +import android.widget.Button +import androidx.test.core.app.ApplicationProvider +import be.scri.databinding.InputMethodViewBinding +import be.scri.models.ScribeState +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import io.mockk.verify +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class KeyboardTest { + private lateinit var context: Context + private lateinit var binding: InputMethodViewBinding + private val ime = mockk(relaxed = true) + private val inputConnection = mockk(relaxed = true) + private lateinit var keyHandler: KeyHandler + private lateinit var suggestionHandler: SuggestionHandler + private lateinit var translateBtn: Button + private lateinit var conjugateBtn: Button + private lateinit var pluralBtn: Button + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + binding = InputMethodViewBinding.inflate(LayoutInflater.from(context)) + + every { ime.getInputConnection() } returns inputConnection + every { ime.keyboard } returns mockk(relaxed = true) + every { ime.currentState } returns ScribeState.IDLE + every { ime.language } returns "German" + every { ime.profanity } returns emptySet() + + translateBtn = binding.translateBtn + conjugateBtn = binding.conjugateBtn + pluralBtn = binding.pluralBtn + + every { ime.binding } returns binding + + suggestionHandler = SuggestionHandler(ime) + every { ime.suggestionHandler } returns suggestionHandler + + keyHandler = KeyHandler(ime) + } + + @Test + fun testBackspaceReducesStringLengthByOne() { + val initialText = "Hello World" + var currentText = initialText + + every { ime.currentState } returns ScribeState.IDLE + every { inputConnection.getTextBeforeCursor(any(), any()) } returns currentText + every { ime.handleDelete(false) } answers { + if (currentText.isNotEmpty()) { + currentText = currentText.dropLast(1) + } + inputConnection.deleteSurroundingText(1, 0) + } + every { inputConnection.deleteSurroundingText(1, 0) } returns true + + keyHandler.handleKey(KeyboardBase.KEYCODE_DELETE, "en") + + assert(currentText.length == initialText.length - 1) { + "Expected length ${initialText.length - 1}, but got ${currentText.length}" + } + assert(currentText == "Hello Worl") { + "Expected 'Hello Worl', but got '$currentText'" + } + + verify(exactly = 1) { ime.handleDelete(false) } + verify(exactly = 1) { inputConnection.deleteSurroundingText(1, 0) } + } + + @Test + fun testEnterKeyInsertsNewLine() { + every { ime.currentState } returns ScribeState.IDLE + every { ime.handleKeycodeEnter() } answers { + inputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)) + inputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)) + } + + keyHandler.handleKey(KeyboardBase.KEYCODE_ENTER, "en") + + verify(exactly = 1) { ime.handleKeycodeEnter() } + verify(exactly = 1) { + inputConnection.sendKeyEvent(match { it.action == KeyEvent.ACTION_DOWN && it.keyCode == KeyEvent.KEYCODE_ENTER }) + } + verify(exactly = 1) { + inputConnection.sendKeyEvent(match { it.action == KeyEvent.ACTION_UP && it.keyCode == KeyEvent.KEYCODE_ENTER }) + } + } + + @Test + fun testPrepositionTriggersDeclensionSuggestion() { + val handler = mockk(relaxed = true) + val runnableSlot = slot() + every { handler.postDelayed(capture(runnableSlot), any()) } returns true + + val preposition = "mit" + every { ime.language } returns "German" + every { ime.findGenderForLastWord(any(), any()) } returns null + every { ime.getCaseAnnotationForPreposition(any(), preposition) } returns mutableListOf("dative case") + + suggestionHandler = SuggestionHandler(ime, handler) + suggestionHandler.processLinguisticSuggestions(preposition) + + runnableSlot.captured.run() + + verify(exactly = 1) { + ime.updateAutoSuggestText( + nounTypeSuggestion = null, + isPlural = false, + caseAnnotationSuggestion = mutableListOf("dative case"), + ) + } + } + + @Test + fun processSuggestions() { + val handler = mockk(relaxed = true) + val runnableSlot = slot() + every { handler.postDelayed(capture(runnableSlot), any()) } returns true + + every { ime.findGenderForLastWord(any(), "in") } returns listOf("Neuter") + every { ime.findWhetherWordIsPlural(any(), "in") } returns false + every { ime.getCaseAnnotationForPreposition(any(), "in") } returns null + + every { ime.updateAutoSuggestText(any(), any(), any()) } answers { + conjugateBtn.text = "der" + pluralBtn.text = "den" + translateBtn.text = "die" + } + + suggestionHandler = SuggestionHandler(ime, handler) + suggestionHandler.processLinguisticSuggestions("in") + + runnableSlot.captured.run() + + assert(conjugateBtn.text == "der") + assert(pluralBtn.text == "den") + assert(translateBtn.text == "die") + } +} diff --git a/app/src/testKeyboards/kotlin/be/scri/helpers/ui/KeyboardUIManagerTest.kt b/app/src/testKeyboards/kotlin/be/scri/helpers/ui/KeyboardUIManagerTest.kt index a68de5fec..c92340fb2 100644 --- a/app/src/testKeyboards/kotlin/be/scri/helpers/ui/KeyboardUIManagerTest.kt +++ b/app/src/testKeyboards/kotlin/be/scri/helpers/ui/KeyboardUIManagerTest.kt @@ -85,6 +85,8 @@ class KeyboardUIManagerTest { conjugateLabels = null, selectedConjugationSubCategory = null, currentVerbForConjugation = null, + declensionOutput = null, + currentDeclensionSubNodes = null, ) assertEquals(View.VISIBLE, commandOptionsBar.visibility) @@ -113,14 +115,24 @@ class KeyboardUIManagerTest { autoSuggestEmojis = null, conjugateOutput = mockConjugateOutput, conjugateLabels = setOf("1ps", "2ps"), - selectedConjugationSubCategory = null, + selectedConjugationSubCategory = "1ps", currentVerbForConjugation = "be", + declensionOutput = null, + currentDeclensionSubNodes = null, ) assertEquals("Toolbar should be visible", View.VISIBLE, toolbarBar.visibility) assertEquals("Grid container should be visible", View.VISIBLE, conjugateGridContainer.visibility) assertEquals("Keyboard view should be GONE", View.GONE, keyboardView.visibility) + val grid = binding.conjugateGrid + assertTrue("Grid should have children", grid.childCount > 0) + val btn1 = grid.findViewById(be.scri.R.id.conjugate_btn_1) + assertTrue(btn1.text.toString().contains("I am")) + + btn1.performClick() + verify { listener.commitText("I am ") } + assertTrue(commandBarEditText.text.toString().contains("be")) } @@ -133,6 +145,37 @@ class KeyboardUIManagerTest { ) } + @Test + fun `updateUI SELECT_VERB_CONJUNCTION with subcategory shows sub-forms`() { + val mockConjugateOutput = + mapOf( + "Indicative" to + mapOf( + "Present" to listOf("" to "am", "" to "are", "" to "is"), + "Past" to listOf("" to "was", "" to "were"), + ), + ) + + val sharedPrefs = context.getSharedPreferences("keyboard_preferences", Context.MODE_PRIVATE) + sharedPrefs.edit().putInt("conjugate_index", 0).commit() + + uiManager.updateUI( + currentState = ScribeState.SELECT_VERB_CONJUNCTION, + language = "English", + emojiAutoSuggestionEnabled = false, + autoSuggestEmojis = null, + conjugateOutput = mockConjugateOutput, + conjugateLabels = setOf("1ps", "2ps", "3ps"), + selectedConjugationSubCategory = "Past", + currentVerbForConjugation = "be", + declensionOutput = null, + currentDeclensionSubNodes = null, + ) + + val btn1 = binding.conjugateGrid.findViewById(be.scri.R.id.conjugate_btn_1) + assertEquals("was", btn1.text.toString()) + } + @Test fun `updateUI INVALID state shows info icon`() { uiManager.updateUI( @@ -144,6 +187,8 @@ class KeyboardUIManagerTest { conjugateLabels = null, selectedConjugationSubCategory = null, currentVerbForConjugation = null, + declensionOutput = null, + currentDeclensionSubNodes = null, ) assertEquals(View.VISIBLE, toolbarBar.visibility) @@ -200,6 +245,8 @@ class KeyboardUIManagerTest { conjugateLabels = null, selectedConjugationSubCategory = null, currentVerbForConjugation = null, + declensionOutput = null, + currentDeclensionSubNodes = null, ) assertEquals("Toolbar bar should be visible in INVALID state", View.VISIBLE, toolbarBar.visibility) assertEquals("Info icon should be visible in INVALID state", View.VISIBLE, ivInfo.visibility) @@ -223,6 +270,8 @@ class KeyboardUIManagerTest { conjugateLabels = null, selectedConjugationSubCategory = null, currentVerbForConjugation = null, + declensionOutput = null, + currentDeclensionSubNodes = null, ) // Assert no orphaned UI elements remain. @@ -243,6 +292,8 @@ class KeyboardUIManagerTest { conjugateLabels = null, selectedConjugationSubCategory = null, currentVerbForConjugation = null, + declensionOutput = null, + currentDeclensionSubNodes = null, ) assertEquals("Info icon should be visible in ALREADY_PLURAL state", View.VISIBLE, ivInfo.visibility) @@ -261,6 +312,8 @@ class KeyboardUIManagerTest { conjugateLabels = null, selectedConjugationSubCategory = null, currentVerbForConjugation = null, + declensionOutput = null, + currentDeclensionSubNodes = null, ) // Assert that no orphaned UI elements remain. @@ -270,7 +323,18 @@ class KeyboardUIManagerTest { @Test fun `disableAutoSuggest resets buttons to commands`() { - uiManager.updateUI(ScribeState.IDLE, "English", false, null, null, null, null, null) + uiManager.updateUI( + ScribeState.IDLE, + "English", + false, + null, + null, + null, + null, + null, + declensionOutput = null, + currentDeclensionSubNodes = null, + ) uiManager.disableAutoSuggest("English") @@ -302,6 +366,8 @@ class KeyboardUIManagerTest { conjugateLabels = setOf("Present"), selectedConjugationSubCategory = null, currentVerbForConjugation = "be", + declensionOutput = null, + currentDeclensionSubNodes = null, ) // Assert @@ -332,6 +398,8 @@ class KeyboardUIManagerTest { conjugateLabels = setOf("Прошедшее"), selectedConjugationSubCategory = null, currentVerbForConjugation = "читать", + declensionOutput = null, + currentDeclensionSubNodes = null, ) // Assert @@ -361,6 +429,8 @@ class KeyboardUIManagerTest { conjugateLabels = setOf("Presens"), selectedConjugationSubCategory = null, currentVerbForConjugation = "vara", + declensionOutput = null, + currentDeclensionSubNodes = null, ) // Assert @@ -399,6 +469,8 @@ class KeyboardUIManagerTest { conjugateLabels = setOf("Präsens"), selectedConjugationSubCategory = null, currentVerbForConjugation = "haben", + declensionOutput = null, + currentDeclensionSubNodes = null, ) // Assert @@ -443,6 +515,8 @@ class KeyboardUIManagerTest { conjugateLabels = setOf("Present"), selectedConjugationSubCategory = "Singular", currentVerbForConjugation = "be", + declensionOutput = null, + currentDeclensionSubNodes = null, ) // Assert @@ -474,6 +548,8 @@ class KeyboardUIManagerTest { conjugateLabels = setOf("Present"), selectedConjugationSubCategory = null, currentVerbForConjugation = "verb", + declensionOutput = null, + currentDeclensionSubNodes = null, ) // Assert