From c3f249f3217dee8bf098f01558d39cff052792a5 Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Thu, 12 Nov 2026 10:33:54 -0500 Subject: [PATCH 01/69] Add opt-in live conversion for floating zenz candidates --- .../ime_service/IMEService.kt | 23 ++-- .../composing_guide/ComposingGuideSettings.kt | 1 + app/src/main/res/values-ja/zenz_floating.xml | 4 +- app/src/main/res/values/zenz_floating.xml | 4 +- app/src/main/res/xml/pref_zenz.xml | 6 + .../ime_service/ZenzFloatingFallbackTest.kt | 117 ++++++++++++++++++ .../ui/setting/ZenzFloatingSettingsTest.kt | 54 ++++++-- 7 files changed, 187 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt index c940342ff..261a1bb53 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt @@ -1756,14 +1756,19 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, isContinuousTapInputEnabled.set(true) lastFlickConvertedNextHiragana.set(true) if (!hasConvertedKatakana) { + // A completed floating result can arrive before the local live-conversion delay ends. + val zenzState = _zenzLiveSlotState.value + val composingCandidate = zenzState?.candidate?.takeIf { + canUseZenzFloatingPanel() && shouldApplyZenzLiveResultToComposingText(zenzState, it) + } ?: candidate if ( - candidate != null && - candidate.type != CANDIDATE_TYPE_TEXT_MACRO && - candidate.type != CANDIDATE_TYPE_FORMULA_UNICODE && - candidate.type != CANDIDATE_TYPE_FORMULA_TEX && - candidate.presentation == null + composingCandidate != null && + composingCandidate.type != CANDIDATE_TYPE_TEXT_MACRO && + composingCandidate.type != CANDIDATE_TYPE_FORMULA_UNICODE && + composingCandidate.type != CANDIDATE_TYPE_FORMULA_TEX && + composingCandidate.presentation == null ) { - applyFirstSuggestion(candidate) + applyFirstSuggestion(composingCandidate) } else { applyRawComposingFallback(insertString) } @@ -18959,7 +18964,11 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, state: ZenzLiveSlotState, candidate: Candidate ): Boolean { - if (canUseZenzFloatingPanel()) return false + if (canUseZenzFloatingPanel()) { + if (!runtimeInputSharedPreferences.getBoolean(ComposingGuideSettings.ZENZ_LIVE_CONVERSION, false)) return false + if (!shouldStartLiveConversion(state.displayInput)) return false + if (!shouldShowZenzFloatingCandidate(state)) return false + } if (suppressSuggestions) return false if (inputString.value != state.displayInput) return false if (state.requestToken != zenzLiveRequestToken) return false diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/composing_guide/ComposingGuideSettings.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/composing_guide/ComposingGuideSettings.kt index 3f0bb0ddc..7aa78d7c8 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/composing_guide/ComposingGuideSettings.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/composing_guide/ComposingGuideSettings.kt @@ -65,6 +65,7 @@ internal class ComposingGuideSettings(private val preferences: SharedPreferences companion object { const val ZENZ_ENABLED = "zenz_floating_candidates_enabled" + const val ZENZ_LIVE_CONVERSION = "zenz_floating_live_conversion_enabled" const val ZENZ_RESET = "zenz_floating_candidates_reset" const val SHOW_READING = "composing_guide_show_live_reading" const val SHOW_COMPOSING = "composing_guide_show_composing" // Legacy migration only. diff --git a/app/src/main/res/values-ja/zenz_floating.xml b/app/src/main/res/values-ja/zenz_floating.xml index 16a34a416..94b103249 100644 --- a/app/src/main/res/values-ja/zenz_floating.xml +++ b/app/src/main/res/values-ja/zenz_floating.xml @@ -2,7 +2,9 @@ 候補の表示 zenz の変換候補をフローティングで表示 - zenz の生成結果が通常の第一候補と異なる場合のみ表示します。ライブ変換には通常の候補を使い、フローティング候補をタップすると切り替えて確定します。 + zenz の生成結果が通常の第一候補と異なる場合のみ表示します。フローティング候補をタップすると確定します。 + フローティングの zenz 候補をライブ変換に反映 + ライブ変換が有効なとき、フローティングに表示する zenz 候補を入力中の変換テキストに反映します。オフのときは通常の候補を使います。 生成中… モデルと生成 diff --git a/app/src/main/res/values/zenz_floating.xml b/app/src/main/res/values/zenz_floating.xml index 7439f2720..a7d384afe 100644 --- a/app/src/main/res/values/zenz_floating.xml +++ b/app/src/main/res/values/zenz_floating.xml @@ -3,7 +3,9 @@ Candidate display Show zenz candidates in a floating panel - Show a generated candidate only when it differs from the regular first candidate. Live conversion uses regular candidates; tap the floating candidate to switch and commit. + Show a generated candidate only when it differs from the regular first candidate. Tap the floating candidate to commit it. + Use floating zenz candidates for live conversion + When live conversion is enabled, reflect the floating zenz candidate in the composing text. When off, live conversion uses regular candidates. Generating… Model and generation diff --git a/app/src/main/res/xml/pref_zenz.xml b/app/src/main/res/xml/pref_zenz.xml index 3efbc90f6..ebd62c103 100644 --- a/app/src/main/res/xml/pref_zenz.xml +++ b/app/src/main/res/xml/pref_zenz.xml @@ -30,6 +30,12 @@ android:defaultValue="false" android:title="@string/zenz_floating_title" android:summary="@string/zenz_floating_summary" /> + ()) + assertFalse(shouldApply(state)) + ReflectionHelpers.setField(service, "zenzLiveLocalCandidatesSnapshot", listOf(local)) + ReflectionHelpers.setField(service, "suppressSuggestions", true) + assertFalse(shouldApply(state)) + ReflectionHelpers.setField(service, "suppressSuggestions", false) + setInput("あお") + assertFalse(shouldApply(state)) + setInput("あか") + ReflectionHelpers.setField(service, "zenzLiveRequestToken", 1L) + assertFalse(shouldApply(state)) + } + + @Test fun enabledFloatingLiveConversionPreservesExplicitCandidateAndKatakanaSelection() { + enableFloatingLiveConversion() + val state = state(generated) + ReflectionHelpers.setField(service, "suggestionClickNum", 1) + assertFalse(shouldApply(state)) + ReflectionHelpers.setField(service, "suggestionClickNum", 0) + ReflectionHelpers.setField(service, "hasConvertedKatakana", true) + assertFalse(shouldApply(state)) + } + + @Test fun acceptingFloatingResultUpdatesCompositionOnlyWhenEnabledWithoutCommitting() { + val editor = editor(ApplicationProvider.getApplicationContext()) + val content = requireNotNull(editor.editable) + enableFloatingLiveConversion() + for (enabled in listOf(false, true)) { + preferences.edit().putBoolean(ComposingGuideSettings.ZENZ_LIVE_CONVERSION, enabled).commit() + editor.setComposingText(local.string, 1) + ReflectionHelpers.setField(service, "lastCandidate", local.string) + acceptGeneratedResult() + assertEquals(if (enabled) generated.string else local.string, content.toString()) + assertEquals(0, BaseInputConnection.getComposingSpanStart(content)) + assertEquals(content.length, BaseInputConnection.getComposingSpanEnd(content)) + assertEquals("あか", ReflectionHelpers.getField>(service, "_inputString").value) + } + } + + @Test fun delayedLocalLiveConversionKeepsTheEnabledFloatingResult() = runBlocking { + val editor = editor(ApplicationProvider.getApplicationContext()) + enableFloatingLiveConversion() + acceptGeneratedResult() + assertEquals(generated.string, editor.editable.toString()) + applyLocalLiveConversion() + assertEquals(generated.string, editor.editable.toString()) + preferences.edit().putBoolean(ComposingGuideSettings.ZENZ_LIVE_CONVERSION, false).commit() + applyLocalLiveConversion() + assertEquals(local.string, editor.editable.toString()) + } + @Test fun tappingGeneratedCandidateReplacesAndCommitsTheLocalComposition() { val context = ApplicationProvider.getApplicationContext() val editor = editor(context) @@ -188,6 +267,8 @@ class ZenzFloatingFallbackTest { setInput("あか") editor.setComposingText("垢", 1) assertTrue(visible(state)) + enableFloatingLiveConversion() + assertFalse(shouldApply(state)) IMEService::class.java.getDeclaredMethod("handleBunsetsuCandidateClick", Candidate::class.java, Int::class.javaPrimitiveType, List::class.java).apply { isAccessible = true } .invoke(service, generated, 0, listOf(generated)) @@ -203,9 +284,45 @@ class ZenzFloatingFallbackTest { override fun getEditable() = content } doReturn(editor).whenever(service).getCurrentInputConnection() + ReflectionHelpers.setField(service, "composingTextArbiter", ComposingTextArbiter( + writeComposingText = { text, cursor -> editor.setComposingText(text, cursor) }, + finishComposingText = { editor.finishComposingText() }, + copyText = { text -> android.text.SpannableString(text) }, + )) return editor } + private fun enableFloatingLiveConversion() { + preferences.edit().putBoolean(ComposingGuideSettings.ZENZ_LIVE_CONVERSION, true).commit() + setInput("あか") + ReflectionHelpers.setField(service, "isLiveConversionEnable", true) + ReflectionHelpers.setField(service, "liveConversionStartLength", 1) + ReflectionHelpers.setField(service, "zenzEnableLongPressConversionPreference", true) + ReflectionHelpers.setField(service, "zenzLiveSnapshotDisplayInput", "あか") + ReflectionHelpers.setField(service, "zenzLiveLocalCandidatesSnapshot", listOf(local)) + } + + private fun acceptGeneratedResult() { + val state = state(null) + ReflectionHelpers.getField>(service, "_zenzLiveSlotState").value = state + val context = IMEService::class.java.getDeclaredMethod("currentZenzCorrectionContext", CandidateQueryMode::class.java) + .apply { isAccessible = true }.invoke(service, CandidateQueryMode.NO_TAB_DEFAULT) + val source = state.javaClass.getDeclaredField("source").apply { isAccessible = true }.get(state) + val metaClass = IMEService::class.java.declaredClasses.first { it.simpleName == "ZenzLiveResultMeta" } + val meta = metaClass.declaredConstructors.first { it.parameterCount == 6 }.apply { isAccessible = true } + .newInstance(0L, "あか", "あか", source, context, null) + ReflectionHelpers.setField(service, "zenzLiveLatestResultMeta", meta) + IMEService::class.java.getDeclaredMethod("acceptZenzLiveResult", List::class.java) + .apply { isAccessible = true }.invoke(service, + listOf(ZenzCandidate(generated.string, generated.type, generated.length, generated.score, "あか"))) + } + + private suspend fun applyLocalLiveConversion(): Boolean = suspendCoroutineUninterceptedOrReturn { continuation -> + IMEService::class.java.getDeclaredMethod("applyFirstSuggestionOnMainIfCurrent", String::class.java, + Candidate::class.java, CandidateRequestToken::class.java, kotlin.coroutines.Continuation::class.java) + .apply { isAccessible = true }.invoke(service, "あか", local, null, continuation) + } + private fun setInput(text: String) { ReflectionHelpers.getField>(service, "_inputString").value = text } diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/ZenzFloatingSettingsTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/ZenzFloatingSettingsTest.kt index 9e7cb7e5c..a04d8fcef 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/ZenzFloatingSettingsTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/ZenzFloatingSettingsTest.kt @@ -5,12 +5,14 @@ import androidx.test.core.app.ApplicationProvider import com.kazumaproject.markdownhelperkeyboard.R import com.kazumaproject.markdownhelperkeyboard.variant.AppVariantConfig import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference +import com.kazumaproject.markdownhelperkeyboard.ime_service.composing_guide.ComposingGuideSettings import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import org.xmlpull.v1.XmlPullParser @RunWith(RobolectricTestRunner::class) @Config(sdk = [35]) @@ -19,22 +21,48 @@ class ZenzFloatingSettingsTest { @Before fun initializePreferences() { AppPreference.init(context) } @Test fun newAndLegacySettingsShareTheZenzPreferenceKeys() { - val key = "zenz_floating_candidates_enabled" val modernItems = SettingSearchIndex.searchable(context) val legacyItems = SettingSearchIndex.legacySearchable(context) - if (!AppVariantConfig.hasZenz) { - assertFalse(modernItems.any { it.key == key }) - assertFalse(legacyItems.any { it.key == key }) - return + for (key in listOf(ComposingGuideSettings.ZENZ_ENABLED, ComposingGuideSettings.ZENZ_LIVE_CONVERSION)) { + if (!AppVariantConfig.hasZenz) { + assertFalse(modernItems.any { it.key == key }) + assertFalse(legacyItems.any { it.key == key }) + continue + } + val modern = modernItems.first { it.key == key } + val legacy = legacyItems.first { it.key == key } + val toggle = modern.destination as SettingDestinationType.SwitchPreference + assertFalse(toggle.defaultValue) + assertEquals(R.id.zenzPreferenceFragment, toggle.destinationId) + assertEquals(key, legacy.legacyTarget?.preferenceKey) + assertEquals(SettingTabRegistry.TAB_ZENZ, legacy.legacyTarget?.tabKey) } - val modern = modernItems.first { it.key == key } - val legacy = legacyItems.first { it.key == key } - val toggle = modern.destination as SettingDestinationType.SwitchPreference - assertFalse(toggle.defaultValue) - assertEquals(R.id.zenzPreferenceFragment, toggle.destinationId) - assertEquals(key, legacy.legacyTarget?.preferenceKey) - assertEquals(SettingTabRegistry.TAB_ZENZ, legacy.legacyTarget?.tabKey) - assertEquals(R.xml.pref_zenz, SettingTabRegistry.createTabs().first { it.key == SettingTabRegistry.TAB_ZENZ }.xmlRes) + if (AppVariantConfig.hasZenz) { + assertEquals(R.xml.pref_zenz, SettingTabRegistry.createTabs().first { it.key == SettingTabRegistry.TAB_ZENZ }.xmlRes) + } + } + + @Test fun liveConversionSwitchFollowsAndDependsOnFloatingDisplayWithDefaultOff() { + val namespace = "http://schemas.android.com/apk/res/android" + val keys = mutableListOf() + context.resources.getXml(R.xml.pref_zenz).use { parser -> + while (parser.eventType != XmlPullParser.END_DOCUMENT) { + if (parser.eventType == XmlPullParser.START_TAG) { + val key = parser.getAttributeValue(namespace, "key") + if (key != null) keys.add(key) + if (key == ComposingGuideSettings.ZENZ_LIVE_CONVERSION) { + assertEquals("SwitchPreferenceCompat", parser.name) + assertFalse(parser.getAttributeBooleanValue(namespace, "defaultValue", true)) + assertEquals(ComposingGuideSettings.ZENZ_ENABLED, + parser.getAttributeValue(namespace, "dependency")) + } + } + parser.next() + } + } + assertTrue(keys.contains(ComposingGuideSettings.ZENZ_LIVE_CONVERSION)) + assertEquals(keys.indexOf(ComposingGuideSettings.ZENZ_ENABLED) + 1, + keys.indexOf(ComposingGuideSettings.ZENZ_LIVE_CONVERSION)) } @Test fun obsoletePositionResetIsNotSearchable() { val key = "zenz_floating_candidates_reset" From 20c45783e3584683aafc518621a05d47d118de04 Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Thu, 12 Nov 2026 10:53:56 -0500 Subject: [PATCH 02/69] Improve QWERTY key editing with live visual previews --- .../CustomQwertyKeyDeviceTest.kt | 26 +- .../custom_keyboard/ui/QwertyKeyEditorView.kt | 336 +++++++++++++++--- app/src/main/res/values-ja/strings.xml | 39 +- app/src/main/res/values/strings.xml | 39 +- .../ui/QwertyKeyEditorViewTest.kt | 144 ++++++++ 5 files changed, 509 insertions(+), 75 deletions(-) diff --git a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/CustomQwertyKeyDeviceTest.kt b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/CustomQwertyKeyDeviceTest.kt index 8dc098207..520506f05 100644 --- a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/CustomQwertyKeyDeviceTest.kt +++ b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/CustomQwertyKeyDeviceTest.kt @@ -19,6 +19,8 @@ import androidx.test.filters.SdkSuppress import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry import androidx.test.runner.lifecycle.Stage import androidx.test.platform.app.InstrumentationRegistry +import com.google.android.material.button.MaterialButton +import com.google.android.material.textfield.TextInputLayout import com.kazumaproject.core.domain.skin.KeyboardSkinId import com.kazumaproject.custom_keyboard.data.* import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui.KeyboardEditorFragment @@ -296,7 +298,25 @@ class CustomQwertyKeyDeviceTest { main { val fragment = host().childFragmentManager.primaryNavigationFragment as KeyEditorFragment fragment.requireView().findViewById(R.id.chip_qwerty).performClick() - fragment.requireView().findViewById(R.id.qwerty_key_editor).setConfig(expected) + val editor = fragment.requireView().findViewById(R.id.qwerty_key_editor) + fun click(text: Int) = descendants(editor).filterIsInstance() + .first { it.text == context.getString(text) }.performClick() + fun edit(hint: Int, value: String) = descendants(editor).filterIsInstance() + .first { it.hint == context.getString(hint) }.editText!!.setText(value) + click(R.string.qwerty_edit_key) + edit(R.string.qwerty_tap_output, "edited") + edit(R.string.qwerty_key_label, "Key label") + edit(R.string.qwerty_preview_label, "Preview") + edit(R.string.qwerty_columns, "2") + click(R.string.qwerty_add_slot) + edit(R.string.qwerty_candidate_output, "one") + edit(R.string.qwerty_candidate_label, "First") + click(R.string.qwerty_add_slot) + click(R.string.qwerty_add_slot) + edit(R.string.qwerty_candidate_output, "👩‍💻") + assertEquals(expected, editor.config) + assertTrue(descendants(editor).filterIsInstance().any { + it.text == context.getString(R.string.qwerty_candidate_result, "👩‍💻") }) assertTrue(fragment.requireView().findViewById(R.id.chip_qwerty).isChecked) assertTrue(fragment.requireView().findViewById(R.id.button_done).isEnabled) } @@ -307,6 +327,10 @@ class CustomQwertyKeyDeviceTest { } main { val fragment = host().childFragmentManager.primaryNavigationFragment as KeyEditorFragment + val editor = fragment.requireView().findViewById(R.id.qwerty_key_editor) + val candidateInput = descendants(editor).filterIsInstance() + .first { it.hint == context.getString(R.string.qwerty_candidate_output) }.editText!! + assertEquals("👩‍💻", candidateInput.text.toString()) val done = fragment.requireView().findViewById(R.id.button_done) assertTrue(done.isEnabled) done.performClick() diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/QwertyKeyEditorView.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/QwertyKeyEditorView.kt index 3cb97eb7f..92ac2a2f9 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/QwertyKeyEditorView.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/QwertyKeyEditorView.kt @@ -1,25 +1,35 @@ package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui import android.content.Context +import android.os.Bundle +import android.os.Parcelable import android.text.InputFilter import android.text.InputType +import android.text.TextUtils import android.util.AttributeSet import android.view.Gravity +import android.view.View import android.widget.CheckBox import android.widget.EditText +import android.widget.HorizontalScrollView import android.widget.LinearLayout import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView +import androidx.core.view.isVisible import androidx.core.widget.doAfterTextChanged import com.google.android.material.button.MaterialButton +import com.google.android.material.card.MaterialCardView +import com.google.android.material.color.MaterialColors +import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import com.kazumaproject.custom_keyboard.data.QwertyKeyConfig import com.kazumaproject.custom_keyboard.data.QwertyKeyLayer import com.kazumaproject.custom_keyboard.data.QwertyPopupSlot import com.kazumaproject.markdownhelperkeyboard.R +import com.google.android.material.R as MaterialR -/** Keeps the whole draft in one immutable model while switching layers or grid cells. */ +/** The previews and their editors share one draft, including blank popup positions. */ class QwertyKeyEditorView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : LinearLayout(context, attrs) { @@ -29,103 +39,213 @@ class QwertyKeyEditorView @JvmOverloads constructor( private var shifted = false private var binding = false private var selectedSlot = -1 + private var detailsExpanded = false private val normalTab = RadioButton(context).apply { id = generateViewId(); setText(R.string.qwerty_layer_normal) } private val shiftTab = RadioButton(context).apply { id = generateViewId(); setText(R.string.qwerty_layer_shift) } private val tabs = RadioGroup(context).apply { orientation = HORIZONTAL - addView(normalTab) - addView(shiftTab) + addView(normalTab, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)) + addView(shiftTab, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)) check(normalTab.id) } private val overrideShift = CheckBox(context).apply { setText(R.string.qwerty_custom_shift) } - private val label = field(R.string.qwerty_key_label) + private val shiftHelp = text(R.string.qwerty_shift_help) + private val label = field(R.string.qwerty_key_label, optional = true) private val output = field(R.string.qwerty_tap_output) - private val preview = field(R.string.qwerty_preview_label) - private val columns = field(R.string.qwerty_columns).apply { inputType = InputType.TYPE_CLASS_NUMBER } - private val grid = LinearLayout(context).apply { orientation = VERTICAL } - private val selection = TextView(context) + private val preview = field(R.string.qwerty_preview_label, optional = true) + private val details = vertical().apply { + listOf(output, label, preview).forEach { addView(it.container()) } + } + private val keyPreview = previewButton(false) + private val pressPreview = previewButton(true) + private val tapResult = text().apply { gravity = Gravity.CENTER } + private val editKey = button(R.string.qwerty_edit_key) { + detailsExpanded = !detailsExpanded + renderDetails() + } + private val columns = field(R.string.qwerty_columns).apply { + inputType = InputType.TYPE_CLASS_NUMBER + gravity = Gravity.CENTER + isSingleLine = true + } + private val fewerColumns = button(R.string.qwerty_fewer_columns) { changeColumns(-1) }.apply { + contentDescription = context.getString(R.string.qwerty_fewer_columns_description) + } + private val moreColumns = button(R.string.qwerty_more_columns) { changeColumns(1) }.apply { + contentDescription = context.getString(R.string.qwerty_more_columns_description) + } + private val grid = vertical().apply { setPadding(dp(8), dp(8), dp(8), dp(8)) } + private val gridScroll = HorizontalScrollView(context).apply { + isFillViewport = true + addView(grid, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + } + private val emptyGrid = text(R.string.qwerty_no_candidates) + private val gridSurface = MaterialCardView(context).apply { + cardElevation = 0f + strokeWidth = 0 + radius = dp(12).toFloat() + setCardBackgroundColor(MaterialColors.getColor(this, MaterialR.attr.colorSurfaceContainer)) + addView(gridScroll) + } + private val selection = text().apply { setTextAppearance(MaterialR.style.TextAppearance_Material3_TitleSmall) } private val slotOutput = field(R.string.qwerty_candidate_output) - private val slotLabel = field(R.string.qwerty_candidate_label) - private val controls = LinearLayout(context).apply { orientation = VERTICAL } + private val slotLabel = field(R.string.qwerty_candidate_label, optional = true) + private val slotResult = text() + private val controls = vertical() private val append = button(R.string.qwerty_add_slot) { - if (layer().slots.size < QwertyKeyConfig.MAX_SLOTS) { + if (editable() && layer().slots.size < QwertyKeyConfig.MAX_SLOTS) { val slots = layer().slots + QwertyPopupSlot() selectedSlot = slots.lastIndex updateLayer(layer().copy(slots = slots)) render() + slotOutput.requestFocus() } } private val before = button(R.string.qwerty_move_before) { moveSlot(-1) } private val after = button(R.string.qwerty_move_after) { moveSlot(1) } private val clear = button(R.string.qwerty_clear_slot) { changeSlot(QwertyPopupSlot()); render() } private val remove = button(R.string.qwerty_remove_slot) { - val slots = layer().slots.toMutableList() - if (selectedSlot in slots.indices) { - slots.removeAt(selectedSlot) - selectedSlot = selectedSlot.coerceAtMost(slots.lastIndex) - updateLayer(layer().copy(slots = slots)) - render() + if (editable()) { + val slots = layer().slots.toMutableList() + if (selectedSlot in slots.indices) { + slots.removeAt(selectedSlot) + selectedSlot = selectedSlot.coerceAtMost(slots.lastIndex) + updateLayer(layer().copy(slots = slots)) + render() + } } } - val isInputValid: Boolean get() = config.isValid() && columns.text.toString().toIntOrNull() in 1..QwertyKeyConfig.MAX_COLUMNS + val isInputValid: Boolean get() = config.isValid() && validColumns() init { orientation = VERTICAL addView(tabs) addView(overrideShift) - listOf(label, output, preview, columns).forEach { addView(it.parent.parent as TextInputLayout) } - addView(TextView(context).apply { setText(R.string.qwerty_grid_help) }) - addView(grid) + addView(shiftHelp) + addView(heading(R.string.qwerty_key_preview_title)) + val previews = LinearLayout(context).apply { + gravity = Gravity.CENTER + setPadding(dp(8), dp(12), dp(8), dp(12)) + listOf(R.string.qwerty_key_appearance to keyPreview, + R.string.qwerty_press_appearance to pressPreview).forEach { (title, button) -> + addView(vertical().apply { + gravity = Gravity.CENTER + addView(text(title).apply { gravity = Gravity.CENTER }) + addView(button, LayoutParams(dp(88), dp(80))) + }, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)) + } + } + addView(MaterialCardView(context).apply { + cardElevation = 0f + strokeWidth = 0 + radius = dp(16).toFloat() + setCardBackgroundColor(MaterialColors.getColor(this, MaterialR.attr.colorSurfaceContainer)) + addView(previews) + }, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + addView(tapResult) + addView(editKey) + addView(details) + addView(heading(R.string.qwerty_popup_preview_title)) + addView(text(R.string.qwerty_gesture_help)) + addView(text(R.string.qwerty_grid_help)) + addView(LinearLayout(context).apply { + gravity = Gravity.CENTER_VERTICAL + addView(fewerColumns, LayoutParams(dp(56), LayoutParams.WRAP_CONTENT)) + addView(columns.container(), LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)) + addView(moreColumns, LayoutParams(dp(56), LayoutParams.WRAP_CONTENT)) + }) + addView(emptyGrid) + addView(gridSurface) addView(append) - addView(selection) - controls.addView(slotOutput.parent.parent as TextInputLayout) - controls.addView(slotLabel.parent.parent as TextInputLayout) - listOf(before, after, clear, remove).forEach(controls::addView) + controls.addView(selection) + controls.addView(slotOutput.container()) + controls.addView(slotLabel.container()) + controls.addView(slotResult) + controls.addView(actionRow(before, after)) + controls.addView(actionRow(clear, remove)) addView(controls) tabs.setOnCheckedChangeListener { _, id -> - shifted = id == shiftTab.id - selectedSlot = -1 - render() + if (!binding) { + shifted = id == shiftTab.id + selectedSlot = -1 + render(bindColumns = true) + onChanged?.invoke() + } } overrideShift.setOnCheckedChangeListener { _, checked -> if (!binding) { config = config.copy(shifted = if (checked) config.normal.uppercase() else null) - render() + selectedSlot = -1 + render(bindColumns = true) onChanged?.invoke() } } - listOf(label, output, preview, columns).forEach { edit -> + listOf(label, output, preview).forEach { edit -> edit.doAfterTextChanged { - if (!binding) { + if (!binding && editable()) { updateLayer(layer().copy(label = label.text.toString(), output = output.text.toString(), - preview = preview.text.toString(), columns = columns.text.toString().toIntOrNull() - ?.takeIf { it in 1..QwertyKeyConfig.MAX_COLUMNS } ?: layer().columns)) - (columns.parent.parent as TextInputLayout).error = if (columns.text.toString().toIntOrNull() in 1..QwertyKeyConfig.MAX_COLUMNS) - null else context.getString(R.string.qwerty_columns_error, QwertyKeyConfig.MAX_COLUMNS) - renderGrid() + preview = preview.text.toString())) + renderPreviews() } } } + columns.doAfterTextChanged { + if (!binding && editable()) { + if (validColumns()) updateLayer(layer().copy(columns = columns.text.toString().toInt())) + renderColumns() + renderSelectionLabel() + renderGrid() + onChanged?.invoke() + } + } listOf(slotOutput, slotLabel).forEach { edit -> edit.doAfterTextChanged { - if (!binding) { + if (!binding && editable()) { changeSlot(QwertyPopupSlot(slotOutput.text.toString(), slotLabel.text.toString())) + renderSlotResult() renderGrid() } } } - render() + render(bindColumns = true) } fun setConfig(value: QwertyKeyConfig) { config = value selectedSlot = -1 - render() + detailsExpanded = value.normal.output.isEmpty() + render(bindColumns = true) + onChanged?.invoke() + } + + override fun onSaveInstanceState(): Parcelable = Bundle().apply { + putParcelable("parent", super.onSaveInstanceState()) + putBoolean("shifted", shifted) + putInt("selectedSlot", selectedSlot) + putBoolean("detailsExpanded", detailsExpanded) + putString("columns", columns.text.toString()) + } + + override fun onRestoreInstanceState(state: Parcelable?) { + if (state !is Bundle) { + super.onRestoreInstanceState(state) + return + } + @Suppress("DEPRECATION") + super.onRestoreInstanceState(state.getParcelable("parent")) + binding = true + shifted = state.getBoolean("shifted") + tabs.check(if (shifted) shiftTab.id else normalTab.id) + selectedSlot = state.getInt("selectedSlot", -1).takeIf { it in layer().slots.indices } ?: -1 + detailsExpanded = state.getBoolean("detailsExpanded") + render(bindColumns = true) + columns.setText(state.getString("columns", layer().columns.toString())) onChanged?.invoke() } private fun layer(): QwertyKeyLayer = if (shifted) config.shifted ?: config.normal.uppercase() else config.normal private fun editable() = !shifted || config.shifted != null + private fun validColumns() = columns.text.toString().toIntOrNull() in 1..QwertyKeyConfig.MAX_COLUMNS private fun updateLayer(value: QwertyKeyLayer) { if (!editable()) return config = if (shifted) config.copy(shifted = value) else config.copy(normal = value) @@ -137,7 +257,11 @@ class QwertyKeyEditorView @JvmOverloads constructor( slots[selectedSlot] = value updateLayer(layer().copy(slots = slots)) } + private fun changeColumns(delta: Int) { + columns.setText((layer().columns + delta).coerceIn(1, QwertyKeyConfig.MAX_COLUMNS).toString()) + } private fun moveSlot(delta: Int) { + if (!editable()) return val slots = layer().slots.toMutableList() val destination = selectedSlot + delta if (selectedSlot !in slots.indices || destination !in slots.indices) return @@ -148,63 +272,159 @@ class QwertyKeyEditorView @JvmOverloads constructor( updateLayer(layer().copy(slots = slots)) render() } - private fun render() { + private fun render(bindColumns: Boolean = false) { binding = true val value = layer() - overrideShift.visibility = if (shifted) VISIBLE else GONE + overrideShift.isVisible = shifted + shiftHelp.isVisible = shifted && config.shifted == null overrideShift.isChecked = config.shifted != null label.setText(value.label) output.setText(value.output) preview.setText(value.preview) - columns.setText(value.columns.toString()) + if (bindColumns) columns.setText(value.columns.toString()) listOf(label, output, preview, columns).forEach { it.isEnabled = editable() } append.isEnabled = editable() && value.slots.size < QwertyKeyConfig.MAX_SLOTS val slot = value.slots.getOrNull(selectedSlot) - selection.text = if (slot == null) "" else context.getString(R.string.qwerty_selected_slot, - selectedSlot / value.columns + 1, selectedSlot % value.columns + 1) - controls.visibility = if (slot == null) GONE else VISIBLE + controls.isVisible = slot != null + renderSelectionLabel() slotOutput.setText(slot?.output.orEmpty()) slotLabel.setText(slot?.label.orEmpty()) - listOf(slotOutput, slotLabel, before, after, clear, remove).forEach { it.isEnabled = editable() } + listOf(slotOutput, slotLabel, clear, remove).forEach { it.isEnabled = editable() } before.isEnabled = editable() && selectedSlot > 0 after.isEnabled = editable() && selectedSlot < value.slots.lastIndex + renderDetails() + renderPreviews() + renderColumns() + renderSlotResult() renderGrid() binding = false } + private fun renderDetails() { + details.isVisible = detailsExpanded + editKey.setText(if (detailsExpanded) R.string.qwerty_close_key_editor else R.string.qwerty_edit_key) + } + private fun renderPreviews() { + val value = layer() + keyPreview.text = value.displayLabel.ifEmpty { context.getString(R.string.qwerty_unset) } + pressPreview.text = value.previewLabel.ifEmpty { context.getString(R.string.qwerty_unset) } + keyPreview.contentDescription = context.getString(R.string.qwerty_edit_appearance, keyPreview.text) + pressPreview.contentDescription = context.getString(R.string.qwerty_edit_press_appearance, pressPreview.text) + tapResult.text = context.getString(R.string.qwerty_tap_result, + value.output.ifEmpty { context.getString(R.string.qwerty_unset) }) + output.container().error = if (value.output.isEmpty()) context.getString(R.string.qwerty_output_required) else null + } + private fun renderColumns() { + columns.container().error = if (validColumns()) null else + context.getString(R.string.qwerty_columns_error, QwertyKeyConfig.MAX_COLUMNS) + fewerColumns.isEnabled = editable() && (!validColumns() || layer().columns > 1) + moreColumns.isEnabled = editable() && (!validColumns() || layer().columns < QwertyKeyConfig.MAX_COLUMNS) + } + private fun renderSelectionLabel() { + selection.text = if (selectedSlot !in layer().slots.indices) "" else context.getString( + R.string.qwerty_selected_slot, selectedSlot / layer().columns + 1, selectedSlot % layer().columns + 1) + } + private fun renderSlotResult() { + slotResult.text = layer().slots.getOrNull(selectedSlot)?.output?.takeIf { it.isNotEmpty() } + ?.let { context.getString(R.string.qwerty_candidate_result, it) } + ?: context.getString(R.string.qwerty_blank_result) + } private fun renderGrid() { grid.removeAllViews() val value = layer() - val rows = value.slots.chunked(value.columns) - rows.forEachIndexed { rowIndex, slots -> - val row = LinearLayout(context).apply { orientation = HORIZONTAL; gravity = Gravity.CENTER_VERTICAL } + emptyGrid.isVisible = value.slots.isEmpty() + gridSurface.isVisible = value.slots.isNotEmpty() + // Wide popups retain usable touch targets rather than squeezing twelve cells into the screen. + grid.minimumWidth = dp(56) * value.columns + dp(16) + value.slots.chunked(value.columns).forEachIndexed { rowIndex, slots -> + val row = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL } repeat(value.columns) { col -> val index = rowIndex * value.columns + col val slot = slots.getOrNull(col) - row.addView(MaterialButton(context).apply { - text = if (slot == null || slot.output.isEmpty()) context.getString(R.string.qwerty_empty_slot) else slot.displayLabel + val cell = MaterialButton(context, null, MaterialR.attr.materialButtonOutlinedStyle).apply { + text = if (slot == null) "" else if (slot.output.isEmpty()) + context.getString(R.string.qwerty_empty_slot) else slot.displayLabel maxLines = 2 + ellipsize = TextUtils.TruncateAt.END minWidth = 0 minimumWidth = 0 - contentDescription = context.getString(R.string.qwerty_selected_slot, rowIndex + 1, col + 1) + ": " + text - isEnabled = slot != null + minimumHeight = dp(56) + cornerRadius = dp(8) + setPadding(dp(4), 0, dp(4), 0) isCheckable = true isChecked = index == selectedSlot + isEnabled = slot != null + importantForAccessibility = if (slot == null) View.IMPORTANT_FOR_ACCESSIBILITY_NO else View.IMPORTANT_FOR_ACCESSIBILITY_YES + contentDescription = context.getString(R.string.qwerty_cell_description, + rowIndex + 1, col + 1, text, + slot?.output?.takeIf { it.isNotEmpty() } ?: context.getString(R.string.qwerty_blank_result)) + strokeWidth = if (slot?.output?.isEmpty() == true) dp(1) else 0 + if (slot?.output?.isNotEmpty() == true) { + setBackgroundColor(MaterialColors.getColor(this, MaterialR.attr.colorSurface)) + setTextColor(MaterialColors.getColor(this, MaterialR.attr.colorOnSurface)) + } + if (isChecked) { + setBackgroundColor(MaterialColors.getColor(this, MaterialR.attr.colorSecondaryContainer)) + setTextColor(MaterialColors.getColor(this, MaterialR.attr.colorOnSecondaryContainer)) + } setOnClickListener { selectedSlot = index; render() } - }, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)) + } + // The unfilled end of the last popup row is not a saved blank slot. + cell.visibility = if (slot == null) INVISIBLE else VISIBLE + row.addView(cell, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f).apply { + setMargins(dp(2), 0, dp(2), 0) + }) } grid.addView(row) } } - private fun field(hintRes: Int): EditText { - val layout = TextInputLayout(context).apply { hint = context.getString(hintRes) } - return com.google.android.material.textfield.TextInputEditText(context).apply { + private fun field(hintRes: Int, optional: Boolean = false): EditText { + val layout = TextInputLayout(context).apply { + hint = context.getString(hintRes) + if (optional) { + placeholderText = context.getString(R.string.qwerty_same_as_input) + helperText = context.getString(R.string.qwerty_display_fallback) + } + layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { topMargin = dp(12) } + } + return TextInputEditText(context).apply { inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS filters = arrayOf(InputFilter.LengthFilter(QwertyKeyConfig.MAX_TEXT_LENGTH)) layout.addView(this, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) } } - private fun button(textRes: Int, action: () -> Unit) = MaterialButton(context).apply { + private fun EditText.container() = parent.parent as TextInputLayout + private fun vertical() = LinearLayout(context).apply { orientation = VERTICAL } + private fun text(textRes: Int? = null) = TextView(context).apply { + setTextAppearance(MaterialR.style.TextAppearance_Material3_BodyMedium) + setPadding(0, dp(8), 0, dp(8)) + if (textRes != null) setText(textRes) + } + private fun heading(textRes: Int) = text(textRes).apply { + setTextAppearance(MaterialR.style.TextAppearance_Material3_TitleMedium) + layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { topMargin = dp(16) } + androidx.core.view.ViewCompat.setAccessibilityHeading(this, true) + } + private fun actionRow(vararg buttons: MaterialButton) = LinearLayout(context).apply { + buttons.forEach { addView(it, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f).apply { setMargins(dp(2), 0, dp(2), 0) }) } + } + private fun previewButton(pressed: Boolean) = MaterialButton(context, null, + if (pressed) MaterialR.attr.materialButtonStyle else MaterialR.attr.materialButtonOutlinedStyle).apply { + textSize = 28f + cornerRadius = dp(if (pressed) 16 else 10) + maxLines = 2 + ellipsize = TextUtils.TruncateAt.END + minWidth = 0 + minimumWidth = 0 + setPadding(dp(4), 0, dp(4), 0) + setOnClickListener { detailsExpanded = true; renderDetails() } + } + private fun button(textRes: Int, action: () -> Unit) = MaterialButton(context, null, + MaterialR.attr.materialButtonOutlinedStyle).apply { setText(textRes) + minWidth = 0 + minimumWidth = 0 + setPadding(dp(8), 0, dp(8), 0) setOnClickListener { action() } } + private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt() } diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 85d7c4f8e..6ef0c21c7 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1986,15 +1986,15 @@ ABC abc 0123456789 ABC 12345 通常 Shift / Caps Lock Shift 専用の設定を使う - キーの表示(省略時は入力文字列) - タップで入力する文字列 - 押下プレビューの表示(省略時は入力文字列) - ポップアップの列数 + キーに表示する文字(任意) + タップで入力する文字 + 押したときに表示する文字(任意) + 横に並べる数 列数は 1〜%1$d で指定してください - マスをタップして表示と入力を編集します。「空白にする」は位置を残します。Shift 専用設定がない場合、英字は大文字になります。 - 候補の入力文字列(空欄なら空白マス) - 候補の表示(省略時は入力文字列) - マスを追加 + 候補をタップして編集できます。列が多い場合は左右にスクロールできます。 + 入力する文字(空欄なら空白マス) + 候補に表示する文字(任意) + + 候補を追加 前へ移動 後ろへ移動 空白にする @@ -2005,4 +2005,27 @@ ABC abc 0123456789 ABC 12345 押したキーの文字を拡大表示します。長押し候補は表示設定にかかわらず選択できます。 QWERTY 型ポップアップの表示 標準 QWERTY とサイズ・文字設定を共用します + キーのプレビュー + 長押し候補のプレビュー + キーボードの表示 + 押したときの表示 + キーの表示・入力を編集 + 表示・入力の編集を閉じる + − + + + 長押し候補はまだありません。「候補を追加」から並べる文字を設定できます。 + 長押し → 候補へ指を動かす → 離して入力 + 通常設定の英字を大文字にしたプレビューです。この状態を編集するには「Shift 専用の設定を使う」をオンにしてください。 + タップで入力 → %1$s + 選んで離すと入力 → %1$s + 空白マスでは入力されません。「空白にする」は位置を残し、「マスを削除」は間を詰めます。 + 入力する文字と同じ + 未設定 + このキーをタップして入力する文字を設定してください。 + キーの表示を編集:%1$s + 押したときの表示を編集:%1$s + %1$d 行 %2$d 列:%3$s。入力:%4$s + 横に並べる候補を減らす + 横に並べる候補を増やす + 空欄なら入力する文字を表示します。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a2014e4f2..4216c4c1e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1988,15 +1988,15 @@ ABC abc 0123456789 ABC 12345 Normal Shift / Caps Lock Use custom Shift settings - Key label (empty: input text) - Tap input text - Key preview text (empty: input text) - Popup columns + Text shown on the key (optional) + Text entered on tap + Text shown when pressed (optional) + Columns across Enter a column count from 1 to %1$d - Tap a cell to edit its label and input. Clear a cell to keep an empty position. Without custom Shift settings, ASCII letters become uppercase. - Candidate input (empty: blank cell) - Candidate label (empty: input text) - Add a cell + Tap a candidate to edit it. Swipe sideways to see wide grids. + Text to enter (empty: blank cell) + Text shown on the candidate (optional) + + Add candidate Move before Move after Clear cell @@ -2007,4 +2007,27 @@ ABC abc 0123456789 ABC 12345 Enlarge the pressed key text. Long-press alternatives remain available. QWERTY popup appearance Share size and text settings with the standard QWERTY keyboard + Key preview + Long-press candidate preview + On the keyboard + When pressed + Edit key appearance and input + Close key appearance and input editor + − + + + No long-press candidates yet. Add a candidate to start building the popup. + Hold the key → slide to a candidate → release to enter it. + Previewing automatic Shift: ASCII letters become uppercase. Enable custom Shift settings to edit this layer. + Tap to enter → %1$s + Select and release to enter → %1$s + Blank position: nothing is entered. Clear keeps this position; remove closes the gap. + Same as the text to enter + Not set + Enter the text to type when this key is tapped. + Edit key appearance: %1$s + Edit pressed preview: %1$s + Row %1$d, column %2$d: %3$s. Input: %4$s + Fewer popup columns + More popup columns + Leave empty to show the text to enter. diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/QwertyKeyEditorViewTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/QwertyKeyEditorViewTest.kt index e7eb8d134..59423978f 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/QwertyKeyEditorViewTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/QwertyKeyEditorViewTest.kt @@ -1,11 +1,16 @@ package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui import android.content.Context +import android.os.Parcelable +import android.util.SparseArray import android.view.ContextThemeWrapper import android.view.View import android.view.ViewGroup import android.widget.EditText +import android.widget.CheckBox +import android.widget.HorizontalScrollView import android.widget.RadioButton +import android.widget.TextView import androidx.test.core.app.ApplicationProvider import com.google.android.material.button.MaterialButton import com.google.android.material.textfield.TextInputLayout @@ -20,6 +25,9 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [35]) class QwertyKeyEditorViewTest { + private val context get() = ContextThemeWrapper(ApplicationProvider.getApplicationContext(), + com.google.android.material.R.style.Theme_Material3_DayNight_NoActionBar) + @Test fun editingColumnsAndSlotLabelsKeepsBlanksAndIndependentShiftLayer() { val context = ContextThemeWrapper(ApplicationProvider.getApplicationContext(), com.google.android.material.R.style.Theme_Material3_DayNight_NoActionBar) @@ -46,6 +54,142 @@ class QwertyKeyEditorViewTest { assertFalse(editor.isInputValid) } + @Test fun previewOpensEditorAndTracksIndependentDisplayAndOutputWithFallbacks() { + val editor = QwertyKeyEditorView(context) + editor.setConfig(QwertyKeyConfig(QwertyKeyLayer("a"))) + val input = edit(editor, R.string.qwerty_tap_output) + assertEquals(View.GONE, (input.parent.parent.parent as View).visibility) + descendants(editor).filterIsInstance() + .first { it.contentDescription == editor.context.getString(R.string.qwerty_edit_appearance, "a") } + .performClick() + assertEquals(View.VISIBLE, (input.parent.parent.parent as View).visibility) + edit(editor, R.string.qwerty_key_label).setText("Key") + edit(editor, R.string.qwerty_preview_label).setText("Peek") + input.setText("actual input") + assertTrue(descendants(editor).filterIsInstance().any { it.text == "Key" }) + assertTrue(descendants(editor).filterIsInstance().any { it.text == "Peek" }) + assertText(editor, R.string.qwerty_tap_result, "actual input") + edit(editor, R.string.qwerty_key_label).setText("") + edit(editor, R.string.qwerty_preview_label).setText("") + assertEquals(2, descendants(editor).filterIsInstance().count { it.text == "actual input" }) + input.setText("") + assertFalse(editor.isInputValid) + assertNotNull((input.parent.parent as TextInputLayout).error) + input.setText("👩‍💻") + assertTrue(editor.isInputValid) + assertNull((input.parent.parent as TextInputLayout).error) + assertEquals("👩‍💻", editor.config.normal.output) + } + + @Test fun addEditReorderClearAndRemoveCandidatesMatchesVisibleInputResult() { + val editor = QwertyKeyEditorView(context) + editor.setConfig(QwertyKeyConfig(QwertyKeyLayer("a", columns = 2))) + assertEquals(View.VISIBLE, descendants(editor).filterIsInstance().first { + it.text == editor.context.getString(R.string.qwerty_no_candidates) }.visibility) + click(editor, R.string.qwerty_add_slot) + edit(editor, R.string.qwerty_candidate_output).setText("first output") + edit(editor, R.string.qwerty_candidate_label).setText("First") + assertText(editor, R.string.qwerty_candidate_result, "first output") + click(editor, R.string.qwerty_add_slot) + edit(editor, R.string.qwerty_candidate_output).setText("second") + click(editor, R.string.qwerty_move_before) + assertEquals(listOf("second", "first output"), editor.config.normal.slots.map { it.output }) + assertText(editor, R.string.qwerty_selected_slot, 1, 1) + click(editor, R.string.qwerty_more_columns) + assertEquals(3, editor.config.normal.columns) + click(editor, R.string.qwerty_clear_slot) + assertEquals(listOf("", "first output"), editor.config.normal.slots.map { it.output }) + assertText(editor, R.string.qwerty_blank_result) + click(editor, R.string.qwerty_remove_slot) + assertEquals(listOf(QwertyPopupSlot("first output", "First")), editor.config.normal.slots) + assertText(editor, R.string.qwerty_candidate_result, "first output") + click(editor, R.string.qwerty_remove_slot) + assertTrue(editor.config.normal.slots.isEmpty()) + assertEquals(View.VISIBLE, descendants(editor).filterIsInstance().first { + it.text == editor.context.getString(R.string.qwerty_no_candidates) }.visibility) + } + + @Test fun automaticShiftPreviewIsReadOnlyAndOverrideCanBeEditedIndependently() { + val editor = QwertyKeyEditorView(context) + val normal = QwertyKeyLayer("a", slots = listOf(QwertyPopupSlot("abc", "label"))) + editor.setConfig(QwertyKeyConfig(normal)) + descendants(editor).filterIsInstance().first { + it.text == editor.context.getString(R.string.qwerty_layer_shift) }.performClick() + assertEquals("A", edit(editor, R.string.qwerty_tap_output).text.toString()) + assertFalse(edit(editor, R.string.qwerty_tap_output).isEnabled) + assertFalse(button(editor, R.string.qwerty_add_slot).isEnabled) + descendants(editor).filterIsInstance().first { it.text == "LABEL" }.performClick() + assertText(editor, R.string.qwerty_candidate_result, "ABC") + assertFalse(edit(editor, R.string.qwerty_candidate_output).isEnabled) + descendants(editor).filterIsInstance().single().performClick() + assertTrue(edit(editor, R.string.qwerty_tap_output).isEnabled) + edit(editor, R.string.qwerty_tap_output).setText("keepCase") + assertEquals("keepCase", editor.config.shifted!!.output) + assertEquals(normal, editor.config.normal) + descendants(editor).filterIsInstance().single().performClick() + assertNull(editor.config.shifted) + assertEquals("A", edit(editor, R.string.qwerty_tap_output).text.toString()) + } + + @Test fun wideGridKeepsTouchTargetsAndChangingColumnCountUpdatesSelectedCoordinates() { + val editor = QwertyKeyEditorView(context) + editor.setConfig(QwertyKeyConfig(QwertyKeyLayer("a", columns = 12, + slots = List(13) { QwertyPopupSlot("item$it") }))) + editor.measure(View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)) + editor.layout(0, 0, editor.measuredWidth, editor.measuredHeight) + val scroll = descendants(editor).filterIsInstance().single() + assertTrue(scroll.getChildAt(0).measuredWidth > scroll.measuredWidth) + val last = descendants(editor).filterIsInstance().first { it.text == "item12" } + assertTrue(last.measuredWidth >= (48 * editor.resources.displayMetrics.density).toInt()) + last.performClick() + assertText(editor, R.string.qwerty_selected_slot, 2, 1) + edit(editor, R.string.qwerty_columns).setText("3") + assertText(editor, R.string.qwerty_selected_slot, 5, 1) + assertEquals(13, editor.config.normal.slots.size) + edit(editor, R.string.qwerty_columns).setText("0") + assertFalse(editor.isInputValid) + assertNotNull((edit(editor, R.string.qwerty_columns).parent.parent as TextInputLayout).error) + descendants(editor).filterIsInstance().first { it.text == "item0" }.performClick() + assertFalse(editor.isInputValid) + assertEquals("0", edit(editor, R.string.qwerty_columns).text.toString()) + click(editor, R.string.qwerty_more_columns) + assertTrue(editor.isInputValid) + } + + @Test fun recreationRestoresShiftSelectionOpenEditorAndInvalidColumnDraft() { + val editor = QwertyKeyEditorView(context).apply { id = View.generateViewId() } + val normal = QwertyKeyLayer("a", slots = listOf(QwertyPopupSlot("abc", "caption"))) + editor.setConfig(QwertyKeyConfig(normal, normal.copy(output = "keepCase"))) + descendants(editor).filterIsInstance().first { + it.text == editor.context.getString(R.string.qwerty_layer_shift) }.performClick() + descendants(editor).filterIsInstance().first { it.text == "caption" }.performClick() + click(editor, R.string.qwerty_edit_key) + edit(editor, R.string.qwerty_columns).setText("0") + val state = SparseArray() + editor.saveHierarchyState(state) + val restored = QwertyKeyEditorView(context).apply { id = editor.id; setConfig(editor.config) } + restored.restoreHierarchyState(state) + assertTrue(descendants(restored).filterIsInstance().first { + it.text == restored.context.getString(R.string.qwerty_layer_shift) }.isChecked) + assertEquals("keepCase", edit(restored, R.string.qwerty_tap_output).text.toString()) + assertEquals("abc", edit(restored, R.string.qwerty_candidate_output).text.toString()) + assertEquals(View.VISIBLE, (edit(restored, R.string.qwerty_tap_output).parent.parent.parent as View).visibility) + assertFalse(restored.isInputValid) + assertEquals("0", edit(restored, R.string.qwerty_columns).text.toString()) + assertEquals(editor.config, restored.config) + } + + private fun edit(editor: QwertyKeyEditorView, hint: Int): EditText = descendants(editor) + .filterIsInstance().first { it.hint == editor.context.getString(hint) }.editText!! + private fun button(editor: QwertyKeyEditorView, text: Int): MaterialButton = descendants(editor) + .filterIsInstance().first { it.text == editor.context.getString(text) } + private fun click(editor: QwertyKeyEditorView, text: Int) { button(editor, text).performClick() } + private fun assertText(editor: QwertyKeyEditorView, text: Int, vararg args: Any) { + assertTrue(editor.context.getString(text, *args), descendants(editor).filterIsInstance() + .any { it.text == editor.context.getString(text, *args) }) + } + private fun descendants(view: View): List = listOf(view) + if (view is ViewGroup) (0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList() } From 83630892e8461283cc6a7935915cefc96939e812 Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Thu, 12 Nov 2026 12:54:07 -0500 Subject: [PATCH 03/69] Bump Android version to 1.7.151 (850) --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index d8473a4ed..e8fad3d39 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -41,8 +41,8 @@ android { applicationId "com.kazumaproject.markdownhelperkeyboard" minSdk 24 targetSdk 37 - versionCode 847 - versionName "1.7.150" + versionCode 850 + versionName "1.7.151" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } From 01cf84e1ff7f0c0684be94c60a4bc620d00144ad Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Thu, 12 Nov 2026 14:19:48 -0500 Subject: [PATCH 04/69] Use configurable QWERTY keys in templates and add number/symbol layouts --- .../ui/KeyboardEditorViewModel.kt | 8 ++ app/src/main/res/values-ja/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../ui/KeyboardEditorQwertyTemplateTest.kt | 95 +++++++++++++++++++ .../layout/KeyboardDefaultLayouts.kt | 86 +++++++++++++---- .../layout/AlphabetTemplateLayoutsTest.kt | 63 +++++++++++- 6 files changed, 235 insertions(+), 21 deletions(-) create mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorQwertyTemplateTest.kt diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorViewModel.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorViewModel.kt index b9b99c191..0b40a1cae 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorViewModel.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorViewModel.kt @@ -134,6 +134,14 @@ class KeyboardEditorViewModel @Inject constructor( R.string.template_qwerty, KeyboardDefaultLayouts.createQwertyTemplateLayout() ), + LayoutTemplate( + R.string.template_qwerty_number, + KeyboardDefaultLayouts.createQwertyNumberTemplateLayout() + ), + LayoutTemplate( + R.string.template_qwerty_symbol, + KeyboardDefaultLayouts.createQwertySymbolTemplateLayout() + ), LayoutTemplate( R.string.template_empty_5x4_flexible, KeyboardDefaultLayouts.createEmpty5x4FlexibleTemplateLayout() diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 6ef0c21c7..f8f57b487 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -746,6 +746,8 @@ かな入力(トグル) 英語入力 (カーソル) QWERTY + QWERTY(数字) + QWERTY(記号) 空のフレキシブルレイアウト 数字入力 半マスキー diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4216c4c1e..11ef17dff 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -790,6 +790,8 @@ Kana input (toggle) English input (cursor) QWERTY + QWERTY (Numbers) + QWERTY (Symbols) Empty 5x4 Flexible Layout Number input Half key diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorQwertyTemplateTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorQwertyTemplateTest.kt new file mode 100644 index 000000000..920289983 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorQwertyTemplateTest.kt @@ -0,0 +1,95 @@ +package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui + +import android.content.Context +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import com.kazumaproject.custom_keyboard.data.KeyAction +import com.kazumaproject.custom_keyboard.data.KeyItem +import com.kazumaproject.custom_keyboard.data.KeyType +import com.kazumaproject.custom_keyboard.data.KeyboardLayout +import com.kazumaproject.custom_keyboard.data.QwertyPopupSlot +import com.kazumaproject.custom_keyboard.data.copyWithKeys +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.import_export.KeyboardLayoutImportResult +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.import_export.KeyboardLayoutJsonExporter +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.import_export.KeyboardLayoutJsonImporter +import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase +import com.kazumaproject.markdownhelperkeyboard.repository.KeyboardRepository +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class KeyboardEditorQwertyTemplateTest { + @Test + fun applyEditSaveReloadAndBackup_preserveAllThreeTemplatesAndExistingLayouts() = runBlocking { + val context = ApplicationProvider.getApplicationContext() + val db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) + .allowMainThreadQueries().build() + try { + val repository = KeyboardRepository(db.keyboardLayoutDao()) + val editor = KeyboardEditorViewModel(repository) + val names = listOf(R.string.template_qwerty, R.string.template_qwerty_number, R.string.template_qwerty_symbol) + val start = editor.availableTemplates.indexOfFirst { it.nameResId == names.first() } + assertEquals(names, editor.availableTemplates.drop(start).take(3).map { it.nameResId }) + + // A layout saved before the template update must keep its original key type. + val original = editor.availableTemplates[start].layout.let { template -> + template.copyWithKeys(template.keys.map { it.copy(keyType = KeyType.NORMAL, qwertyConfig = null) }) + } + val oldId = repository.saveLayout(original, "Existing QWERTY", null) + val saved = names.map { name -> + editor.applyTemplate(editor.availableTemplates.single { it.nameResId == name }.layout) + val layout = editor.uiState.value.layout + assertTrue(keyboardEditorCapabilities(layout).showHalfCellControls) + assertTrue(layout.keys.filterNot { it.isSpecialKey }.all { it.keyType == KeyType.QWERTY }) + val key = layout.keys.first { !it.isSpecialKey } + val config = requireNotNull(key.qwertyConfig) + val normal = config.normal.copy(output = "custom text", + slots = listOf(QwertyPopupSlot("é"), QwertyPopupSlot(), QwertyPopupSlot("👩‍💻"))) + val edited = key.copy(label = normal.displayLabel, action = KeyAction.Text(normal.output), + qwertyConfig = config.copy(normal = normal)) + val expected = layout.copyWithKeys(layout.keys.map { if (it.keyId == key.keyId) edited else it }) + val id = repository.saveLayout(expected, context.getString(name), null) + assertLayoutContent(expected, repository.getFullLayout(id).first()) + expected + } + assertLayoutContent(original, repository.getFullLayout(oldId).first()) + val backups = repository.getAllFullLayoutsForExport().filter { it.layout.layoutId != oldId } + val imported = KeyboardLayoutJsonImporter.parse(KeyboardLayoutJsonExporter.toJson(backups)) + assertTrue(imported is KeyboardLayoutImportResult.Success) + repository.deleteLayoutConfirmed(oldId) + backups.forEach { repository.deleteLayoutConfirmed(it.layout.layoutId) } + assertTrue(repository.importLayouts((imported as KeyboardLayoutImportResult.Success).layouts) + is KeyboardLayoutImportResult.Success) + val restored = repository.getLayoutsNotFlow() + names.zip(saved).forEach { (name, expected) -> + val id = restored.single { it.name == context.getString(name) }.layoutId + assertLayoutContent(expected, repository.getFullLayout(id).first()) + } + } finally { + db.close() + } + } + + private fun assertLayoutContent(expected: KeyboardLayout, actual: KeyboardLayout) { + assertEquals(expected.columnUnitCount, actual.columnUnitCount) + assertEquals(expected.rowUnitCount, actual.rowUnitCount) + expected.keys.forEach { before -> + val after = actual.keys.single { it.keyId == before.keyId } + assertEquals(before.label, after.label) + assertEquals(before.action, after.action) + assertEquals(before.keyType, after.keyType) + assertEquals(before.qwertyConfig, after.qwertyConfig) + assertEquals(before.doubleTapBinding, after.doubleTapBinding) + } + fun placements(layout: KeyboardLayout) = layout.items.filterIsInstance() + .associate { it.keyData.keyId to it.placement } + assertEquals(placements(expected), placements(actual)) + } +} diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayouts.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayouts.kt index 862044a0f..93cd31a1d 100644 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayouts.kt +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayouts.kt @@ -1,5 +1,8 @@ package com.kazumaproject.custom_keyboard.layout +import com.kazumaproject.core.data.qwerty.QWERTYKeys +import com.kazumaproject.core.domain.qwerty.QWERTYKeyInfo +import com.kazumaproject.core.domain.qwerty.QWERTYKeyMap import com.kazumaproject.custom_keyboard.data.FlickAction import com.kazumaproject.custom_keyboard.data.FlickDirection import com.kazumaproject.custom_keyboard.data.DoubleTapBinding @@ -12,6 +15,9 @@ import com.kazumaproject.custom_keyboard.data.KeyType import com.kazumaproject.custom_keyboard.data.KeyboardInputMode import com.kazumaproject.custom_keyboard.data.KeyboardLayout import com.kazumaproject.custom_keyboard.data.KeyboardLayoutItem +import com.kazumaproject.custom_keyboard.data.QwertyKeyConfig +import com.kazumaproject.custom_keyboard.data.QwertyKeyLayer +import com.kazumaproject.custom_keyboard.data.QwertyPopupSlot import com.kazumaproject.custom_keyboard.data.SpacerItem import com.kazumaproject.custom_keyboard.data.TfbiFlickRotation import com.kazumaproject.custom_keyboard.data.SumireFlickInputMode @@ -4749,9 +4755,10 @@ object KeyboardDefaultLayouts { val columnSpanUnits: Int } - /** Plain character key (label is also the typed text). */ + /** Character key with the standard QWERTY tap and long-press layers. */ private data class CharKeySpec( val label: String, + val qwertyConfig: QwertyKeyConfig, override val columnSpanUnits: Int = 2 ) : TemplateItemSpec @@ -4814,9 +4821,10 @@ object KeyboardDefaultLayouts { action = KeyAction.Text(itemSpec.label), rowSpan = approxRowSpan, colSpan = approxColSpan, - keyType = KeyType.NORMAL, + keyType = KeyType.QWERTY, isSpecialKey = false, - keyId = keyId + keyId = keyId, + qwertyConfig = itemSpec.qwertyConfig ) items += KeyItem(id = keyId, keyData = keyData, placement = placement) keys += keyData @@ -4867,7 +4875,18 @@ object KeyboardDefaultLayouts { ) } - private fun chars(vararg s: String): List = s.map { CharKeySpec(it) } + private fun QWERTYKeyInfo.QWERTYVariation.toTemplateConfig(): QwertyKeyConfig { + fun layer(output: Char, candidates: List?) = QwertyKeyLayer( + output = output.toString(), + columns = candidates.orEmpty().size.coerceIn(1, 3), + slots = candidates.orEmpty().map { QwertyPopupSlot(output = it.toString()) } + ) + val tap = requireNotNull(tap) + return QwertyKeyConfig( + normal = layer(tap, variations), + shifted = layer(capChar ?: tap, capVariations ?: variations) + ) + } private val shiftSpec get() = SpecialKeySpec( @@ -4918,33 +4937,66 @@ object KeyboardDefaultLayouts { * Row 2: Shift | spacer | z x c v b n m | spacer | Delete * Row 3: SwitchIme | Space | Enter */ - fun createQwertyTemplateLayout(): KeyboardLayout { + fun createQwertyTemplateLayout(): KeyboardLayout = QWERTYKeyMap().let { keyMap -> + createQwertyTemplate( + "qwerty", "QWERTY", QWERTYKeys.DEFAULT_KEYS, middleRowSize = 9, + keyMap.keysDefault.map(keyMap::getKeyInfoDefault) + ) + } + + fun createQwertyNumberTemplateLayout(): KeyboardLayout = QWERTYKeyMap().let { keyMap -> + createQwertyTemplate( + "qwerty_number", "QWERTY (Numbers)", QWERTYKeys.NUMBER_KEYS, middleRowSize = 10, + keyMap.keysNumber.map(keyMap::getKeyInfoNumber) + ) + } + + fun createQwertySymbolTemplateLayout(): KeyboardLayout = QWERTYKeyMap().let { keyMap -> + createQwertyTemplate( + "qwerty_symbol", "QWERTY (Symbols)", QWERTYKeys.SYMBOL_KEYS, middleRowSize = 10, + keyMap.keysSymbol.map(keyMap::getKeyInfoSymbol) + ) + } + + private fun createQwertyTemplate( + idPrefix: String, + name: String, + characters: List, + middleRowSize: Int, + keyInfos: List + ): KeyboardLayout { + val configs = keyInfos.filterIsInstance() + .filter { it.tap != null } + .associate { it.tap!! to it.toTemplateConfig() } + fun chars(characters: List) = characters.map { char -> + CharKeySpec(char.toString(), configs.getValue(char)) + } + val bottomRow = characters.drop(10 + middleRowSize) + val bottomGap = (16 - bottomRow.size * 2) / 2 val spec = TemplateLayoutSpec( - idPrefix = "qwerty", - name = "QWERTY", + idPrefix = idPrefix, + name = name, rowUnitCount = 8, columnUnitCount = 20, rows = listOf( TemplateRowSpec( rowUnits = 0, - items = listOf( - *chars("q", "w", "e", "r", "t", "y", "u", "i", "o", "p").toTypedArray() - ) + items = chars(characters.take(10)) ), TemplateRowSpec( rowUnits = 2, - items = listOf( - SpacerSpec("row1_gap", columnSpanUnits = 1), - *chars("a", "s", "d", "f", "g", "h", "j", "k", "l").toTypedArray() - ) + items = buildList { + if (middleRowSize == 9) add(SpacerSpec("row1_gap", columnSpanUnits = 1)) + addAll(chars(characters.drop(10).take(middleRowSize))) + } ), TemplateRowSpec( rowUnits = 4, items = listOf( shiftSpec, - SpacerSpec("shift_gap", columnSpanUnits = 1), - *chars("z", "x", "c", "v", "b", "n", "m").toTypedArray(), - SpacerSpec("delete_gap", columnSpanUnits = 1), + SpacerSpec("shift_gap", columnSpanUnits = bottomGap), + *chars(bottomRow).toTypedArray(), + SpacerSpec("delete_gap", columnSpanUnits = bottomGap), deleteSpec ) ), diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/layout/AlphabetTemplateLayoutsTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/layout/AlphabetTemplateLayoutsTest.kt index 04c82b588..d411c1516 100644 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/layout/AlphabetTemplateLayoutsTest.kt +++ b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/layout/AlphabetTemplateLayoutsTest.kt @@ -1,5 +1,8 @@ package com.kazumaproject.custom_keyboard.layout +import com.kazumaproject.core.data.qwerty.QWERTYKeys +import com.kazumaproject.core.domain.qwerty.QWERTYKeyInfo +import com.kazumaproject.core.domain.qwerty.QWERTYKeyMap import com.kazumaproject.custom_keyboard.data.GridPlacement import com.kazumaproject.custom_keyboard.data.DoubleTapPolicy import com.kazumaproject.custom_keyboard.data.FlickAction @@ -95,7 +98,7 @@ class AlphabetTemplateLayoutsTest { ) } - private fun assertAllCharacterKeysAreNormalText(layout: KeyboardLayout) { + private fun assertAllCharacterKeysAreQwertyText(layout: KeyboardLayout) { layout.keys.filter { !it.isSpecialKey }.forEach { key -> val action = key.action assertTrue( @@ -103,9 +106,10 @@ class AlphabetTemplateLayoutsTest { action is KeyAction.Text && action.text == key.label ) assertEquals( - "Character key '${key.label}' must be NORMAL", - KeyType.NORMAL, key.keyType + "Character key '${key.label}' must be QWERTY", + KeyType.QWERTY, key.keyType ) + assertTrue(key.qwertyConfig?.isValid() == true) assertFalse("Character key '${key.label}' must not be flickable", key.isFlickable) assertNotNull("Character key '${key.label}' must have a keyId", key.keyId) } @@ -123,11 +127,62 @@ class AlphabetTemplateLayoutsTest { row0Labels(layout) ) assertHasSpecialKeys(layout, "QWERTY") - assertAllCharacterKeysAreNormalText(layout) + assertAllCharacterKeysAreQwertyText(layout) assertNotNull(layout.keys.firstOrNull { it.keyId == "qwerty_key_q" }) assertNotNull(layout.keys.firstOrNull { it.keyId == "qwerty_key_p" }) } + @Test + fun qwertyTemplates_matchStandardTapAndLongPressLayers() { + val map = QWERTYKeyMap() + val modes = listOf( + Triple(KeyboardDefaultLayouts.createQwertyTemplateLayout(), QWERTYKeys.DEFAULT_KEYS, + map.keysDefault.map(map::getKeyInfoDefault)), + Triple(KeyboardDefaultLayouts.createQwertyNumberTemplateLayout(), QWERTYKeys.NUMBER_KEYS, + map.keysNumber.map(map::getKeyInfoNumber)), + Triple(KeyboardDefaultLayouts.createQwertySymbolTemplateLayout(), QWERTYKeys.SYMBOL_KEYS, + map.keysSymbol.map(map::getKeyInfoSymbol)) + ) + modes.forEach { (layout, characters, infos) -> + assertCommonStructure(layout) + assertHasSpecialKeys(layout, "QWERTY") + assertAllCharacterKeysAreQwertyText(layout) + assertFalse(hasPlacementIssues(layout.items, layout.rowUnitCount, layout.columnUnitCount)) + assertEquals(layout.keys.size, layout.keys.map { it.keyId }.toSet().size) + val characterKeys = layout.items.filterIsInstance() + .filter { !it.keyData.isSpecialKey } + .sortedWith(compareBy({ it.placement.rowUnits }, { it.placement.columnUnits })) + .map { it.keyData } + assertEquals(characters.map(Char::toString), characterKeys.map { it.label }) + characterKeys.forEach { key -> + val info = infos.filterIsInstance() + .first { it.tap.toString() == key.label } + val config = key.qwertyConfig!! + val shifted = requireNotNull(config.shifted) + assertEquals(info.tap.toString(), config.normal.output) + assertEquals(info.variations.orEmpty().map(Char::toString), config.normal.slots.map { it.output }) + assertEquals((info.capChar ?: info.tap).toString(), shifted.output) + assertEquals((info.capVariations ?: info.variations).orEmpty().map(Char::toString), + shifted.slots.map { it.output }) + } + } + } + + @Test + fun numberAndSymbolTemplates_haveTenTenFiveCharactersAndCenteredBottomRow() { + listOf( + "qwerty_number" to KeyboardDefaultLayouts.createQwertyNumberTemplateLayout(), + "qwerty_symbol" to KeyboardDefaultLayouts.createQwertySymbolTemplateLayout() + ).forEach { (prefix, layout) -> + assertTrue(layout.keys.all { it.keyId!!.startsWith("${prefix}_") }) + val characters = layout.items.filterIsInstance().filter { !it.keyData.isSpecialKey } + assertEquals(listOf(10, 10, 5), listOf(0, 2, 4).map { row -> characters.count { it.placement.rowUnits == row } }) + val bottom = characters.filter { it.placement.rowUnits == 4 } + assertEquals(listOf(5, 7, 9, 11, 13), bottom.map { it.placement.columnUnits }) + assertTrue(bottom.all { it.placement.columnSpanUnits == 2 }) + } + } + @Test fun flickEnglishCursorTemplate_usesCommitAndInsertSpaceForTemplateSpaces() { val layout = KeyboardDefaultLayouts.createFlickEnglishTemplateLayout( From 34f5cc920d4a80c17dd18bfc4e25f0f4641d9464 Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Thu, 12 Nov 2026 15:13:34 -0500 Subject: [PATCH 05/69] Add independent custom QWERTY popup size settings --- .../ime_service/IMEService.kt | 23 ++++- .../setting_activity/AppPreference.kt | 5 ++ .../CustomQwertyPopupPreferences.kt | 62 +++++++++++++ .../ui/popup_style/PopupStyleFragments.kt | 40 +++++++-- .../CustomKeyboardPreferenceFragment.kt | 2 +- .../ui/setting/FrequentSettingFilters.kt | 1 + .../ui/setting/SettingDestination.kt | 1 + .../main/res/navigation/mobile_navigation.xml | 4 + app/src/main/res/values-ja/strings.xml | 9 +- app/src/main/res/values/strings.xml | 9 +- .../CustomQwertyPopupPreferencesTest.kt | 90 +++++++++++++++++++ .../controller/QwertyKeyInputController.kt | 11 +-- .../QwertyKeyInputControllerTest.kt | 53 ++++++++++- 13 files changed, 286 insertions(+), 24 deletions(-) create mode 100644 app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/CustomQwertyPopupPreferences.kt create mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/CustomQwertyPopupPreferencesTest.kt diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt index 261a1bb53..1375a184e 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt @@ -1081,6 +1081,19 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, ) private val runtimeInputPreferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { preferences, key -> + if (key == null || key.startsWith("custom_qwerty_") || key == "custom_keyboard_show_key_preview") { + runOnMainThread { + val styles = currentCustomQwertyPopupViewStyleSet() + val showPreview = appPreference.custom_keyboard_show_key_preview + listOfNotNull(mainLayoutBinding?.customLayoutDefault, + floatingKeyboardBinding?.customLayoutFloating).forEach { + it.setQwertyPopupSettings(showPreview, styles) + } + splitInputs.values.forEach { + it.binding.customLayoutFloating.setQwertyPopupSettings(showPreview, styles) + } + } + } if (key == null || key == AppPreference.TENKEY_SPECIAL_KEY_LABEL_SCALE_KEY) { runOnMainThread { val scale = appPreference.tenkey_special_key_label_scale_percent @@ -15765,11 +15778,13 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } private fun currentCustomQwertyPopupViewStyleSet(): QwertyPopupViewStyleSet { - val styles = currentQwertyPopupViewStyleSet() - if (keyboardThemeMode != "custom") return styles + val styles = appPreference.custom_qwerty_popup_preferences.styles() fun colors(style: PopupViewStyle) = style.copy( - backgroundColor = style.backgroundColor ?: customThemeSpecialKeyColor, - textColor = style.textColor ?: customThemeSpecialKeyTextColor + backgroundColor = popupBackgroundColorOrNull() + ?: customThemeSpecialKeyColor.takeIf { keyboardThemeMode == "custom" }, + textColor = popupTextColorOrNull() + ?: customThemeSpecialKeyTextColor.takeIf { keyboardThemeMode == "custom" }, + skinId = keyboardSkinId ) return styles.copy(keyPreview = colors(styles.keyPreview), variation = colors(styles.variation)) } diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreference.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreference.kt index 43b403ddc..ea74e4c83 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreference.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreference.kt @@ -1073,6 +1073,7 @@ object AppPreference { appContext.codeCacheDir.setReadOnly() isTabletDevice = context.resources.getBoolean(CoreR.bool.isTablet) loadedPreferences = PreferenceManager.getDefaultSharedPreferences(context) + CustomQwertyPopupPreferences.migrate(preferences) com.kazumaproject.markdownhelperkeyboard.setting_activity.keyboard_size.IndependentKeyboardSizePreferences.migrate(preferences) migrateCandidateHeightDefaultsIfNeeded() removeUnsafeLegacyGemmaHandwritingPrompt() @@ -3730,6 +3731,9 @@ object AppPreference { it.putFloat(TENKEY_POPUP_TEXT_SIZE_SP.first, value ?: TENKEY_POPUP_TEXT_SIZE_SP.second) } + val custom_qwerty_popup_preferences: CustomQwertyPopupPreferences + get() = CustomQwertyPopupPreferences(preferences) + var qwerty_key_preview_popup_size_scale_percent: Int? get() = preferences.getInt( QWERTY_KEY_PREVIEW_POPUP_SIZE_SCALE_PERCENT.first, @@ -5409,6 +5413,7 @@ object AppPreference { } migrateSumireKeymapGuideModesIfNeeded() migrateGojuonKeyboardTypeIfNeeded() + CustomQwertyPopupPreferences.migrate(preferences) com.kazumaproject.markdownhelperkeyboard.setting_activity.keyboard_size.IndependentKeyboardSizePreferences.migrate(preferences) return backup.shortcutIds } diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/CustomQwertyPopupPreferences.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/CustomQwertyPopupPreferences.kt new file mode 100644 index 000000000..97d9fc46f --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/CustomQwertyPopupPreferences.kt @@ -0,0 +1,62 @@ +package com.kazumaproject.markdownhelperkeyboard.setting_activity + +import android.content.SharedPreferences +import androidx.core.content.edit +import com.kazumaproject.core.data.popup.PopupViewStyle +import com.kazumaproject.core.data.popup.QwertyPopupViewStyleSet + +/** Custom QWERTY keys start with the previously shared values, then remain independent. */ +class CustomQwertyPopupPreferences(private val preferences: SharedPreferences) { + init { + migrate(preferences) + } + + var keyPreview: PopupViewStyle + get() = read(PREVIEW_SIZE, PREVIEW_TEXT) + set(value) = write(PREVIEW_SIZE, PREVIEW_TEXT, value) + + var variation: PopupViewStyle + get() = read(VARIATION_SIZE, VARIATION_TEXT) + set(value) = write(VARIATION_SIZE, VARIATION_TEXT, value) + + fun styles() = QwertyPopupViewStyleSet(keyPreview, variation) + + private fun read(sizeKey: String, textKey: String) = PopupViewStyle( + preferences.getInt(sizeKey, 100).coerceIn(50, 200), + preferences.getFloat(textKey, 28f).coerceIn(8f, 48f) + ) + + private fun write(sizeKey: String, textKey: String, value: PopupViewStyle) { + preferences.edit { + putInt(sizeKey, value.sizeScalePercent.coerceIn(50, 200)) + putFloat(textKey, value.textSizeSp.coerceIn(8f, 48f)) + } + } + + companion object { + const val PREVIEW_SIZE = "custom_qwerty_key_preview_popup_size_scale_percent" + const val PREVIEW_TEXT = "custom_qwerty_key_preview_popup_text_size_sp" + const val VARIATION_SIZE = "custom_qwerty_variation_popup_size_scale_percent" + const val VARIATION_TEXT = "custom_qwerty_variation_popup_text_size_sp" + + fun migrate(preferences: SharedPreferences) { + val sizes = mapOf( + PREVIEW_SIZE to "qwerty_key_preview_popup_size_scale_percent_preference", + VARIATION_SIZE to "qwerty_variation_popup_size_scale_percent_preference" + ) + val texts = mapOf( + PREVIEW_TEXT to "qwerty_key_preview_popup_text_size_sp_preference", + VARIATION_TEXT to "qwerty_variation_popup_text_size_sp_preference" + ) + if ((sizes.keys + texts.keys).all(preferences::contains)) return + preferences.edit { + sizes.forEach { (target, source) -> + if (!preferences.contains(target)) putInt(target, preferences.getInt(source, 100).coerceIn(50, 200)) + } + texts.forEach { (target, source) -> + if (!preferences.contains(target)) putFloat(target, preferences.getFloat(source, 28f).coerceIn(8f, 48f)) + } + } + } + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/popup_style/PopupStyleFragments.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/popup_style/PopupStyleFragments.kt index 08979a21b..9d632ea6a 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/popup_style/PopupStyleFragments.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/popup_style/PopupStyleFragments.kt @@ -25,6 +25,7 @@ import com.kazumaproject.core.data.popup.TfbiFlickStartPositionMode import com.kazumaproject.core.data.popup.TfbiPopupPresentationMode import com.kazumaproject.markdownhelperkeyboard.R import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference +import com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.navigateSafely class TenKeyPopupStyleSettingFragment : Fragment() { @@ -75,7 +76,8 @@ class TenKeyPopupStyleSettingFragment : Fragment() { } } -class QwertyPopupStyleSettingFragment : Fragment() { +open class QwertyPopupStyleSettingFragment : Fragment() { + protected open val useCustomKeyboardSettings = false override fun onCreateView( inflater: LayoutInflater, @@ -84,35 +86,51 @@ class QwertyPopupStyleSettingFragment : Fragment() { ): View { // MainActivity completes preference initialization before opening settings destinations. val root = editorRoot() - root.addView(sectionTitle("Key preview popup")) + val customPreferences = if (useCustomKeyboardSettings) AppPreference.custom_qwerty_popup_preferences else null + if (useCustomKeyboardSettings) { + root.addView(sectionTitle(getString(R.string.custom_qwerty_normal_key_size))) + root.addView(TextView(requireContext()).apply { setText(R.string.custom_qwerty_normal_key_size_summary) }) + root.addView(Button(requireContext()).apply { + setText(R.string.custom_qwerty_normal_key_size) + setOnClickListener { + navigateSafely(R.id.flickKeyboardSizeSettingsFragment, bundleOf("sizingSurface" to "custom")) + } + }) + root.addView(TextView(requireContext()).apply { setText(R.string.custom_qwerty_popup_scope) }) + } + root.addView(sectionTitle(getString(R.string.qwerty_tap_popup_section))) root.addView( styleEditorSection( preview = PopupStylePreviewView(requireContext()).apply { previewText = "A" }, - initialStyle = PopupViewStyle( + initialStyle = customPreferences?.keyPreview ?: PopupViewStyle( AppPreference.qwerty_key_preview_popup_size_scale_percent ?: DEFAULT_SIZE, AppPreference.qwerty_key_preview_popup_text_size_sp ?: DEFAULT_QWERTY_PREVIEW_TEXT ), defaultTextSize = DEFAULT_QWERTY_PREVIEW_TEXT, onChanged = { - AppPreference.qwerty_key_preview_popup_size_scale_percent = it.sizeScalePercent - AppPreference.qwerty_key_preview_popup_text_size_sp = it.textSizeSp + if (customPreferences != null) customPreferences.keyPreview = it else { + AppPreference.qwerty_key_preview_popup_size_scale_percent = it.sizeScalePercent + AppPreference.qwerty_key_preview_popup_text_size_sp = it.textSizeSp + } } ) ) - root.addView(sectionTitle("Long-press variation popup")) + root.addView(sectionTitle(getString(R.string.qwerty_long_press_popup_section))) root.addView( styleEditorSection( preview = PopupStylePreviewView(requireContext()).apply { previewText = "á" }, - initialStyle = PopupViewStyle( + initialStyle = customPreferences?.variation ?: PopupViewStyle( AppPreference.qwerty_variation_popup_size_scale_percent ?: DEFAULT_SIZE, AppPreference.qwerty_variation_popup_text_size_sp ?: DEFAULT_QWERTY_VARIATION_TEXT ), defaultTextSize = DEFAULT_QWERTY_VARIATION_TEXT, onChanged = { - AppPreference.qwerty_variation_popup_size_scale_percent = it.sizeScalePercent - AppPreference.qwerty_variation_popup_text_size_sp = it.textSizeSp + if (customPreferences != null) customPreferences.variation = it else { + AppPreference.qwerty_variation_popup_size_scale_percent = it.sizeScalePercent + AppPreference.qwerty_variation_popup_text_size_sp = it.textSizeSp + } } ) ) @@ -146,6 +164,10 @@ class QwertyPopupStyleSettingFragment : Fragment() { } } +class CustomQwertyPopupStyleSettingFragment : QwertyPopupStyleSettingFragment() { + override val useCustomKeyboardSettings = true +} + class FlickKeyboardPopupStyleListFragment : Fragment() { override fun onCreateView( diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/CustomKeyboardPreferenceFragment.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/CustomKeyboardPreferenceFragment.kt index f88f20d87..bb8ff2e80 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/CustomKeyboardPreferenceFragment.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/CustomKeyboardPreferenceFragment.kt @@ -34,7 +34,7 @@ class CustomKeyboardPreferenceFragment : AsyncPreferenceFragment() { } findPreference("custom_qwerty_popup_style")?.setOnPreferenceClickListener { - navigateSafely(R.id.qwertyPopupStyleSettingFragment) + navigateSafely(R.id.customQwertyPopupStyleSettingFragment) true } applyLegacySearchResultFilterIfNeeded() diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/FrequentSettingFilters.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/FrequentSettingFilters.kt index 932245ea3..9eb8bdf79 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/FrequentSettingFilters.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/FrequentSettingFilters.kt @@ -89,6 +89,7 @@ internal object FrequentSettingFilters { R.id.qwertyMarginSettingFragment, R.id.qwertyNumberKeyFlickSettingFragment, R.id.qwertyPopupStyleSettingFragment, + R.id.customQwertyPopupStyleSettingFragment, R.id.flickKeyboardPopupStyleListFragment, R.id.flickKeyboardSizeSettingsFragment, R.id.circularFlickSettingsFragment, diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt index 389153ee8..7ccad22d1 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt @@ -911,6 +911,7 @@ object SettingDestinations { "tenkey_popup_view_style_preference" -> R.id.tenKeyPopupStyleSettingFragment "qwerty_button_size_preference" -> R.id.qwertyMarginSettingFragment "qwerty_popup_view_style_preference" -> R.id.qwertyPopupStyleSettingFragment + "custom_qwerty_popup_style" -> R.id.customQwertyPopupStyleSettingFragment "qwerty_number_key_flick_setting_preference" -> R.id.qwertyNumberKeyFlickSettingFragment "sumire_keyboard_size_preference" -> R.id.flickKeyboardSizeSettingsFragment "custom_keyboard_size_preference" -> R.id.flickKeyboardSizeSettingsFragment diff --git a/app/src/main/res/navigation/mobile_navigation.xml b/app/src/main/res/navigation/mobile_navigation.xml index 69170e94e..37b4bbfef 100644 --- a/app/src/main/res/navigation/mobile_navigation.xml +++ b/app/src/main/res/navigation/mobile_navigation.xml @@ -502,6 +502,10 @@ android:id="@+id/qwertyPopupStyleSettingFragment" android:name="com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.popup_style.QwertyPopupStyleSettingFragment" android:label="@string/qwerty_popup_view_style_preference_title" /> + %1$d 行 %2$d 列 QWERTY 型キーの押下プレビューを表示 押したキーの文字を拡大表示します。長押し候補は表示設定にかかわらず選択できます。 - QWERTY 型ポップアップの表示 - 標準 QWERTY とサイズ・文字設定を共用します + QWERTY 型キー・ポップアップのサイズ + 標準 QWERTY とは別に、カスタム QWERTY のタップ・長押しポップアップの大きさと文字サイズを設定します + 通常のキーサイズ + 通常のキーと文字の大きさは、カスタムキーボードのキーサイズ設定を使用します。 + カスタムキーボードの QWERTY 型キーに適用します。すべてのスキンで、タップ時と長押し時の大きさ・文字サイズを個別に変更できます。 + タップ時の拡大ポップアップ + 長押し候補のポップアップ キーのプレビュー 長押し候補のプレビュー キーボードの表示 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 11ef17dff..b13f587e2 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2007,8 +2007,13 @@ ABC abc 0123456789 ABC 12345 Row %1$d, column %2$d Show QWERTY key previews Enlarge the pressed key text. Long-press alternatives remain available. - QWERTY popup appearance - Share size and text settings with the standard QWERTY keyboard + QWERTY key and popup sizes + Set custom QWERTY tap and long-press popup sizes and text sizes independently of standard QWERTY + Normal key size + Normal key and text sizes use the custom keyboard key size settings. + Applies to QWERTY-type keys in custom keyboards. Popup size and text size can be adjusted separately for taps and long presses, with any skin. + Tap preview popup + Long-press alternatives popup Key preview Long-press candidate preview On the keyboard diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/CustomQwertyPopupPreferencesTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/CustomQwertyPopupPreferencesTest.kt new file mode 100644 index 000000000..cbdb02eac --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/CustomQwertyPopupPreferencesTest.kt @@ -0,0 +1,90 @@ +package com.kazumaproject.markdownhelperkeyboard.setting_activity + +import android.content.Context +import androidx.preference.PreferenceManager +import androidx.test.core.app.ApplicationProvider +import com.kazumaproject.core.data.popup.PopupViewStyle +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.SettingDestinationType +import com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.SettingDestinations +import com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.SettingSearchIndex +import org.junit.Assert.* +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 = [35]) +class CustomQwertyPopupPreferencesTest { + private val context = ApplicationProvider.getApplicationContext() + private val preferences = PreferenceManager.getDefaultSharedPreferences(context) + + @Before fun clear() { + AppPreference.init(context) + preferences.edit().clear().commit() + } + + @Test fun migrationSnapshotsSharedSettingsAndBothSurfacesRemainIndependent() { + preferences.edit() + .putInt("qwerty_key_preview_popup_size_scale_percent_preference", 125) + .putFloat("qwerty_key_preview_popup_text_size_sp_preference", 23f) + .putInt("qwerty_variation_popup_size_scale_percent_preference", 160) + .putFloat("qwerty_variation_popup_text_size_sp_preference", 35f).commit() + AppPreference.init(context) + val custom = AppPreference.custom_qwerty_popup_preferences + assertEquals(PopupViewStyle(125, 23f), custom.keyPreview) + assertEquals(PopupViewStyle(160, 35f), custom.variation) + AppPreference.qwerty_key_preview_popup_size_scale_percent = 200 + AppPreference.qwerty_variation_popup_text_size_sp = 48f + CustomQwertyPopupPreferences.migrate(preferences) + assertEquals(PopupViewStyle(125, 23f), custom.keyPreview) + assertEquals(PopupViewStyle(160, 35f), custom.variation) + custom.keyPreview = PopupViewStyle(80, 18f) + assertEquals(PopupViewStyle(160, 35f), custom.variation) + assertEquals(200, AppPreference.qwerty_key_preview_popup_size_scale_percent) + custom.variation = PopupViewStyle(140, 32f) + assertEquals(48f, AppPreference.qwerty_variation_popup_text_size_sp) + assertEquals(PopupViewStyle(80, 18f), CustomQwertyPopupPreferences(preferences).keyPreview) + } + + @Test fun defaultsBoundsAndPartialMigrationPreserveExistingCustomValues() { + val custom = CustomQwertyPopupPreferences(preferences) + assertEquals(PopupViewStyle(100, 28f), custom.keyPreview) + assertEquals(PopupViewStyle(100, 28f), custom.variation) + custom.keyPreview = PopupViewStyle(1, 99f) + custom.variation = PopupViewStyle(999, 1f) + assertEquals(PopupViewStyle(50, 48f), custom.keyPreview) + assertEquals(PopupViewStyle(200, 8f), custom.variation) + preferences.edit().remove(CustomQwertyPopupPreferences.VARIATION_SIZE) + .putInt("qwerty_variation_popup_size_scale_percent_preference", 120).commit() + CustomQwertyPopupPreferences.migrate(preferences) + assertEquals(PopupViewStyle(50, 48f), custom.keyPreview) + assertEquals(PopupViewStyle(120, 8f), custom.variation) + } + + @Test fun backupRoundTripAndLegacyRestoreKeepTheIndependentSettings() { + AppPreference.init(context) + val custom = AppPreference.custom_qwerty_popup_preferences + custom.keyPreview = PopupViewStyle(80, 18f) + custom.variation = PopupViewStyle(140, 32f) + val backup = AppPreference.exportAllToJson() + AppPreference.importAllFromJson(backup) + assertEquals(PopupViewStyle(80, 18f), custom.keyPreview) + assertEquals(PopupViewStyle(140, 32f), custom.variation) + AppPreference.importAllFromJson("""{"version":1,"entries":[{"key":"qwerty_key_preview_popup_size_scale_percent_preference","type":"int","value":150}]}""") + assertEquals(PopupViewStyle(150, 28f), custom.keyPreview) + assertEquals(PopupViewStyle(100, 28f), custom.variation) + } + + @Test fun bothSettingsInterfacesExposeCustomPopupSettings() { + AppPreference.init(context) + val modern = SettingSearchIndex.searchable(context).single { it.key == "custom_qwerty_popup_style" } + assertTrue(modern.destination is SettingDestinationType.NavDestination) + assertEquals(R.id.customQwertyPopupStyleSettingFragment, SettingDestinations.destinationId(modern.destination)) + val legacy = SettingSearchIndex.legacySearchable(context).single { it.key == "custom_qwerty_popup_style" } + assertEquals(R.xml.pref_custom, legacy.legacyTarget!!.xmlRes) + assertEquals(R.id.customKeyboardPreferenceFragment, legacy.legacyTarget!!.destinationId) + } +} diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/QwertyKeyInputController.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/QwertyKeyInputController.kt index 565ccf236..9dcd04830 100644 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/QwertyKeyInputController.kt +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/QwertyKeyInputController.kt @@ -134,7 +134,6 @@ class QwertyKeyInputController( ellipsize = android.text.TextUtils.TruncateAt.END setTextColor(style.textColor ?: skin?.palette?.text ?: ContextCompat.getColor(context, com.kazumaproject.core.R.color.keyboard_icon_color)) - setTextSize(TypedValue.COMPLEX_UNIT_SP, style.textSizeSp) val location = IntArray(2).also(key::getLocationOnScreen) val geometry = skin?.keyPreview(resources, key.width, key.height, location[0], resources.displayMetrics.widthPixels, key.top > 0) @@ -143,6 +142,7 @@ class QwertyKeyInputController( style.backgroundColor?.let { backgroundTintList = ColorStateList.valueOf(it) } } skin?.configurePreviewText(this) + setTextSize(TypedValue.COMPLEX_UNIT_SP, style.textSizeSp) setPadding(paddingLeft, (6 * resources.displayMetrics.density).toInt(), paddingRight, paddingBottom) } KeyboardFontApplicator.apply(content, fontProvider()) @@ -190,14 +190,15 @@ class QwertyKeyInputController( val previewGeometry = if (choosing) null else KeyboardSkinRegistry.find(style.skinId)?.keyPreview( key.resources, key.width, key.height, location[0], size.x, key.top > 0) val width = if (choosing) (48 * density * scale * layer.columns).toInt() else - previewGeometry?.width ?: (key.width * 2 * scale).toInt() + ((previewGeometry?.width ?: (key.width * 2)) * scale).toInt() val height = if (choosing) (56 * density * scale * layer.rowCount).toInt() else - previewGeometry?.height ?: ((key.height * 2 + 64) * scale).toInt() + ((previewGeometry?.height ?: (key.height * 2 + 64)) * scale).toInt() val w = width.coerceIn(1, viewport.width().coerceAtLeast(1)) val h = height.coerceIn(1, viewport.height().coerceAtLeast(1)) - val desiredX = location[0] + (previewGeometry?.xOffset ?: (key.width / 2 - w / 2)) + val desiredX = location[0] + (previewGeometry?.let { it.xOffset + (it.width - w) / 2 } + ?: (key.width / 2 - w / 2)) val desiredY = if (choosing) location[1] - h else - location[1] + key.height + (previewGeometry?.yOffset ?: -h) + location[1] + key.height + (previewGeometry?.let { it.yOffset + it.height - h } ?: -h) val x = desiredX.coerceIn(viewport.left, viewport.right - w) val y = desiredY.coerceIn(viewport.top, viewport.bottom - h) val bounds = Rect(x, y, x + w, y + h) diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/controller/QwertyKeyInputControllerTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/controller/QwertyKeyInputControllerTest.kt index e5bb3e102..8ee96ab01 100644 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/controller/QwertyKeyInputControllerTest.kt +++ b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/controller/QwertyKeyInputControllerTest.kt @@ -5,11 +5,13 @@ import android.os.Looper import android.view.MotionEvent import android.widget.Button import android.widget.FrameLayout +import android.widget.TextView import com.kazumaproject.core.data.popup.PopupViewStyle import com.kazumaproject.core.data.popup.QwertyPopupViewStyleSet import com.kazumaproject.core.domain.flick.GestureSessionConfig import com.kazumaproject.core.domain.flick.GestureSessionConfigSource import com.kazumaproject.core.ui.font.KeyboardFontSnapshot +import com.kazumaproject.core.domain.skin.KeyboardSkinId import com.kazumaproject.custom_keyboard.data.QwertyKeyLayer import com.kazumaproject.custom_keyboard.data.QwertyPopupSlot import org.junit.Assert.* @@ -24,6 +26,55 @@ import java.time.Duration @RunWith(RobolectricTestRunner::class) @Config(sdk = [35]) class QwertyKeyInputControllerTest { + @Test fun previewAndAlternativesScaleIndependentlyWithEverySkin() { + val activity = Robolectric.buildActivity(Activity::class.java).setup().get() + val root = FrameLayout(activity) + activity.setContentView(root) + activity.window.decorView.layout(0, 0, 320, 470) + root.layout(0, 0, 320, 470) + val key = Button(activity) + root.addView(key, FrameLayout.LayoutParams(48, 48)) + key.layout(120, 300, 168, 348) + try { + KeyboardSkinId.entries.forEach { skin -> + var styles = QwertyPopupViewStyleSet( + PopupViewStyle(100, 20f, skinId = skin), PopupViewStyle(100, 24f, skinId = skin)) + val controller = QwertyKeyInputController(GestureSessionConfigSource { + GestureSessionConfig(1L, 100, 20f, longPressTimeoutMillis = 300) + }, { QwertyKeyLayer("a", columns = 2, slots = listOf(QwertyPopupSlot("á"), QwertyPopupSlot("à"))) }, + { styles }, { KeyboardFontSnapshot() }, { true }, { null }, {}, {}) + controller.attach(key) + try { + key.send(MotionEvent.ACTION_DOWN) + val original = shadowOf(activity.application).latestPopupWindow + val width = original.width + val height = original.height + key.send(MotionEvent.ACTION_CANCEL) + styles = styles.copy(keyPreview = styles.keyPreview.copy(sizeScalePercent = 150, textSizeSp = 35f)) + key.send(MotionEvent.ACTION_DOWN) + val preview = shadowOf(activity.application).latestPopupWindow + assertEquals(skin.name, (width * 1.5f).toInt(), preview.width) + assertEquals(skin.name, (height * 1.5f).toInt(), preview.height) + assertEquals(35f * key.resources.displayMetrics.scaledDensity, + (preview.contentView as TextView).textSize, 0.1f) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350)) + val alternatives = shadowOf(activity.application).latestPopupWindow + val alternativesWidth = alternatives.width + val alternativesHeight = alternatives.height + key.send(MotionEvent.ACTION_CANCEL) + styles = styles.copy(variation = styles.variation.copy(sizeScalePercent = 75)) + key.send(MotionEvent.ACTION_DOWN) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350)) + val smaller = shadowOf(activity.application).latestPopupWindow + assertEquals((alternativesWidth * 0.75f).toInt(), smaller.width) + assertEquals((alternativesHeight * 0.75f).toInt(), smaller.height) + assertEquals(48, key.width) + assertEquals(48, key.height) + } finally { controller.cancel() } + } + } finally { activity.finish() } + } + @Test fun tapHoldCancelAndDisabledPreviewCommitOnlyTheirOwnText() { val activity = Robolectric.buildActivity(Activity::class.java).setup().get() val root = FrameLayout(activity) @@ -68,6 +119,6 @@ class QwertyKeyInputControllerTest { private fun Button.send(action: Int) { val now = android.os.SystemClock.uptimeMillis() - MotionEvent.obtain(now, now, action, 50f, 50f, 0).also { dispatchTouchEvent(it); it.recycle() } + MotionEvent.obtain(now, now, action, width / 2f, height / 2f, 0).also { dispatchTouchEvent(it); it.recycle() } } } From 385dbe2151b31019814a6f4f79a7e0f74386cc2a Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Fri, 13 Nov 2026 03:23:33 -0500 Subject: [PATCH 06/69] Add key-anchored popup map input and editor for Sumire --- .../SumirePopupEditorDeviceTest.kt | 108 ++++++ .../SumirePopupInputDeviceTest.kt | 210 ++++++++++++ .../ime_service/IMEService.kt | 23 +- .../setting_activity/MainActivity.kt | 6 + .../ui/setting/SettingDestination.kt | 2 + .../ui/setting/SumirePreferenceFragment.kt | 24 +- .../sumire_popup/PopupMapEditorCanvas.kt | 169 ++++++++++ .../sumire_popup/PopupMapEditorFragment.kt | 309 ++++++++++++++++++ .../sumire_popup/PopupMapEditorViewModel.kt | 46 +++ .../sumire_popup/SumirePopupRepository.kt | 31 ++ .../main/res/navigation/mobile_navigation.xml | 5 + .../res/values-ja/sumire_popup_strings.xml | 59 ++++ .../main/res/values/sumire_popup_strings.xml | 59 ++++ app/src/main/res/xml/pref_sumire.xml | 5 + .../sumire_popup/SumirePopupRepositoryTest.kt | 60 ++++ core/src/main/res/values-ja/arrays.xml | 2 + core/src/main/res/values/arrays.xml | 2 + .../controller/PopupMapInputController.kt | 133 ++++++++ .../custom_keyboard/data/KeyModels.kt | 3 +- .../custom_keyboard/data/PopupMap.kt | 129 ++++++++ .../layout/KeyboardDefaultLayouts.kt | 11 + .../custom_keyboard/view/FlickKeyboardView.kt | 18 + .../custom_keyboard/view/PopupMapView.kt | 51 +++ .../custom_keyboard/data/PopupMapTest.kt | 82 +++++ 24 files changed, 1544 insertions(+), 3 deletions(-) create mode 100644 app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumirePopupEditorDeviceTest.kt create mode 100644 app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumirePopupInputDeviceTest.kt create mode 100644 app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvas.kt create mode 100644 app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorFragment.kt create mode 100644 app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorViewModel.kt create mode 100644 app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/SumirePopupRepository.kt create mode 100644 app/src/main/res/values-ja/sumire_popup_strings.xml create mode 100644 app/src/main/res/values/sumire_popup_strings.xml create mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/SumirePopupRepositoryTest.kt create mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/PopupMapInputController.kt create mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/PopupMap.kt create mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/PopupMapView.kt create mode 100644 custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/PopupMapTest.kt diff --git a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumirePopupEditorDeviceTest.kt b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumirePopupEditorDeviceTest.kt new file mode 100644 index 000000000..194889879 --- /dev/null +++ b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumirePopupEditorDeviceTest.kt @@ -0,0 +1,108 @@ +package com.kazumaproject.markdownhelperkeyboard + +import android.content.Intent +import android.os.SystemClock +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.widget.Spinner +import android.widget.EditText +import android.widget.TextView +import androidx.navigation.fragment.NavHostFragment +import androidx.preference.Preference +import androidx.preference.PreferenceManager +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry +import androidx.test.runner.lifecycle.Stage +import com.google.android.material.button.MaterialButton +import com.google.android.material.textfield.TextInputEditText +import com.kazumaproject.custom_keyboard.data.* +import com.kazumaproject.markdownhelperkeyboard.setting_activity.MainActivity +import com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.SumirePreferenceFragment +import com.kazumaproject.markdownhelperkeyboard.sumire_popup.* +import org.junit.Assert.* +import org.junit.Assume.assumeTrue +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class SumirePopupEditorDeviceTest { + private val ins=InstrumentationRegistry.getInstrumentation() + private val context get()=ins.targetContext + private fun activity()=ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).filterIsInstance().firstOrNull() + private fun nav()=(activity()?.supportFragmentManager?.findFragmentById(R.id.nav_host_fragment_activity_main) as? NavHostFragment) + private fun descendants(view: View): List = listOf(view)+if(view is ViewGroup) (0 until view.childCount).flatMap {descendants(view.getChildAt(it))} else emptyList() + private fun views()=activity()?.window?.decorView?.let(::descendants).orEmpty() + private fun canvas()=views().filterIsInstance().firstOrNull() + private fun await(test: ()->Boolean) { + val until=SystemClock.uptimeMillis()+20000 + while(SystemClock.uptimeMillis()(R.id.setting_search_input).setText(context.getString(R.string.popup_editor_entry))} + await {views().filterIsInstance().any {it !is EditText && it.isShown && it.text.toString()==context.getString(R.string.popup_editor_entry)}} + ins.runOnMainSync { + var target: View?=views().filterIsInstance().first {it !is EditText && it.isShown && it.text.toString()==context.getString(R.string.popup_editor_entry)} + while(target!=null && !target.isClickable) target=target.parent as? View + assertTrue("Search result must open the editor",target?.performClick()==true) + } + } else { + await {nav()?.childFragmentManager?.primaryNavigationFragment is SumirePreferenceFragment} + ins.runOnMainSync {(nav()!!.childFragmentManager.primaryNavigationFragment as SumirePreferenceFragment).findPreference("sumire_popup_map_editor_preference")!!.performClick()} + } + await {canvas()!=null && canvas()!!.config!=null} + ins.runOnMainSync { + val input=views().filterIsInstance().single {it.contentDescription==context.getString(R.string.popup_input)} + input.setText(if(modern) "は★" else "は☆") + views().filterIsInstance().single {it.text==context.getString(R.string.popup_save)}.performClick() + } + assertEquals(if(modern) "は★" else "は☆",repository.load("は").map("normal")!!.tapText) + ins.runOnMainSync {activity()!!.finish()} + } + } + @Test fun popupTextDragConstraintsAndDraftSurviveRecreation() { + assumeTrue(context.packageName.endsWith(".popuptest")) + SumirePopupRepository(context).save(SumirePopupDefaults.create("は")) + ins.startActivitySync(Intent(context,MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + await {nav()?.navController?.currentDestination!=null} + ins.runOnMainSync {nav()!!.navController.navigate(R.id.popupMapEditorFragment)} + await {canvas()!=null && canvas()!!.width>0} + ins.runOnMainSync { + val c=canvas()!! + val mapSpinner=views().filterIsInstance()[1] + mapSpinner.setSelection(c.config!!.maps.indexOfFirst {it.id=="voiced"}) + } + await {canvas()?.map?.id=="voiced"} + ins.runOnMainSync { + val c=canvas()!! + fun touch(action: Int,x: Float,y: Float) {val event=MotionEvent.obtain(0,SystemClock.uptimeMillis(),action,c.originX+x*c.keyWidth,c.originY+y*c.keyHeight,0);c.dispatchTouchEvent(event);event.recycle()} + touch(MotionEvent.ACTION_DOWN,-1f,-.7f);touch(MotionEvent.ACTION_UP,-1f,-.7f) + views().filterIsInstance().single {it.contentDescription==context.getString(R.string.popup_input)}.setText("ありがとう") + touch(MotionEvent.ACTION_DOWN,-1f,-.7f);touch(MotionEvent.ACTION_MOVE,0f,0f);touch(MotionEvent.ACTION_UP,0f,0f) + assertTrue(PopupMapValidator.conflicts(c.config!!).isEmpty()) + assertFalse(c.selectedBounds!!.intersects(PopupBounds.KEY)) + activity()!!.recreate() + } + await {canvas()?.map?.id=="voiced" && canvas()!!.map!!.regions.any {it.action.text=="ありがとう"}} + ins.runOnMainSync { + views().filterIsInstance().single {it.text==context.getString(R.string.popup_save)}.performClick() + activity()!!.finish() + } + assertTrue(SumirePopupRepository(context).load("は").map("voiced")!!.regions.any {it.action.text=="ありがとう"}) + } +} diff --git a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumirePopupInputDeviceTest.kt b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumirePopupInputDeviceTest.kt new file mode 100644 index 000000000..312b8492c --- /dev/null +++ b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumirePopupInputDeviceTest.kt @@ -0,0 +1,210 @@ +package com.kazumaproject.markdownhelperkeyboard + +import android.accessibilityservice.AccessibilityServiceInfo +import android.content.Intent +import android.graphics.Matrix +import android.graphics.Rect +import android.os.ParcelFileDescriptor +import android.os.SystemClock +import android.view.InputDevice +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.view.ContextThemeWrapper +import android.widget.FrameLayout +import android.widget.TextView +import android.view.accessibility.AccessibilityNodeInfo +import android.view.inspector.WindowInspector +import androidx.preference.PreferenceManager +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry +import androidx.test.runner.lifecycle.Stage +import com.kazumaproject.custom_keyboard.data.* +import com.kazumaproject.custom_keyboard.controller.PopupMapInputController +import com.kazumaproject.custom_keyboard.view.PopupMapView +import com.kazumaproject.markdownhelperkeyboard.sumire_popup.SumirePopupRepository +import org.junit.Assert.* +import org.junit.Assume.assumeTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** Exercises the installed IME and real InputConnection, including popup screen coordinates. */ +@RunWith(AndroidJUnit4::class) +class SumirePopupInputDeviceTest { + private val ins=InstrumentationRegistry.getInstrumentation() + private val automation get()=ins.uiAutomation + private val context get()=ins.targetContext + private fun shell(command: String)=ParcelFileDescriptor.AutoCloseInputStream(automation.executeShellCommand(command)).bufferedReader().use {it.readText()} + @Test fun rotatedKeyUsesItsPhysicalCentreAndCancelKeepsItsLabel() { + assumeTrue(context.packageName.endsWith(".popuptest")) + val host=ins.startActivitySync(Intent(context,FastInputHostActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as FastInputHostActivity + lateinit var key: TextView + lateinit var controller: PopupMapInputController + var committed: String?=null + try { + ins.runOnMainSync { + val themed=ContextThemeWrapper(host,R.style.Theme_MarkdownKeyboard) + val frame=FrameLayout(themed) + key=TextView(themed).apply {text="は";rotation=30f} + frame.addView(key,FrameLayout.LayoutParams(200,100).apply {leftMargin=200;topMargin=500}) + host.setContentView(frame) + controller=PopupMapInputController(SumirePopupDefaults.create("は"),{null},{it},{},{_,_->},{text,_->committed=text},{}) + controller.attach(key) + } + await {key.width==200 && key.isAttachedToWindow} + ins.runOnMainSync { + fun touch(action: Int,x: Float,y: Float) { + val e=MotionEvent.obtain(0,SystemClock.uptimeMillis(),action,x,y,0) + key.dispatchTouchEvent(e);e.recycle() + } + touch(MotionEvent.ACTION_DOWN,100f,50f) + } + await {popup()?.width?.let {it>0}==true} + ins.runOnMainSync { + fun touch(action: Int,x: Float,y: Float) { + val e=MotionEvent.obtain(0,SystemClock.uptimeMillis(),action,x,y,0) + key.dispatchTouchEvent(e);e.recycle() + } + val drawing=popup()!! + val position=IntArray(2).also(drawing::getLocationOnScreen) + val centre=floatArrayOf(100f,50f) + val matrix=Matrix();key.transformMatrixToGlobal(matrix);matrix.mapPoints(centre) + assertEquals(centre[0],position[0]+drawing.originX,3f) + assertEquals(centre[1],position[1]+drawing.originY,3f) + assertEquals(30f,drawing.keyRotation,0f) + touch(MotionEvent.ACTION_MOVE,-100f,-20f) + touch(MotionEvent.ACTION_UP,-100f,-20f) + assertEquals("ひ",committed) + controller.cancel() + assertEquals("は",key.text.toString()) + committed=null + touch(MotionEvent.ACTION_DOWN,100f,50f) + key.layoutParams=key.layoutParams.apply {width=220} + } + await {key.width==220} + ins.runOnMainSync { + val up=MotionEvent.obtain(0,SystemClock.uptimeMillis(),MotionEvent.ACTION_UP,100f,50f,0) + key.dispatchTouchEvent(up);up.recycle() + assertNull("Relayout must cancel instead of committing at stale coordinates",committed) + assertEquals("は",key.text.toString()) + } + } finally {ins.runOnMainSync {host.finish()}} + } + @Test fun fixedKeyOriginTextMapSwitchImmediateTextAndBack() { + assumeTrue("Use an isolated debug application ID",context.packageName.endsWith(".popuptest")) + val target="${context.packageName}/com.kazumaproject.markdownhelperkeyboard.ime_service.IMEService" + val oldIme=shell("settings get secure default_input_method").trim() + val enabled=shell("ime list -s").lineSequence().any {it.trim()==target} + val floating=InstrumentationRegistry.getArguments().getString("surface","normal")=="floating" + val preferences=PreferenceManager.getDefaultSharedPreferences(context) + preferences.edit().clear() + .putString("keyboard_order_preference","[\"SUMIRE\"]") + .putBoolean("save_last_used_keyboard",false) + .putBoolean("gojuon_keyboard_type_migrated_v1",true) + .putString("sumire_input_method_preference",InstrumentationRegistry.getArguments().getString("inputStyle","flick")) + .putString("sumire_keyboard_style_preference",SumirePopupDefaults.STYLE) + .putBoolean("keyboard_floating_preference",floating) + .putBoolean("sumire_restore_input_mode_on_restart_preference",false) + .putBoolean("landscape_force_qwerty_preference",false) + .putBoolean("live_conversion_preference",false) + .putBoolean("learn_dictionary_preference",false) + .putBoolean("flick_editor_preview_preference",false) + .putBoolean("key_sound_preference",false).commit() + val original=SumirePopupDefaults.create("は") + val entry=original.map("normal")!!.regions.first {it.action.type==PopupActionType.SWITCH} + SumirePopupRepository(context).save(original.withMap(original.map("voiced")!!.let { page -> + page.copy(regions=page.regions.map { if (it.action.text=="び") it.copy(action=PopupAction(text="ありがとう")) else it }+PopupRegion("immediate",entry.bounds,PopupAction(text="★"))) + })) + automation.serviceInfo=automation.serviceInfo.apply {flags=flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS or AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS} + try { + shell("ime enable $target");shell("ime set $target") + shell("am start -n ${context.packageName}/${FastInputHostActivity::class.java.name}") + await {host()!=null} + if (InstrumentationRegistry.getArguments().getString("orientation")=="landscape") { + ins.runOnMainSync {host()!!.requestedOrientation=android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE} + await {host()?.resources?.configuration?.orientation==android.content.res.Configuration.ORIENTATION_LANDSCAPE} + SystemClock.sleep(300) + } + reset() + var key=findKey("は") + preferences.edit().putString("sumire_keyboard_style_preference", "default").commit() + SystemClock.sleep(200) + preferences.edit().putString("sumire_keyboard_style_preference", SumirePopupDefaults.STYLE).commit() + SystemClock.sleep(200) + val origins=mutableListOf>() + for(fraction in listOf(.15f,.85f)) { + reset();key=findKey("は") + val down=SystemClock.uptimeMillis() + inject(down,MotionEvent.ACTION_DOWN,key.left+key.width()*fraction,key.centerY().toFloat()) + await {popup()!=null} + ins.runOnMainSync { + val view=popup()!! + val xy=IntArray(2).also(view::getLocationOnScreen) + val origin=(xy[0]+view.originX).toInt() to (xy[1]+view.originY).toInt() + origins+=origin + assertEquals("Popup x must use the original key",key.centerX().toFloat(),origin.first.toFloat(),3f) + assertEquals("Popup y must use the original key",key.centerY().toFloat(),origin.second.toFloat(),3f) + } + inject(down,MotionEvent.ACTION_UP,key.left+key.width()*fraction,key.centerY().toFloat()) + awaitText("は") + } + assertEquals(origins[0],origins[1]) + reset();key=findKey("は") + gesture(key,listOf(-1f to -.7f));awaitText("ひ") + reset();key=findKey("は") + gesture(key,listOf(-1f to -2f,0f to 0f));awaitText("ば") + reset();key=findKey("は") + gesture(key,listOf(-1f to -2f));awaitText("★") + reset();key=findKey("は") + gesture(key,listOf(-1f to -2f,-1f to -.7f));awaitText("ありがとう") + reset();key=findKey("は") + gesture(key,listOf(-1f to -2f,0f to -3f,-1f to -.7f));awaitText("ひ") + reset();key=findKey("は") + gesture(key,listOf(1.6f to .6f));awaitText("") + } finally { + ins.runOnMainSync {host()?.let {it.requestedOrientation=android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;it.finish()}} + if(oldIme.isNotBlank() && oldIme!="null") shell("ime set $oldIme") + if(!enabled) shell("ime disable $target") + } + } + private fun host()=ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).filterIsInstance().firstOrNull() + private fun reset() {ins.runOnMainSync {host()!!.restartEditorInput(true)};SystemClock.sleep(250)} + private fun awaitText(value: String) {await {host()?.editText?.text?.toString()==value}} + private fun await(test: ()->Boolean) { + val end=SystemClock.uptimeMillis()+20000 + while(SystemClock.uptimeMillis() = listOf(view)+if(view is ViewGroup) (0 until view.childCount).flatMap {descendants(view.getChildAt(it))} else emptyList() + private fun popup()=WindowInspector.getGlobalWindowViews().flatMap(::descendants).filterIsInstance().firstOrNull() + private fun findKey(label: String): Rect { + val end=SystemClock.uptimeMillis()+20000 + while(SystemClock.uptimeMillis()() + fun visit(node: AccessibilityNodeInfo) {nodes+=node;repeat(node.childCount) {node.getChild(it)?.let(::visit)}} + automation.windows.forEach {it.root?.let(::visit)} + nodes.firstOrNull {it.packageName?.toString()==context.packageName && it.isVisibleToUser && it.isClickable && (it.text?.toString()?.lineSequence()?.firstOrNull()?.trim()==label || it.contentDescription?.toString()==label)}?.let { + val bounds=Rect().also(it::getBoundsInScreen) + if(!bounds.isEmpty) return bounds + } + SystemClock.sleep(50) + } + error("Key $label not found") + } + private fun inject(down: Long,action: Int,x: Float,y: Float) { + val event=MotionEvent.obtain(down,SystemClock.uptimeMillis(),action,x,y,0).apply {source=InputDevice.SOURCE_TOUCHSCREEN} + check(automation.injectInputEvent(event,true));event.recycle();SystemClock.sleep(60) + } + private fun gesture(key: Rect,points: List>) { + val down=SystemClock.uptimeMillis() + inject(down,MotionEvent.ACTION_DOWN,key.centerX().toFloat(),key.centerY().toFloat()) + points.forEach {(x,y)->inject(down,MotionEvent.ACTION_MOVE,key.centerX()+x*key.width(),key.centerY()+y*key.height())} + val last=points.last();inject(down,MotionEvent.ACTION_UP,key.centerX()+last.first*key.width(),key.centerY()+last.second*key.height()) + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt index 261a1bb53..941ba796c 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt @@ -31,6 +31,7 @@ import com.kazumaproject.core.domain.flick.FlickTextPreviewEvent import com.kazumaproject.markdownhelperkeyboard.ime_service.floating_dictionary.FloatingDictionaryStore import com.kazumaproject.morse_keyboard.* import com.kazumaproject.markdownhelperkeyboard.morse.MorsePreferences +import com.kazumaproject.custom_keyboard.data.copyWithKeys import android.annotation.SuppressLint import android.Manifest import android.content.ClipDescription @@ -1134,6 +1135,16 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, applyZenzaiDraftPreference(AppVariantConfig.hasZenz && appPreference.enable_zenzai_preference) } } + if (key == "sumire_keyboard_style_preference" || key == "sumire_input_method_preference") { + runOnMainThread { + sumireInputStyle = appPreference.sumire_keyboard_style + sumireInputKeyLayoutType = appPreference.sumire_input_method + refreshSumireLayouts(hiraganaOnly = false) + } + } + if (key == null || key.startsWith(com.kazumaproject.markdownhelperkeyboard.sumire_popup.SumirePopupRepository.PREFIX)) { + runOnMainThread { refreshSumireLayouts(hiraganaOnly = true) } + } if (key != null && key in runtimeInputPreferenceKeys) { runOnMainThread { syncRuntimeInputPreferences() @@ -11343,6 +11354,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } } + private val sumirePopupRepository by lazy { + com.kazumaproject.markdownhelperkeyboard.sumire_popup.SumirePopupRepository(this) + } + private fun createSumireKeyboardLayout(): KeyboardLayout = createSumireKeyboardLayout(customKeyboardMode) @@ -11366,7 +11381,13 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, highlightSelectedMode = sumireModeKeyHighlight ), mode - ).let { baseLayout -> + ).let { popupLayout -> + if (popupLayout.keys.none { it.popupMapConfig != null }) popupLayout else { + popupLayout.copyWithKeys(popupLayout.keys.map { key -> + key.popupMapConfig?.let { key.copy(popupMapConfig = sumirePopupRepository.load(it.keyId)) } ?: key + }) + } + }.let { baseLayout -> SumireSpecialKeyActionDisplayOverrideApplier.apply( layout = baseLayout, layoutType = layoutType, diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/MainActivity.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/MainActivity.kt index bf3df1d37..8e5d030bf 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/MainActivity.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/MainActivity.kt @@ -82,6 +82,7 @@ class MainActivity : AppCompatActivity() { } private val destinationsWithoutBottomNavigation = setOf( + R.id.popupMapEditorFragment, R.id.candidateViewHeightSettingFragment, R.id.candidateHeightLandscapeSettingFragment, R.id.candidateHeightDefaultsFragment, @@ -305,6 +306,11 @@ class MainActivity : AppCompatActivity() { override fun onSupportNavigateUp(): Boolean { if (!isSettingsContentReady) return super.onSupportNavigateUp() val navController = currentNavController() + val current = (supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as? androidx.navigation.fragment.NavHostFragment)?.childFragmentManager?.primaryNavigationFragment + if (current is com.kazumaproject.markdownhelperkeyboard.sumire_popup.PopupMapEditorFragment) { + current.leaveEditor() + return true + } return navController.navigateUp() || super.onSupportNavigateUp() } diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt index 389153ee8..9de6d9e9e 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt @@ -126,6 +126,7 @@ object SettingDestinations { "ng_word_preference", "physical_keyboard_shortcut_setting_preference", "sumire_special_key_editor_preference", + "sumire_popup_map_editor_preference", "morse_maps", "morse_key_layout", "gemma_prompt_template_management_preference", @@ -918,6 +919,7 @@ object SettingDestinations { "sumire_custom_angle_preference" -> R.id.circularFlickSettingsFragment "circular_slot_action_setting_preference" -> R.id.circularSlotActionSettingFragment "sumire_special_key_editor_preference" -> R.id.sumireSpecialKeyEditorFragment + "sumire_popup_map_editor_preference" -> R.id.popupMapEditorFragment "physical_keyboard_shortcut_setting_preference" -> R.id.physicalKeyboardShortcutListFragment else -> null } diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SumirePreferenceFragment.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SumirePreferenceFragment.kt index e9346ad11..93ea88f0f 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SumirePreferenceFragment.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SumirePreferenceFragment.kt @@ -51,6 +51,23 @@ class SumirePreferenceFragment : AsyncPreferenceFragment() { return value == "second-flick" } + fun updatePopupSettings(style: String?) { + val free = style == com.kazumaproject.custom_keyboard.data.SumirePopupDefaults.STYLE + listOf("sumire_show_flick_popup_preference", "sumire_show_long_press_popup_preference").forEach { key -> + findPreference(key)?.apply { + isEnabled = !free + summary = if (free) getString(R.string.popup_only_kana) else null + } + } + findPreference("sumire_input_method_preference")?.let { method -> + method.summary = if (free) getString(R.string.popup_method_scope, method.entry) else method.entry + } + } + findPreference("sumire_popup_map_editor_preference")?.setOnPreferenceClickListener { + navigateSafely(R.id.popupMapEditorFragment) + true + } + sumireStylePreference?.apply { if (value == "third-flick") { summary = getString(com.kazumaproject.core.R.string.three_stage_flick_suspended) @@ -69,6 +86,7 @@ class SumirePreferenceFragment : AsyncPreferenceFragment() { setOnPreferenceChangeListener { preference, newValue -> val stringValue = newValue as String + updatePopupSettings(stringValue) val listPreference = preference as ListPreference val index = listPreference.findIndexOfValue(stringValue) @@ -98,12 +116,16 @@ class SumirePreferenceFragment : AsyncPreferenceFragment() { val listPreference = preference as ListPreference val index = listPreference.findIndexOfValue(newValue as String) if (index >= 0) { - preference.summary = listPreference.entries[index].toString() + preference.summary = if (sumireStylePreference?.value == com.kazumaproject.custom_keyboard.data.SumirePopupDefaults.STYLE) { + getString(R.string.popup_method_scope, listPreference.entries[index]) + } else listPreference.entries[index].toString() } true } } + updatePopupSettings(sumireStylePreference?.value) + sumireKeyboardSizePreference?.apply { setOnPreferenceClickListener { navigateSafely(R.id.flickKeyboardSizeSettingsFragment, Bundle().apply { putString("sizingSurface", "sumire") }) diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvas.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvas.kt new file mode 100644 index 000000000..210504e19 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvas.kt @@ -0,0 +1,169 @@ +package com.kazumaproject.markdownhelperkeyboard.sumire_popup + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Canvas +import android.graphics.DashPathEffect +import android.graphics.Paint +import android.graphics.RectF +import android.view.MotionEvent +import android.view.ViewConfiguration +import com.google.android.material.R +import com.google.android.material.color.MaterialColors +import com.kazumaproject.custom_keyboard.data.* +import com.kazumaproject.custom_keyboard.view.PopupMapView +import kotlin.math.ceil +import kotlin.math.hypot + +@SuppressLint("ClickableViewAccessibility") +class PopupMapEditorCanvas(context: Context) : PopupMapView(context) { + var config: PopupKeyConfig? = null + var mapId = "normal" + var tapSelected = true + var trying = false + var onSelect: (String?) -> Unit = {} + var onChange: (PopupKeyConfig) -> Unit = {} + var onBlocked: (PopupConflict?) -> Unit = {} + var onTrial: (String?, PopupMapSession) -> Unit = { _, _ -> } + private val pen = Paint(Paint.ANTI_ALIAS_FLAG) + private var startX = 0f + private var startY = 0f + private var original: PopupRegion? = null + private var resizeCorner = -1 + private var dragging = false + private var ghost: PopupBounds? = null + private var trial: PopupMapSession? = null + private var beforeDrag: PopupKeyConfig? = null + val selectedBounds get() = map?.regions?.firstOrNull { it.id == selectedId }?.bounds + + fun showConfig(value: PopupKeyConfig, pageId: String, selection: String?, test: Boolean) { + config = value; mapId = pageId; map = value.map(pageId) + selectedId = selection; tapSelected = selection == null; trying = test + if (!test) trial = null + invalidate() + } + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + keyWidth = minOf(w / 3.65f, 100 * resources.displayMetrics.density) + keyHeight = minOf(h / 5.2f, 64 * resources.displayMetrics.density) + originX = w / 2f; originY = h - keyHeight * 1.6f + } + private fun rect(b: PopupBounds) = RectF(originX+b.left*keyWidth,originY+b.top*keyHeight,originX+b.right*keyWidth,originY+b.bottom*keyHeight) + private fun inViewport(b: PopupBounds): Boolean { + val r=rect(b); val margin=4*resources.displayMetrics.density + return r.left>=margin && r.top>=margin && r.right<=width-margin && r.bottom<=height-margin + } + fun canPlace(value: PopupKeyConfig, bounds: PopupBounds): Boolean = inViewport(bounds) && PopupMapValidator.conflicts(value).isEmpty() + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val primary=MaterialColors.getColor(this,androidx.appcompat.R.attr.colorPrimary) + val foreground=MaterialColors.getColor(this,R.attr.colorOnSurface) + pen.style=Paint.Style.FILL + pen.color=MaterialColors.getColor(this,if(tapSelected) R.attr.colorPrimaryContainer else R.attr.colorSurfaceContainerHigh) + val key=rect(PopupBounds.KEY) + canvas.drawRoundRect(key,10f,10f,pen) + pen.style=Paint.Style.STROKE;pen.strokeWidth=if(tapSelected) 3*resources.displayMetrics.density else resources.displayMetrics.density + pen.color=if(tapSelected) primary else MaterialColors.getColor(this,R.attr.colorOutline) + canvas.drawRoundRect(key,10f,10f,pen) + pen.style=Paint.Style.FILL;pen.color=foreground;pen.textAlign=Paint.Align.CENTER;pen.textSize=24*resources.displayMetrics.scaledDensity + val tap=map?.tapText.orEmpty().ifEmpty { "—" } + val text=android.text.TextUtils.ellipsize(tap,android.text.TextPaint(pen),key.width()-12,android.text.TextUtils.TruncateAt.END).toString() + canvas.drawText(text,key.centerX(),key.centerY()-(pen.ascent()+pen.descent())/2,pen) + if (!trying) { + config?.maps?.forEach { source -> source.regions.filter { it.action.type==PopupActionType.SWITCH && it.action.targetMapId==mapId }.forEach { + pen.style=Paint.Style.STROKE;pen.strokeWidth=resources.displayMetrics.density + pen.color=MaterialColors.getColor(this,R.attr.colorTertiary);pen.pathEffect=DashPathEffect(floatArrayOf(8f,6f),0f) + canvas.drawRect(rect(it.bounds),pen);pen.pathEffect=null + } } + selectedBounds?.let { b -> + val r=rect(b);pen.style=Paint.Style.FILL;pen.color=primary + listOf(r.left to r.top,r.right to r.top,r.left to r.bottom,r.right to r.bottom).forEach { canvas.drawCircle(it.first,it.second,5*resources.displayMetrics.density,pen) } + } + ghost?.let { pen.style=Paint.Style.STROKE;pen.color=MaterialColors.getColor(this,androidx.appcompat.R.attr.colorError);pen.strokeWidth=2*resources.displayMetrics.density;pen.pathEffect=DashPathEffect(floatArrayOf(10f,6f),0f);canvas.drawRect(rect(it),pen);pen.pathEffect=null } + } + contentDescription="${config?.keyId} / ${map?.name} / ${map?.tapText}" + } + override fun performClick(): Boolean { super.performClick(); return true } + override fun onTouchEvent(event: MotionEvent): Boolean { + val value=config ?: return false + val x=(event.x-originX)/keyWidth;val y=(event.y-originY)/keyHeight + if (trying) { + when(event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + if (x !in -.5f.. .5f || y !in -.5f.. .5f) return true + parent.requestDisallowInterceptTouchEvent(true) + trial=PopupMapSession(value,keyWidth,keyHeight) + } + MotionEvent.ACTION_MOVE -> trial?.let { active -> + for(i in 0 until event.historySize) active.move((event.getHistoricalX(i)-originX)/keyWidth,(event.getHistoricalY(i)-originY)/keyHeight) + active.move(x,y) + } + MotionEvent.ACTION_UP -> trial?.let { active -> + val output=active.release(x,y);onTrial(output,active) + trial=null;parent.requestDisallowInterceptTouchEvent(false) + } + MotionEvent.ACTION_CANCEL -> {trial=null;parent.requestDisallowInterceptTouchEvent(false)} + } + trial?.let { map=it.currentMap;selectedId=it.selectedRegionId;tapSelected=it.isTap;onTrial(null,it) } + if(trial==null) {map=value.map(mapId);selectedId=null;tapSelected=true} + invalidate();return true + } + when(event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + startX=event.x;startY=event.y;dragging=false;ghost=null + val corner=selectedBounds?.let { b -> + val r=rect(b) + val corners=listOf(r.left to r.top,r.right to r.top,r.left to r.bottom,r.right to r.bottom) + corners.indices.minByOrNull { i -> hypot(event.x-corners[i].first,event.y-corners[i].second) }?.takeIf { i -> hypot(event.x-corners[i].first,event.y-corners[i].second)<24*resources.displayMetrics.density } + } ?: -1 + val hit=if(corner>=0) map?.regions?.firstOrNull { it.id==selectedId } else map?.regions?.firstOrNull { it.bounds.contains(x,y,keyWidth,keyHeight) } + original=hit;beforeDrag=value;resizeCorner=corner + selectedId=hit?.id;tapSelected=hit==null;onSelect(selectedId) + parent.requestDisallowInterceptTouchEvent(true);invalidate();return true + } + MotionEvent.ACTION_MOVE -> { + val source=original ?: return true + if(!dragging && hypot(event.x-startX,event.y-startY) b.copy(left=(b.left+dx).coerceAtMost(b.right-.35f),top=(b.top+dy).coerceAtMost(b.bottom-.35f)) + 1 -> b.copy(right=(b.right+dx).coerceAtLeast(b.left+.35f),top=(b.top+dy).coerceAtMost(b.bottom-.35f)) + 2 -> b.copy(left=(b.left+dx).coerceAtMost(b.right-.35f),bottom=(b.bottom+dy).coerceAtLeast(b.top+.35f)) + 3 -> b.copy(right=(b.right+dx).coerceAtLeast(b.left+.35f),bottom=(b.bottom+dy).coerceAtLeast(b.top+.35f)) + else -> b.offset(dx,dy) + } + val current=selectedBounds ?: source.bounds + val distance=maxOf(kotlin.math.abs(desired.left-current.left),kotlin.math.abs(desired.top-current.top),kotlin.math.abs(desired.right-current.right),kotlin.math.abs(desired.bottom-current.bottom)) + val steps=ceil(distance*keyWidth/2).toInt().coerceIn(1,512) + var accepted=current + var blocked=false + var collision: PopupConflict?=null + for(i in 1..steps) { + val t=i.toFloat()/steps + val b=PopupBounds(current.left+(desired.left-current.left)*t,current.top+(desired.top-current.top)*t,current.right+(desired.right-current.right)*t,current.bottom+(desired.bottom-current.bottom)*t) + val page=config!!.map(mapId)!! + val candidate=config!!.withMap(page.copy(regions=page.regions.map { if(it.id==source.id) it.copy(bounds=b) else it })) + collision=PopupMapValidator.conflicts(candidate).firstOrNull() + if(!inViewport(b) || collision!=null) {blocked=true;break} + accepted=b + } + val page=config!!.map(mapId)!! + config=config!!.withMap(page.copy(regions=page.regions.map { if(it.id==source.id) it.copy(bounds=accepted) else it })) + map=config!!.map(mapId);ghost=if(blocked) desired else null + if(blocked) onBlocked(collision) + invalidate();return true + } + MotionEvent.ACTION_UP -> { + performClick();parent.requestDisallowInterceptTouchEvent(false) + if(dragging && config!=beforeDrag) onChange(config!!) + original=null;ghost=null;invalidate();return true + } + MotionEvent.ACTION_CANCEL -> { + beforeDrag?.let { config=it;map=it.map(mapId) };original=null;ghost=null + parent.requestDisallowInterceptTouchEvent(false);invalidate();return true + } + } + return true + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorFragment.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorFragment.kt new file mode 100644 index 000000000..f838b0910 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorFragment.kt @@ -0,0 +1,309 @@ +package com.kazumaproject.markdownhelperkeyboard.sumire_popup + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.* +import androidx.activity.OnBackPressedCallback +import androidx.core.widget.NestedScrollView +import androidx.core.widget.doAfterTextChanged +import androidx.fragment.app.Fragment +import androidx.fragment.app.viewModels +import androidx.navigation.fragment.findNavController +import com.google.android.material.button.MaterialButton +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.google.android.material.textfield.TextInputEditText +import com.google.android.material.textfield.TextInputLayout +import com.kazumaproject.custom_keyboard.data.* +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference +import java.util.UUID + +class PopupMapEditorFragment : Fragment() { + private val model: PopupMapEditorViewModel by viewModels() + private lateinit var repository: SumirePopupRepository + private lateinit var content: LinearLayout + private lateinit var properties: LinearLayout + private lateinit var canvas: PopupMapEditorCanvas + private lateinit var status: TextView + private lateinit var output: TextView + private lateinit var mapSpinner: Spinner + private lateinit var keySpinner: Spinner + private lateinit var breadcrumb: TextView + private lateinit var sourceButton: MaterialButton + private lateinit var editButton: MaterialButton + private lateinit var tryButton: MaterialButton + private var bindingSelectors = false + private var result = "" + private val config get() = requireNotNull(model.config) + private val page get() = requireNotNull(config.map(model.mapId)) + private fun id() = UUID.randomUUID().toString() + private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt() + private fun label(id: Int) = getString(id) + private fun column() = LinearLayout(requireContext()).apply { orientation=LinearLayout.VERTICAL } + private fun row() = LinearLayout(requireContext()).apply { orientation=LinearLayout.HORIZONTAL;gravity=android.view.Gravity.CENTER_VERTICAL } + private fun text(value: String) = TextView(requireContext()).apply { text=value;setPadding(0,dp(6),0,dp(6));textSize=14f } + private fun button(title: String, action: () -> Unit) = MaterialButton(requireContext(),null,com.google.android.material.R.attr.materialButtonOutlinedStyle).apply { text=title;setOnClickListener { action() } } + private fun LinearLayout.item(view: View, weight: Float=0f) { addView(view,LinearLayout.LayoutParams(if(weight>0) 0 else ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,weight)) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + repository=SumirePopupRepository(requireContext()) + if(model.config==null) model.load(repository.load("は")) + content=column().apply {setPadding(dp(16),dp(8),dp(16),dp(24))} + val scroll=NestedScrollView(requireContext()).apply {isFillViewport=true;addView(content)} + if(AppPreference.sumire_keyboard_style!=SumirePopupDefaults.STYLE) content.addView(text(label(R.string.popup_inactive))) + breadcrumb=text("") + sourceButton=button(label(R.string.popup_back_editor)) { goSource() } + content.addView(row().apply { + item(breadcrumb,1f) + item(sourceButton) + item(button(label(R.string.popup_save)) { save() }) + }) + keySpinner=Spinner(requireContext()) + mapSpinner=Spinner(requireContext()) + content.addView(row().apply { + item(text(label(R.string.popup_key)));item(keySpinner,1f) + item(text(label(R.string.popup_map)));item(mapSpinner,1f) + }) + editButton=button(label(R.string.popup_edit)) {model.trying=false;refresh()}.apply {isCheckable=true} + tryButton=button(label(R.string.popup_try)) {model.trying=true;model.selectedId=null;refresh()}.apply {isCheckable=true} + content.addView(row().apply { + item(editButton,1f);item(tryButton,1f) + item(button(label(R.string.popup_add_map)) {newMap()},1.25f) + item(button("⋮") {showMapMenu(null)}.apply {minWidth=dp(40);minimumWidth=dp(40);setPadding(dp(8),0,dp(8),0)},.45f) + }) + canvas=PopupMapEditorCanvas(requireContext()).apply { + onSelect={ selected -> model.selectedId=selected; showProperties() } + onChange={ changed -> model.change(changed);refreshCanvas();showProperties() } + onBlocked={ conflict -> status.text=conflictMessage(conflict) } + onTrial={ entered, session -> + if(entered!=null) result+=entered + output.text="${label(R.string.popup_result)}:$result" + status.text=session.mapPath.joinToString(" → ") { this@PopupMapEditorFragment.config.map(it)?.name.orEmpty() } + " " + session.selectedText.orEmpty() + } + } + content.addView(canvas,LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,dp(240))) + status=text("");content.addView(status) + output=text("");content.addView(output) + properties=column();content.addView(properties) + content.addView(row().apply { + item(button(label(R.string.popup_add)) { addPopup() },1f) + item(button(label(R.string.popup_undo)) { model.undo();refresh() },1f) + }) + installSelectors() + refresh() + return scroll + } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,object:OnBackPressedCallback(true) { + override fun handleOnBackPressed() { leaveEditor() } + }) + } + private fun adapter(items: List) = ArrayAdapter(requireContext(),android.R.layout.simple_spinner_dropdown_item,items) + private fun installSelectors() { + keySpinner.adapter=adapter(SumirePopupDefaults.rows.keys.toList()) + keySpinner.setSelection(SumirePopupDefaults.rows.keys.indexOf(config.keyId)) + keySpinner.onItemSelectedListener=object:AdapterView.OnItemSelectedListener { + override fun onNothingSelected(parent: AdapterView<*>?) {} + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, rowId: Long) { + val key=SumirePopupDefaults.rows.keys.elementAt(position) + if(bindingSelectors || key==config.keyId) return + guardUnsaved({model.load(repository.load(key));refresh()}) + keySpinner.setSelection(SumirePopupDefaults.rows.keys.indexOf(config.keyId)) + } + } + mapSpinner.onItemSelectedListener=object:AdapterView.OnItemSelectedListener { + override fun onNothingSelected(parent: AdapterView<*>?) {} + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, rowId: Long) { + if(bindingSelectors || position !in config.maps.indices || config.maps[position].id==model.mapId) return + model.mapId=config.maps[position].id;model.path=arrayListOf();model.selectedId=null;refresh() + } + } + } + private fun refresh() { + bindingSelectors=true + if(config.map(model.mapId)==null) model.mapId=config.startMapId + keySpinner.setSelection(SumirePopupDefaults.rows.keys.indexOf(config.keyId)) + mapSpinner.adapter=adapter(config.maps.map { it.name });mapSpinner.setSelection(config.maps.indexOfFirst { it.id==model.mapId }) + bindingSelectors=false + sourceButton.visibility=if(model.path.isEmpty()) View.GONE else View.VISIBLE + editButton.isChecked=!model.trying + tryButton.isChecked=model.trying + breadcrumb.text=(listOf(config.keyId)+model.path.mapNotNull { config.map(it)?.name }+page.name).joinToString(" / ") + status.text=when { + repository.hasInvalidSavedConfig(config.keyId) -> label(R.string.popup_invalid_saved) + model.trying -> label(R.string.popup_try_hint) + config.maps.any { source -> source.regions.any { it.action.type==PopupActionType.SWITCH && it.action.targetMapId==model.mapId } } -> label(R.string.popup_transition_hint) + else -> label(R.string.popup_hint) + } + output.text="${label(R.string.popup_result)}:$result";output.visibility=if(model.trying) View.VISIBLE else View.GONE + refreshCanvas();showProperties() + } + private fun refreshCanvas() { canvas.showConfig(config,if(model.trying) config.startMapId else model.mapId,model.selectedId,model.trying) } + private fun change(value: PopupKeyConfig, refreshFields: Boolean=false): Boolean { + val conflicts=PopupMapValidator.conflicts(value) + if(conflicts.isNotEmpty()) { + status.text=conflictMessage(conflicts.first()) + Toast.makeText(requireContext(),status.text,Toast.LENGTH_LONG).show() + return false + } + model.change(value);refreshCanvas() + if(refreshFields) refresh() + return true + } + private fun conflictMessage(conflict: PopupConflict?): String { + if(conflict==null) return label(R.string.popup_collision) + if(conflict.type==PopupConflictType.KEY) return getString(R.string.popup_collision_detail,label(R.string.popup_tap),config.keyId) + val map=config.map(conflict.otherMapId ?: conflict.mapId) + val region=map?.regions?.firstOrNull {it.id==(conflict.otherRegionId ?: conflict.regionId)} + return getString(R.string.popup_collision_detail,map?.name.orEmpty(),region?.displayLabel().orEmpty()) + } + private fun field(title: String, value: String, callback: (String) -> Unit): TextInputEditText { + val input=TextInputEditText(requireContext()).apply {setText(value);textSize=16f;setSingleLine(false);contentDescription=title} + properties.addView(TextInputLayout(requireContext()).apply { hint=title;addView(input);setPadding(0,dp(5),0,dp(5)) }) + input.doAfterTextChanged { callback(it?.toString().orEmpty()) } + return input + } + private fun showProperties() { + properties.removeAllViews() + if(model.trying) { + properties.addView(button(label(R.string.popup_reset_trial)) {result="";output.text="${label(R.string.popup_result)}:"}) + return + } + val selected=page.regions.firstOrNull { it.id==model.selectedId } + if(selected==null) { + properties.addView(text("${label(R.string.popup_selection)}:${label(R.string.popup_tap)}")) + properties.addView(text(label(R.string.popup_fixed))) + field(label(R.string.popup_input),page.tapText) { value -> change(config.withMap(page.copy(tapText=value))) } + return + } + val selectedHeading=text("") + fun updateHeading() { + val current=page.regions.firstOrNull {it.id==selected.id} + selectedHeading.text="${label(R.string.popup_selection)}:${current?.displayLabel()?.ifEmpty {label(R.string.popup_unset)}}" + } + properties.addView(selectedHeading) + updateHeading() + field(label(R.string.popup_label),selected.label) { value -> updateRegion(selected.id) {it.copy(label=value)};updateHeading() } + properties.addView(text(label(R.string.popup_action))) + val actions=listOf(label(R.string.popup_text),label(R.string.popup_switch),label(R.string.popup_back)) + val action=Spinner(requireContext()).apply {adapter=adapter(actions);setSelection(selected.action.type.ordinal)} + properties.addView(action) + action.onItemSelectedListener=object:AdapterView.OnItemSelectedListener { + override fun onNothingSelected(parent: AdapterView<*>?) {} + override fun onItemSelected(parent: AdapterView<*>?,view: View?,position: Int,rowId: Long) { + val current=page.regions.firstOrNull {it.id==selected.id} ?: return + val type=PopupActionType.entries[position] + if(type==current.action.type) return + val target=if(type==PopupActionType.SWITCH) config.maps.firstOrNull {it.id!=page.id}?.id else null + if(type==PopupActionType.SWITCH && target==null) { newMap(page.id,current.id);return } + updateRegion(current.id,true) {it.copy(action=PopupAction(type,current.action.text,target))} + showProperties() + } + } + when(selected.action.type) { + PopupActionType.TEXT -> field(label(R.string.popup_input),selected.action.text) { value ->updateRegion(selected.id) {it.copy(action=it.action.copy(text=value))};updateHeading() } + PopupActionType.SWITCH -> { + properties.addView(text(label(R.string.popup_target))) + val maps=config.maps.filter {it.id!=page.id} + val target=Spinner(requireContext()).apply {adapter=adapter(maps.map {it.name});setSelection(maps.indexOfFirst {it.id==selected.action.targetMapId}.coerceAtLeast(0))} + properties.addView(target) + target.onItemSelectedListener=object:AdapterView.OnItemSelectedListener { + override fun onNothingSelected(parent: AdapterView<*>?) {} + override fun onItemSelected(parent: AdapterView<*>?,view: View?,position: Int,rowId: Long) { + val current=page.regions.firstOrNull {it.id==selected.id} ?: return + val targetId=maps.getOrNull(position)?.id ?: return + if(current.action.targetMapId!=targetId && !updateRegion(current.id) {it.copy(action=it.action.copy(targetMapId=targetId))}) showProperties() + } + } + properties.addView(button(label(R.string.popup_new_map)) {newMap(page.id,selected.id)}) + properties.addView(button(label(R.string.popup_edit_target)) { selected.action.targetMapId?.let { openMap(it) } }) + } + PopupActionType.BACK -> properties.addView(text(label(R.string.popup_back))) + } + properties.addView(button(label(R.string.popup_delete)) {change(config.withMap(page.copy(regions=page.regions.filterNot {it.id==selected.id})),true);model.selectedId=null;showProperties()}) + } + private fun updateRegion(regionId: String, redraw: Boolean=false, transform: (PopupRegion)->PopupRegion): Boolean = change(config.withMap(page.copy(regions=page.regions.map {if(it.id==regionId) transform(it) else it})),redraw) + private fun openMap(mapId: String) {model.path=ArrayList(model.path+model.mapId);model.mapId=mapId;model.selectedId=null;refresh()} + private fun goSource() { + val source=model.path.lastOrNull() ?: return + model.path=ArrayList(model.path.dropLast(1));model.mapId=source;model.selectedId=null;refresh() + } + private fun addPopup() { + if(model.trying) {model.trying=false;refresh()} + val regionId=id() + for(y in listOf(-3.6f,-2.6f,-1.6f,-.6f,.6f)) for(x in listOf(-1.5f,-.4f,.7f)) { + val region=PopupRegion(regionId,PopupBounds(x,y,x+.8f,y+.8f)) + val updated=config.withMap(page.copy(regions=page.regions+region)) + if(canvas.canPlace(updated,region.bounds)) {model.change(updated);model.selectedId=regionId;refresh();return} + } + status.text=label(R.string.popup_no_space) + } + private fun newMap(sourceMapId: String?=null, sourceRegionId: String?=null) { + val layout=column().apply {setPadding(dp(24),0,dp(24),0)} + val name=TextInputEditText(requireContext()).apply {hint=label(R.string.popup_name);setText(label(R.string.popup_new_map)+" ${config.maps.size+1}")} + layout.addView(name) + val choices=RadioGroup(requireContext()) + val blank=RadioButton(requireContext()).apply {id=View.generateViewId();text=label(R.string.popup_blank)} + val copy=RadioButton(requireContext()).apply {id=View.generateViewId();text=label(R.string.popup_copy)} + choices.addView(blank);choices.addView(copy);choices.check(if(sourceMapId==null) copy.id else blank.id);layout.addView(choices) + val dialog=MaterialAlertDialogBuilder(requireContext()).setTitle(R.string.popup_new_map).setView(layout).setNegativeButton(R.string.popup_cancel,null).setPositiveButton(R.string.popup_create,null).create() + dialog.setOnShowListener {dialog.getButton(-1).setOnClickListener { + val title=name.text.toString().trim() + if(title.isEmpty() || config.maps.any {it.name==title}) {name.error=label(R.string.popup_name_required);return@setOnClickListener} + val new=if(choices.checkedRadioButtonId==copy.id) page.copy(id=id(),name=title,regions=page.regions.map {it.copy(id=id())}) else PopupMap(id(),title,"") + var updated=config.copy(maps=config.maps+new) + var linked=true + if(sourceMapId!=null && sourceRegionId!=null) { + val source=updated.map(sourceMapId)!! + val connected=updated.withMap(source.copy(regions=source.regions.map { if(it.id==sourceRegionId) it.copy(action=PopupAction(PopupActionType.SWITCH,targetMapId=new.id)) else it })) + if(PopupMapValidator.conflicts(connected).isEmpty()) updated=connected else linked=false + } + if(change(updated)) { + dialog.dismiss();openMap(new.id) + if(!linked) status.text=label(R.string.popup_created_unlinked) + } + }} + dialog.show() + } + private fun showMapMenu(it: View?) { + val menu=PopupMenu(requireContext(),it ?: mapSpinner) + listOf(R.string.popup_rename,R.string.popup_duplicate,R.string.popup_delete).forEach { resource -> menu.menu.add(0,resource,0,resource) } + menu.setOnMenuItemClickListener { item -> + when(item.itemId) { + R.string.popup_rename -> renameMap() + R.string.popup_duplicate -> newMap() + R.string.popup_delete -> deleteMap() + };true + };menu.show() + } + private fun renameMap() { + val input=TextInputEditText(requireContext()).apply {setText(page.name)} + val dialog=MaterialAlertDialogBuilder(requireContext()).setTitle(R.string.popup_rename).setView(input).setNegativeButton(R.string.popup_cancel,null).setPositiveButton(R.string.popup_apply,null).create() + dialog.setOnShowListener {dialog.getButton(-1).setOnClickListener { + val name=input.text.toString().trim() + if(name.isEmpty() || config.maps.any {it.id!=page.id && it.name==name}) input.error=label(R.string.popup_name_required) + else {change(config.withMap(page.copy(name=name)),true);dialog.dismiss()} + }};dialog.show() + } + private fun deleteMap() { + if(page.id==config.startMapId) {Toast.makeText(requireContext(),R.string.popup_start_delete,Toast.LENGTH_LONG).show();return} + val references=config.maps.flatMap { source -> source.regions.filter {it.action.type==PopupActionType.SWITCH && it.action.targetMapId==page.id}.map {"${source.name} / ${it.displayLabel()}"} } + if(references.isNotEmpty()) {MaterialAlertDialogBuilder(requireContext()).setMessage(label(R.string.popup_used)+"\n\n"+references.joinToString("\n")).setPositiveButton(android.R.string.ok,null).show();return} + MaterialAlertDialogBuilder(requireContext()).setMessage(R.string.popup_delete_confirm).setNegativeButton(R.string.popup_cancel,null).setPositiveButton(R.string.popup_delete) {_,_-> + model.change(config.copy(maps=config.maps.filterNot {it.id==page.id}));model.mapId=config.startMapId;model.path=arrayListOf();model.selectedId=null;refresh() + }.show() + } + private fun save(): Boolean { + return runCatching {repository.save(config);model.markSaved();status.text=label(R.string.popup_saved);true}.getOrElse {status.text=label(R.string.popup_collision);false} + } + fun leaveEditor() {guardUnsaved {findNavController().popBackStack()} } + private fun guardUnsaved(next: ()->Unit) { + if(!model.dirty) {next();return} + MaterialAlertDialogBuilder(requireContext()).setTitle(R.string.popup_unsaved) + .setPositiveButton(R.string.popup_save) {_,_->if(save()) next()} + .setNegativeButton(R.string.popup_discard) {_,_->next()} + .setNeutralButton(R.string.popup_cancel,null).show() + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorViewModel.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorViewModel.kt new file mode 100644 index 000000000..3c3b83426 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorViewModel.kt @@ -0,0 +1,46 @@ +package com.kazumaproject.markdownhelperkeyboard.sumire_popup + +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import com.google.gson.Gson +import com.kazumaproject.custom_keyboard.data.PopupKeyConfig + +class PopupMapEditorViewModel(private val state: SavedStateHandle) : ViewModel() { + private val gson = Gson() + var config: PopupKeyConfig? = state.get("draft")?.let { gson.fromJson(it, PopupKeyConfig::class.java) } + private set + var mapId: String + get() = state["map"] ?: config?.startMapId.orEmpty() + set(value) { state["map"] = value } + var selectedId: String? + get() = state["selected"] + set(value) { state["selected"] = value } + var trying: Boolean + get() = state["trying"] ?: false + set(value) { state["trying"] = value } + var path: ArrayList + get() = state["path"] ?: arrayListOf() + set(value) { state["path"] = value } + private var undo: ArrayList + get() = state["undo"] ?: arrayListOf() + set(value) { state["undo"] = value } + val dirty get() = config != null && gson.toJson(config) != state.get("baseline") + fun load(value: PopupKeyConfig) { + config = value; state["draft"] = gson.toJson(value); state["baseline"] = gson.toJson(value) + mapId = value.startMapId; selectedId = null; path = arrayListOf(); undo = arrayListOf(); trying = false + } + fun change(value: PopupKeyConfig) { + if (value == config) return + undo = ArrayList((undo + gson.toJson(config)).takeLast(50)) + config = value; state["draft"] = gson.toJson(value) + } + fun markSaved() { state["baseline"] = gson.toJson(config) } + fun undo(): Boolean { + val previous = undo.lastOrNull() ?: return false + undo = ArrayList(undo.dropLast(1)) + config = gson.fromJson(previous, PopupKeyConfig::class.java); state["draft"] = previous + if (config?.map(mapId) == null) mapId = config!!.startMapId + selectedId = selectedId?.takeIf { id -> config!!.map(mapId)!!.regions.any { it.id == id } } + return true + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/SumirePopupRepository.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/SumirePopupRepository.kt new file mode 100644 index 000000000..9b43dccaf --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/SumirePopupRepository.kt @@ -0,0 +1,31 @@ +package com.kazumaproject.markdownhelperkeyboard.sumire_popup + +import android.content.Context +import androidx.preference.PreferenceManager +import com.google.gson.Gson +import com.kazumaproject.custom_keyboard.data.PopupKeyConfig +import com.kazumaproject.custom_keyboard.data.PopupMapValidator +import com.kazumaproject.custom_keyboard.data.SumirePopupDefaults + +/** One atomic value per key; included in the existing preferences backup. */ +class SumirePopupRepository(context: Context) { + private val preferences = PreferenceManager.getDefaultSharedPreferences(context.applicationContext) + private val gson = Gson() + fun load(key: String): PopupKeyConfig = decode(preferences.getString(PREFIX + key, null), key) + fun hasInvalidSavedConfig(key: String): Boolean { + val json = preferences.getString(PREFIX + key, null) ?: return false + return runCatching { val value = gson.fromJson(json, PopupKeyConfig::class.java); value.keyId == key && PopupMapValidator.conflicts(value).isEmpty() }.getOrDefault(false).not() + } + fun save(config: PopupKeyConfig) { + require(config.keyId in SumirePopupDefaults.rows) + require(PopupMapValidator.conflicts(config).isEmpty()) + preferences.edit().putString(PREFIX + config.keyId, gson.toJson(config)).apply() + } + fun encode(config: PopupKeyConfig): String = gson.toJson(config) + fun decode(json: String?, key: String): PopupKeyConfig = runCatching { + val config = gson.fromJson(json, PopupKeyConfig::class.java) + require(config.keyId == key && PopupMapValidator.conflicts(config).isEmpty()) + config + }.getOrElse { SumirePopupDefaults.create(key) } + companion object { const val PREFIX = "sumire_popup_maps_v1_" } +} diff --git a/app/src/main/res/navigation/mobile_navigation.xml b/app/src/main/res/navigation/mobile_navigation.xml index 69170e94e..a7993ecc5 100644 --- a/app/src/main/res/navigation/mobile_navigation.xml +++ b/app/src/main/res/navigation/mobile_navigation.xml @@ -252,6 +252,11 @@ android:name="com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.QwertyRomajiPreferenceFragment" android:label="@string/qwerty_romaji_category_title" /> + + + + popupマップ編集 + 自由配置popup入力 + popupマップを編集 + 日本語かなキーのタップ・文字popup・マップ切替を編集します + この設定は「自由配置popup入力」で使用します。編集だけでは入力スタイルは変わりません。 + 対象キー + マップ + 編集 + 試す + 保存 + 保存しました + タップ(キー内) + キー全体・位置と大きさは固定 + 入力する文字 + 表示名 + 動作 + 文字入力 + 別マップへ切替 + 前のマップへ戻る + + popup追加 + + マップ + 新しいマップ + マップ名 + 空から作る + 現在のマップを複製 + 作成して編集 + 切替先 + 切替先を編集 + 切替元へ + 名前を変更 + 複製 + 削除 + 取り消す + 適用 + キャンセル + 未設定 + popupを追加して、動作と文字を設定してください。 + キーやpopupを選択。枠をドラッグして移動、角をドラッグしてサイズ変更。 + ここには配置できません。枠・キーとの重なり、または切替直後の操作枠が競合しています。 + 点線の範囲:切替直後に指が入る場所です。文字popupのみ配置できます。 + 空き領域がありません。既存のpopupを移動・縮小してください。 + 次のpopupがこのマップを使用しています。切替先を変更するか、そのpopupを削除してから削除してください。 + 開始マップは削除できません。 + 変更を保存しますか? + 破棄 + 入力結果 + 選択中 + キー内から試してください。切替枠に入るとマップ切替、文字の枠で離すと入力します。 + 保存された設定を読み込めないため初期配置を表示しています。保存済みデータは上書きしていません。 + このマップを削除しますか? + 重複しないマップ名を入力してください。 + 日本語かなキーが対象です。この方式では入力に使うpopupを表示します。 + 入力結果を消去 + %1$s / %2$s と競合するため、ここには配置できません。 + マップを作成しました。切替元と操作枠が競合するため、配置を調整してから切替先に指定してください。 + %1$s(英字・数字用)。日本語かなキーは枠を選び、指を離すと入力します。 + diff --git a/app/src/main/res/values/sumire_popup_strings.xml b/app/src/main/res/values/sumire_popup_strings.xml new file mode 100644 index 000000000..19a533ef2 --- /dev/null +++ b/app/src/main/res/values/sumire_popup_strings.xml @@ -0,0 +1,59 @@ + + + Popup map editor + Custom popup input + Edit popup maps + Edit tap text, popup regions and map transitions for Japanese kana keys + These maps are used when Custom popup input is selected. Editing does not change the input style. + Starting key + Map + Edit + Try + Save + Saved + Tap (inside key) + Entire key · fixed position and size + Text to enter + Display label + Action + Enter text + Switch to another map + Return to previous map + + Add popup + + Map + New map + Map name + Start empty + Copy current map + Create and edit + Destination map + Edit destination + Back to source + Rename + Duplicate + Delete + Undo + Apply + Cancel + Not assigned + Add a popup, then choose its action and text. + Select a key or popup. Drag a popup to move it; drag a corner to resize. + Cannot place here: overlaps a popup, the key, or a control after a transition. + Dashed areas: only text popups can appear here after a transition. + No free space. Move or resize an existing popup first. + This map is used by the following popups. Change their destinations or remove them before deleting this map. + The starting map cannot be deleted. + Save changes? + Discard + Output + Selection + Start inside the key. Enter a control to switch maps; release in a text region to enter text. + Saved maps could not be loaded. Showing defaults; the stored data has not been replaced. + Delete this map? + Enter a unique map name. + Japanese kana keys only. Popup regions are displayed while using this style. + Clear output + Cannot place here: conflicts with %1$s / %2$s. + Map created. Its controls conflict with the source popup; adjust them, then select this map as the destination. + %1$s for English and numbers. Japanese kana uses popup regions and release to enter text. + diff --git a/app/src/main/res/xml/pref_sumire.xml b/app/src/main/res/xml/pref_sumire.xml index aa0450673..15d16a2e7 100644 --- a/app/src/main/res/xml/pref_sumire.xml +++ b/app/src/main/res/xml/pref_sumire.xml @@ -69,6 +69,11 @@ android:summary="%s" android:title="@string/sumire_keyboard_style_title" /> + + () + private val preferences=PreferenceManager.getDefaultSharedPreferences(context) + private val repository=SumirePopupRepository(context) + @Before fun setup() {preferences.edit().clear().commit();AppPreference.init(context)} + @Test fun keysAndMapsPersistIndependentlyAndSurviveBackup() { + val initial=repository.load("は") + val edited=initial.withMap(initial.map("voiced")!!.copy(tapText="ありがとう")) + repository.save(edited) + assertEquals(edited,SumirePopupRepository(context).load("は")) + assertEquals(SumirePopupDefaults.create("か"),repository.load("か")) + val backup=AppPreference.exportAllToJson() + preferences.edit().clear().commit() + AppPreference.importAllFromJson(backup) + assertEquals(edited,repository.load("は")) + } + @Test fun malformedOrDanglingDataIsNotExecutedOrSilentlyOverwritten() { + val key=SumirePopupRepository.PREFIX+"は" + preferences.edit().putString(key,"{broken").commit() + assertTrue(repository.hasInvalidSavedConfig("は")) + assertEquals(SumirePopupDefaults.create("は"),repository.load("は")) + assertEquals("{broken",preferences.getString(key,null)) + val original=SumirePopupDefaults.create("は") + val invalid=original.copy(maps=original.maps.filterNot {it.id=="voiced"}) + assertThrows(IllegalArgumentException::class.java) {repository.save(invalid)} + } + @Test fun draftAndUndoSurviveViewModelRecreationWithoutChangingSavedConfiguration() { + val handle=SavedStateHandle() + val first=PopupMapEditorViewModel(handle) + first.load(repository.load("は")) + first.mapId="voiced" + val edited=first.config!!.withMap(first.config!!.map("voiced")!!.copy(tapText="★")) + first.change(edited) + val restored=PopupMapEditorViewModel(handle) + assertEquals("voiced",restored.mapId) + assertEquals("★",restored.config!!.map("voiced")!!.tapText) + assertTrue(restored.dirty) + assertEquals("ば",repository.load("は").map("voiced")!!.tapText) + assertTrue(restored.undo()) + assertEquals("ば",restored.config!!.map("voiced")!!.tapText) + assertFalse(restored.dirty) + } +} diff --git a/core/src/main/res/values-ja/arrays.xml b/core/src/main/res/values-ja/arrays.xml index 1f3004956..e14bb0929 100644 --- a/core/src/main/res/values-ja/arrays.xml +++ b/core/src/main/res/values-ja/arrays.xml @@ -30,6 +30,7 @@ 2段フリック入力 中央開始ポインターフリック入力 ドーナツ入力 + 自由配置popup入力 @@ -38,6 +39,7 @@ second-flick center-guide-flick sumire + free-popup diff --git a/core/src/main/res/values/arrays.xml b/core/src/main/res/values/arrays.xml index f698a4a20..bafd7e99e 100644 --- a/core/src/main/res/values/arrays.xml +++ b/core/src/main/res/values/arrays.xml @@ -32,6 +32,7 @@ Two-step flick input Center-start pointer flick input Donuts input + Custom popup input @@ -40,6 +41,7 @@ second-flick center-guide-flick sumire + free-popup diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/PopupMapInputController.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/PopupMapInputController.kt new file mode 100644 index 000000000..ea8c63ee0 --- /dev/null +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/PopupMapInputController.kt @@ -0,0 +1,133 @@ +package com.kazumaproject.custom_keyboard.controller + +import android.annotation.SuppressLint +import android.graphics.Color +import android.graphics.drawable.ColorDrawable +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.widget.PopupWindow +import android.widget.TextView +import com.kazumaproject.custom_keyboard.data.PopupKeyConfig +import com.kazumaproject.custom_keyboard.data.PopupMapSession +import com.kazumaproject.custom_keyboard.view.PopupMapView +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.cos +import kotlin.math.sin + +class PopupMapInputController( + private val config: PopupKeyConfig, + private val windowAnchor: () -> View?, + private val transform: (String) -> String, + private val onPress: (String) -> Unit, + private val onSelection: (String?, Boolean) -> Unit, + private val onCommit: (String, Boolean) -> Unit, + private val onCancel: () -> Unit +) { + private var anchor: View? = null + private var session: PopupMapSession? = null + private var popup: PopupWindow? = null + private var content: PopupMapView? = null + private var originalLabel: CharSequence? = null + private var width = 1 + private var height = 1 + private var rotation = 0f + private val locationScratch = IntArray(2) + private var initialLeft = 0 + private var initialTop = 0 + private fun sameGeometry(view: View): Boolean { + view.getLocationOnScreen(locationScratch) + return view.width == width && view.height == height && view.rotation == rotation && + locationScratch[0] == initialLeft && locationScratch[1] == initialTop + } + + @SuppressLint("ClickableViewAccessibility") + fun attach(view: View) { + anchor = view + view.setOnTouchListener { _, event -> + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + if (event.x !in 0f..view.width.toFloat() || event.y !in 0f..view.height.toFloat()) return@setOnTouchListener false + width = view.width.coerceAtLeast(1); height = view.height.coerceAtLeast(1) + rotation = view.rotation + view.getLocationOnScreen(locationScratch) + initialLeft = locationScratch[0]; initialTop = locationScratch[1] + session = PopupMapSession(config, width.toFloat(), height.toFloat()) + originalLabel = (view as? TextView)?.text + view.isPressed = true + onPress(session!!.currentMap.tapText) + render() + true + } + MotionEvent.ACTION_MOVE -> { + val active = session ?: return@setOnTouchListener true + if (!sameGeometry(view)) { end(true); return@setOnTouchListener true } + for (i in 0 until event.historySize) active.move(event.getHistoricalX(i) / width - .5f, event.getHistoricalY(i) / height - .5f) + active.move(event.x / width - .5f, event.y / height - .5f) + onSelection(active.selectedText, !active.isTap) + render() + true + } + MotionEvent.ACTION_UP -> { + if (!sameGeometry(view)) { end(true); return@setOnTouchListener true } + val active = session + val output = active?.release(event.x / width - .5f, event.y / height - .5f) + val flick = active?.isTap == false + end(output == null) + if (output != null) onCommit(output, flick) + true + } + MotionEvent.ACTION_CANCEL -> { end(true); true } + else -> true + } + } + } + + private fun render() { + val key = anchor ?: return + val active = session ?: return + val host = windowAnchor() ?: key + if (!key.isAttachedToWindow || !host.isAttachedToWindow || host.windowToken == null) return + (key as? TextView)?.text = transform(active.currentMap.tapText) + val regions = active.currentMap.regions + if (regions.isEmpty()) { popup?.dismiss(); return } + val angle = Math.toRadians(rotation.toDouble()) + val cosine = cos(angle).toFloat() + val sine = sin(angle).toFloat() + val corners = regions.flatMap { region -> + val b = region.bounds + listOf(b.left to b.top, b.right to b.top, b.left to b.bottom, b.right to b.bottom).map { (x,y) -> + (x * width * cosine - y * height * sine) to (x * width * sine + y * height * cosine) + } + } + val left = floor(corners.minOf { it.first }).toInt() - 2 + val top = floor(corners.minOf { it.second }).toInt() - 2 + val right = ceil(corners.maxOf { it.first }).toInt() + 2 + val bottom = ceil(corners.maxOf { it.second }).toInt() + 2 + val drawing = content ?: PopupMapView(key.context).also { content = it } + drawing.map = active.currentMap; drawing.selectedId = active.selectedRegionId + drawing.keyWidth = width.toFloat(); drawing.keyHeight = height.toFloat(); drawing.keyRotation = rotation + drawing.originX = -left.toFloat(); drawing.originY = -top.toFloat(); drawing.textTransform = transform + val window = popup ?: PopupWindow(drawing, right-left, bottom-top, false).apply { + isTouchable = false; isOutsideTouchable = false; isClippingEnabled = false + setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) + }.also { popup = it } + val location = getLocationRelativeToWindowAnchor(key, host) + val x = location[0] + width / 2 + left + val y = location[1] + height / 2 + top + if (window.isShowing) window.update(x,y,right-left,bottom-top) else { + window.width = right-left; window.height = bottom-top + window.showAtLocation(host, Gravity.TOP or Gravity.LEFT, x, y) + } + drawing.invalidate() + } + private fun end(canceled: Boolean) { + popup?.dismiss() + anchor?.isPressed = false + if (session != null) (anchor as? TextView)?.text = originalLabel + if (canceled && session != null) onCancel() + session = null + } + fun cancel() { end(true) } +} diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyModels.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyModels.kt index 2bbe2d9c1..73df89d35 100644 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyModels.kt +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyModels.kt @@ -163,7 +163,8 @@ data class KeyData( val specialKeyColorStyle: SpecialKeyColorStyle = SpecialKeyColorStyle.SPECIAL, val doubleTapBinding: DoubleTapBinding? = null, val textInputBehavior: KeyTextInputBehavior = KeyTextInputBehavior.NORMAL, - val qwertyConfig: QwertyKeyConfig? = null + val qwertyConfig: QwertyKeyConfig? = null, + val popupMapConfig: PopupKeyConfig? = null ) data class GridPlacement( diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/PopupMap.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/PopupMap.kt new file mode 100644 index 000000000..770cbcff4 --- /dev/null +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/PopupMap.kt @@ -0,0 +1,129 @@ +package com.kazumaproject.custom_keyboard.data + +import androidx.annotation.Keep +import kotlin.math.abs +import kotlin.math.min + +/** Coordinates are key-width/key-height units relative to the original key's centre. */ +@Keep +data class PopupBounds(val left: Float, val top: Float, val right: Float, val bottom: Float) { + val width get() = right - left + val height get() = bottom - top + fun offset(dx: Float, dy: Float) = copy(left = left + dx, right = right + dx, top = top + dy, bottom = bottom + dy) + fun intersects(other: PopupBounds) = left < other.right && right > other.left && top < other.bottom && bottom > other.top + fun contains(x: Float, y: Float, keyWidth: Float = 1f, keyHeight: Float = 1f): Boolean { + if (x < left || x >= right || y < top || y >= bottom) return false + val radius = min(width * keyWidth, height * keyHeight) * .16f + val dx = ((abs(x - (left + right) / 2) - width / 2) * keyWidth + radius).coerceAtLeast(0f) + val dy = ((abs(y - (top + bottom) / 2) - height / 2) * keyHeight + radius).coerceAtLeast(0f) + return dx * dx + dy * dy <= radius * radius + } + companion object { val KEY = PopupBounds(-.5f, -.5f, .5f, .5f) } +} + +@Keep +enum class PopupActionType { TEXT, SWITCH, BACK } +@Keep +data class PopupAction(val type: PopupActionType = PopupActionType.TEXT, val text: String = "", val targetMapId: String? = null) +@Keep +data class PopupRegion(val id: String, val bounds: PopupBounds, val action: PopupAction = PopupAction(), val label: String = "") { + val isControl get() = action.type != PopupActionType.TEXT + fun displayLabel() = label.ifEmpty { + when (action.type) { PopupActionType.TEXT -> action.text; PopupActionType.SWITCH -> "↗"; PopupActionType.BACK -> "↶" } + } +} +@Keep +data class PopupMap(val id: String, val name: String, val tapText: String, val regions: List = emptyList()) +@Keep +data class PopupKeyConfig(val keyId: String, val startMapId: String, val maps: List, val version: Int = 1) { + fun map(id: String) = maps.firstOrNull { it.id == id } + fun withMap(map: PopupMap) = copy(maps = maps.map { if (it.id == map.id) map else it }) +} + +enum class PopupConflictType { INVALID, KEY, OVERLAP, TARGET, TRANSITION } +data class PopupConflict(val type: PopupConflictType, val mapId: String, val regionId: String? = null, val otherMapId: String? = null, val otherRegionId: String? = null) + +/** Used by the editor, persistence boundary and runtime; never a separate preview rule. */ +object PopupMapValidator { + fun conflicts(config: PopupKeyConfig): List { + val result = mutableListOf() + if (config.version != 1 || config.maps.isEmpty() || config.map(config.startMapId) == null || config.maps.map { it.id }.distinct().size != config.maps.size) { + return listOf(PopupConflict(PopupConflictType.INVALID, config.startMapId)) + } + val parents = config.maps.associate { target -> target.id to config.maps.filter { source -> source.regions.any { it.action.type == PopupActionType.SWITCH && it.action.targetMapId == target.id } } } + config.maps.forEach { map -> + if (map.regions.map { it.id }.distinct().size != map.regions.size) result += PopupConflict(PopupConflictType.INVALID, map.id) + map.regions.forEachIndexed { index, region -> + val b = region.bounds + if (listOf(b.left, b.top, b.right, b.bottom).any { !it.isFinite() } || b.width <= 0 || b.height <= 0) result += PopupConflict(PopupConflictType.INVALID, map.id, region.id) + if (b.intersects(PopupBounds.KEY)) result += PopupConflict(PopupConflictType.KEY, map.id, region.id) + map.regions.drop(index + 1).filter { b.intersects(it.bounds) }.forEach { result += PopupConflict(PopupConflictType.OVERLAP, map.id, region.id, map.id, it.id) } + if (!region.isControl) return@forEachIndexed + val destinations = when (region.action.type) { + PopupActionType.SWITCH -> listOfNotNull(config.map(region.action.targetMapId.orEmpty())) + PopupActionType.BACK -> parents[map.id].orEmpty() + else -> emptyList() + } + if (region.action.type == PopupActionType.SWITCH && (destinations.isEmpty() || region.action.targetMapId == map.id)) result += PopupConflict(PopupConflictType.TARGET, map.id, region.id) + destinations.forEach { target -> target.regions.filter { it.isControl && b.intersects(it.bounds) }.forEach { + result += PopupConflict(PopupConflictType.TRANSITION, map.id, region.id, target.id, it.id) + } } + } + } + return result + } +} + +/** Stateful selection engine shared by the real IME and the editor's Try tab. */ +class PopupMapSession(val config: PopupKeyConfig, private val keyWidth: Float = 1f, private val keyHeight: Float = 1f) { + private val history = mutableListOf(config.startMapId) + val currentMap get() = requireNotNull(config.map(history.last())) + val mapPath get() = history.toList() + var selectedRegionId: String? = null; private set + var selectedText: String? = null; private set + var isTap = true; private set + init { require(PopupMapValidator.conflicts(config).isEmpty()); select(0f, 0f) } + fun move(x: Float, y: Float) { + val region = currentMap.regions.firstOrNull { it.bounds.contains(x, y, keyWidth, keyHeight) } + if (region?.isControl == true) { + when (region.action.type) { + PopupActionType.SWITCH -> history += requireNotNull(region.action.targetMapId) + PopupActionType.BACK -> if (history.size > 1) history.removeAt(history.lastIndex) + else -> Unit + } + } + // One transition per position. Text immediately under the finger is selectable. + select(x, y) + } + fun release(x: Float, y: Float): String? { select(x, y); return selectedText?.takeIf { it.isNotEmpty() } } + private fun select(x: Float, y: Float) { + val region = currentMap.regions.firstOrNull { it.bounds.contains(x, y, keyWidth, keyHeight) } + selectedRegionId = region?.id + isTap = x >= -.5f && x < .5f && y >= -.5f && y < .5f + selectedText = if (isTap) currentMap.tapText else region?.takeIf { !it.isControl }?.action?.text + } +} + +object SumirePopupDefaults { + const val STYLE = "free-popup" + val rows = linkedMapOf("あ" to "あいうえお", "か" to "かきくけこ", "さ" to "さしすせそ", "た" to "たちつてと", "な" to "なにぬねの", "は" to "はひふへほ", "ま" to "まみむめも", "や" to "やゆよ", "ら" to "らりるれろ", "わ" to "わをんー") + private val voiced = mapOf("か" to "がぎぐげご", "さ" to "ざじずぜぞ", "た" to "だぢづでど", "は" to "ばびぶべぼ") + private val slots = listOf(PopupBounds(-1.4f,-1.1f,-.6f,-.3f), PopupBounds(-.4f,-1.4f,.4f,-.6f), PopupBounds(.6f,-1.1f,1.4f,-.3f), PopupBounds(-.4f,-2.4f,.4f,-1.6f)) + fun create(keyId: String): PopupKeyConfig { + val row = rows.getValue(keyId) + fun page(id: String, chars: String): PopupMap { + val regions = chars.drop(1).mapIndexed { index, char -> PopupRegion("$id-$index", slots[index], PopupAction(text = char.toString())) }.toMutableList() + if (id != "normal") regions += PopupRegion("$id-back", PopupBounds(-.4f,-3.4f,.4f,-2.6f), PopupAction(PopupActionType.BACK), "戻る") + return PopupMap(id, chars.first().toString() + "行", chars.first().toString(), regions) + } + val normal = page("normal", row).copy(name = "通常") + val maps = mutableListOf(normal) + voiced[keyId]?.let { maps += page("voiced", it) } + if (keyId == "は") maps += page("semi", "ぱぴぷぺぽ") + val controls = maps.drop(1).mapIndexed { index, target -> + val x = if (index == 0) -1.4f else .6f + PopupRegion("open-${target.id}", PopupBounds(x,-2.4f,x+.8f,-1.6f), PopupAction(PopupActionType.SWITCH, targetMapId = target.id), target.name) + } + return PopupKeyConfig(keyId, "normal", listOf(normal.copy(regions = normal.regions + controls)) + maps.drop(1)) + } +} diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayouts.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayouts.kt index 862044a0f..44432a8d2 100644 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayouts.kt +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayouts.kt @@ -171,6 +171,17 @@ object KeyboardDefaultLayouts { sumireFlickInputMode: SumireFlickInputMode = SumireFlickInputMode.ALL, highlightSelectedMode: Boolean = true ): KeyboardLayout { + if (inputStyle == com.kazumaproject.custom_keyboard.data.SumirePopupDefaults.STYLE) { + val base = createFinalLayout(mode, dynamicKeyStates, inputLayoutType, "default", deleteKeyFlickSettings, tfbiFlickRotation, sumireFlickInputMode, highlightSelectedMode) + if (mode != KeyboardInputMode.HIRAGANA) return base + return base.copyWithKeys(base.keys.map { key -> + if (!key.isSpecialKey && key.label in com.kazumaproject.custom_keyboard.data.SumirePopupDefaults.rows) { + key.copy(keyId = "popup-kana-${key.label}", keyType = KeyType.PETAL_FLICK, + textInputBehavior = com.kazumaproject.custom_keyboard.data.KeyTextInputBehavior.NORMAL, + popupMapConfig = com.kazumaproject.custom_keyboard.data.SumirePopupDefaults.create(key.label)) + } else key + }) + } if (inputStyle == "third-flick") { return createFinalLayout( mode, dynamicKeyStates, "flick", "default", deleteKeyFlickSettings, diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardView.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardView.kt index 7b910e0b3..3a0e3c982 100644 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardView.kt +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardView.kt @@ -162,6 +162,7 @@ class FlickKeyboardView @JvmOverloads constructor( private val independentTextPreviews = linkedMapOf() private val independentLastCoordinates = mutableMapOf>() + private val popupMapControllers = mutableListOf() private val flickControllers = mutableListOf() private val crossFlickControllers = mutableListOf() private val centerGuideFlickControllers = mutableListOf() @@ -1704,6 +1705,17 @@ class FlickKeyboardView @JvmOverloads constructor( if (isSuspended(keyData)) return null val layout = currentLayout ?: return null + keyData.popupMapConfig?.let { config -> + return com.kazumaproject.custom_keyboard.controller.PopupMapInputController( + config = config, + windowAnchor = { popupWindowAnchorProvider?.invoke() }, + transform = ::transformInputTextForDisplay, + onPress = { notifyTextPress(keyData, it) }, + onSelection = { text, flick -> updateTextPreview(keyData, text, flick) }, + onCommit = { text, flick -> dispatchCommittedKeyAction(keyData, KeyAction.Text(text), flick) }, + onCancel = { cancelTextPreview(keyData) } + ).also { it.attach(keyView); popupMapControllers.add(it) } + } when (keyData.keyType) { KeyType.QWERTY -> { val config = keyData.qwertyConfig ?: QwertyKeyConfig(QwertyKeyLayer( @@ -2976,6 +2988,10 @@ class FlickKeyboardView @JvmOverloads constructor( private fun detachKeyBehavior(controller: Any?) { when (controller) { + is com.kazumaproject.custom_keyboard.controller.PopupMapInputController -> { + controller.cancel() + popupMapControllers.remove(controller) + } is CustomAngleFlickController -> { controller.cancel() flickControllers.remove(controller) @@ -3071,6 +3087,8 @@ class FlickKeyboardView @JvmOverloads constructor( private fun cancelInputControllers() { controllerRebindPending = true + popupMapControllers.forEach { it.cancel() } + popupMapControllers.clear() flickControllers.forEach { it.cancel() } flickControllers.clear() crossFlickControllers.forEach { it.cancel() } diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/PopupMapView.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/PopupMapView.kt new file mode 100644 index 000000000..def08df91 --- /dev/null +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/PopupMapView.kt @@ -0,0 +1,51 @@ +package com.kazumaproject.custom_keyboard.view + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RectF +import android.view.View +import com.google.android.material.R +import com.google.android.material.color.MaterialColors +import com.kazumaproject.custom_keyboard.data.PopupMap + +/** Draws the same key-relative rectangles used by PopupMapSession. */ +open class PopupMapView(context: Context) : View(context) { + var map: PopupMap? = null + var keyWidth = 1f + var keyHeight = 1f + var originX = 0f + var originY = 0f + var selectedId: String? = null + var keyRotation = 0f + var textTransform: (String) -> String = { it } + private val paint = Paint(Paint.ANTI_ALIAS_FLAG) + override fun onDraw(canvas: Canvas) { + val saved = canvas.save() + canvas.rotate(keyRotation, originX, originY) + val surface = MaterialColors.getColor(this, R.attr.colorSurfaceContainerHigh) + val selected = MaterialColors.getColor(this, R.attr.colorPrimaryContainer) + val foreground = MaterialColors.getColor(this, R.attr.colorOnSurface) + val outline = MaterialColors.getColor(this, R.attr.colorOutline) + map?.regions?.forEach { region -> + val b = region.bounds + val rect = RectF(originX + b.left * keyWidth, originY + b.top * keyHeight, originX + b.right * keyWidth, originY + b.bottom * keyHeight) + val radius = minOf(rect.width(), rect.height()) * .16f + paint.style = Paint.Style.FILL + paint.color = if (region.id == selectedId) selected else surface + canvas.drawRoundRect(rect, radius, radius, paint) + paint.style = Paint.Style.STROKE + paint.strokeWidth = resources.displayMetrics.density + paint.color = outline + canvas.drawRoundRect(rect, radius, radius, paint) + paint.style = Paint.Style.FILL + paint.color = foreground + paint.textAlign = Paint.Align.CENTER + paint.textSize = minOf(20 * resources.displayMetrics.scaledDensity, rect.height() * .42f) + val label = textTransform(region.displayLabel()) + val text = android.text.TextUtils.ellipsize(label, android.text.TextPaint(paint), (rect.width() - 8 * resources.displayMetrics.density).coerceAtLeast(1f), android.text.TextUtils.TruncateAt.END).toString() + canvas.drawText(text, rect.centerX(), rect.centerY() - (paint.ascent() + paint.descent()) / 2, paint) + } + canvas.restoreToCount(saved) + } +} diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/PopupMapTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/PopupMapTest.kt new file mode 100644 index 000000000..5246e0d91 --- /dev/null +++ b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/PopupMapTest.kt @@ -0,0 +1,82 @@ +package com.kazumaproject.custom_keyboard.data + +import org.junit.Assert.* +import org.junit.Test + +class PopupMapTest { + @Test fun onlyKanaKeysUseTheNewStyleAndTapDoesNotToggle() { + val builder=com.kazumaproject.custom_keyboard.layout.KeyboardDefaultLayouts + for(method in listOf("toggle","flick")) { + val layout=builder.createFinalLayout(KeyboardInputMode.HIRAGANA,emptyMap(),method,SumirePopupDefaults.STYLE) + assertEquals(SumirePopupDefaults.rows.size,layout.keys.count {it.popupMapConfig!=null}) + assertTrue(layout.keys.filter {it.popupMapConfig!=null}.all {it.textInputBehavior==KeyTextInputBehavior.NORMAL && !it.isSpecialKey}) + } + for(mode in listOf(KeyboardInputMode.ENGLISH,KeyboardInputMode.SYMBOLS)) { + assertTrue(builder.createFinalLayout(mode,emptyMap(),"flick",SumirePopupDefaults.STYLE).keys.none {it.popupMapConfig!=null}) + } + assertTrue(builder.createFinalLayout(KeyboardInputMode.HIRAGANA,emptyMap(),"flick","default").keys.none {it.popupMapConfig!=null}) + } + @Test fun allInitialMapsAreValid() { + SumirePopupDefaults.rows.keys.forEach { assertEquals(it, emptyList(), PopupMapValidator.conflicts(SumirePopupDefaults.create(it))) } + } + @Test fun tapBelongsToActiveMapAndBackRestoresPreviousTap() { + val session = PopupMapSession(SumirePopupDefaults.create("は")) + assertEquals("は", session.release(.45f,.45f)) + session.move(-1f,-2f) + assertEquals("voiced", session.currentMap.id) + assertEquals("ば",session.release(-.4f,.4f)) + session.move(0f,-3f) + assertEquals("normal",session.currentMap.id) + assertEquals("は",session.release(0f,0f)) + } + @Test fun textUnderFingerAfterSwitchCommitsWithoutReentry() { + val initial = SumirePopupDefaults.create("は") + val target = initial.map("voiced")!! + val config = initial.withMap(target.copy(regions = target.regions + PopupRegion("immediate", initial.map("normal")!!.regions.first { it.isControl }.bounds, PopupAction(text="ありがとう")))) + val session = PopupMapSession(config) + session.move(-1f,-2f) + assertEquals("ありがとう", session.release(-1f,-2f)) + } + @Test fun controlsCannotAppearUnderFingerOnEitherForwardOrBackTransition() { + val initial = SumirePopupDefaults.create("は") + val target = initial.map("voiced")!! + val source = initial.map("normal")!! + val bounds = source.regions.first { it.isControl }.bounds + val invalid = initial.withMap(target.copy(regions=target.regions + PopupRegion("loop", bounds, PopupAction(PopupActionType.BACK)))) + assertTrue(PopupMapValidator.conflicts(invalid).any { it.type==PopupConflictType.TRANSITION }) + // A different control in the parent also matters when Back returns to it. + val back = target.regions.first { it.action.type==PopupActionType.BACK } + val invalidBack = initial.withMap(source.copy(regions=source.regions + PopupRegion("other", back.bounds, PopupAction(PopupActionType.SWITCH,targetMapId="semi")))) + assertTrue(PopupMapValidator.conflicts(invalidBack).any { it.mapId=="voiced" && it.otherMapId=="normal" }) + } + @Test fun overlapAndKeyIntrusionAreRejected() { + val initial=SumirePopupDefaults.create("か"); val map=initial.map("normal")!! + assertTrue(PopupMapValidator.conflicts(initial.withMap(map.copy(regions=map.regions + map.regions.first().copy(id="duplicate")))).any { it.type==PopupConflictType.OVERLAP }) + assertTrue(PopupMapValidator.conflicts(initial.withMap(map.copy(regions=map.regions + PopupRegion("key",PopupBounds.KEY)))).any { it.type==PopupConflictType.KEY }) + } + @Test fun releaseUsesCurrentPositionNotPreviouslyVisitedText() { + val session=PopupMapSession(SumirePopupDefaults.create("か")) + session.move(-1f,-.7f) + assertEquals("き",session.selectedText) + assertNull(session.release(3f,3f)) + assertEquals("か",session.release(.49f,-.49f)) + } + @Test fun missingAndSelfTargetsCannotRun() { + val initial=SumirePopupDefaults.create("か"); val map=initial.map("normal")!! + listOf("missing","normal").forEach { target -> + val bad=initial.withMap(map.copy(regions=map.regions.map { if(it.isControl) it.copy(action=it.action.copy(targetMapId=target)) else it })) + assertTrue(PopupMapValidator.conflicts(bad).any { it.type==PopupConflictType.TARGET }) + } + } + @Test fun roundedCornerIsNotAnInvisibleHitTarget() { + val bounds=PopupBounds(-1f,-2f,0f,-1f) + assertFalse(bounds.contains(-1f,-2f)) + assertTrue(bounds.contains(-.5f,-1.5f)) + } + @Test fun nonSquareKeysUseTheSamePixelRadiusForDrawingAndHitTesting() { + val bounds=PopupBounds(0f,0f,1f,1f) + assertTrue(bounds.contains(.05f,.03f,200f,100f)) + assertFalse(bounds.contains(.02f,.02f,200f,100f)) + assertFalse(bounds.contains(1f,.5f,200f,100f)) + } +} From 7ea849489f572b65fa99411bb4dce78ea8757556 Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Fri, 13 Nov 2026 07:45:16 -0500 Subject: [PATCH 07/69] Add Free Flick nearest selection, compact guide and 12-key template --- .../FreeFlickSettingsDeviceTest.kt | 120 ++++++++++++++++++ .../LegacyPopupFixture.kt | 27 ++++ .../SumirePopupEditorDeviceTest.kt | 6 +- .../SumirePopupInputDeviceTest.kt | 47 ++++++- .../ime_service/IMEService.kt | 8 ++ .../ui/popup_style/PopupStyleFragments.kt | 5 +- .../ui/setting/SettingDestination.kt | 2 + .../ui/setting/SettingSearchIndex.kt | 4 +- .../ui/setting/SumirePreferenceFragment.kt | 4 + .../sumire_popup/FreeFlickPreferences.kt | 23 ++++ .../sumire_popup/FreeFlickSettingsFragment.kt | 52 ++++++++ .../sumire_popup/PopupMapEditorCanvas.kt | 51 +++++++- .../sumire_popup/PopupMapEditorFragment.kt | 22 +++- .../main/res/layout/free_flick_preview.xml | 6 + .../main/res/navigation/mobile_navigation.xml | 5 + app/src/main/res/values-ja/strings.xml | 12 +- .../res/values-ja/sumire_popup_strings.xml | 30 ++++- app/src/main/res/values/strings.xml | 12 +- .../main/res/values/sumire_popup_strings.xml | 30 ++++- app/src/main/res/xml/pref_free_flick.xml | 14 ++ app/src/main/res/xml/pref_sumire.xml | 5 + .../sumire_popup/FreeFlickPreferencesTest.kt | 49 +++++++ .../sumire_popup/SumirePopupRepositoryTest.kt | 30 ++++- core/src/main/res/values-ja/arrays.xml | 2 +- core/src/main/res/values/arrays.xml | 2 +- .../controller/PopupMapGuideHost.kt | 110 ++++++++++++++++ .../controller/PopupMapInputController.kt | 35 ++++- .../controller/TfbiGuidePopupHost.kt | 8 +- .../custom_keyboard/data/PopupMap.kt | 102 +++++++++++---- .../view/CompactFlickGuideSize.kt | 16 +++ .../custom_keyboard/view/FlickKeyboardView.kt | 8 +- .../custom_keyboard/view/PopupMapGuideView.kt | 68 ++++++++++ .../view/TfbiGuidePopupView.kt | 60 ++++++--- .../data/FreeFlickSelectionTest.kt | 87 +++++++++++++ .../custom_keyboard/data/PopupMapTest.kt | 36 +++++- .../view/PopupMapGuideViewTest.kt | 62 +++++++++ 36 files changed, 1066 insertions(+), 94 deletions(-) create mode 100644 app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/FreeFlickSettingsDeviceTest.kt create mode 100644 app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/LegacyPopupFixture.kt create mode 100644 app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickPreferences.kt create mode 100644 app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickSettingsFragment.kt create mode 100644 app/src/main/res/layout/free_flick_preview.xml create mode 100644 app/src/main/res/xml/pref_free_flick.xml create mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickPreferencesTest.kt create mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/PopupMapGuideHost.kt create mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/CompactFlickGuideSize.kt create mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/view/PopupMapGuideView.kt create mode 100644 custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/FreeFlickSelectionTest.kt create mode 100644 custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/PopupMapGuideViewTest.kt diff --git a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/FreeFlickSettingsDeviceTest.kt b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/FreeFlickSettingsDeviceTest.kt new file mode 100644 index 000000000..2d33b97b3 --- /dev/null +++ b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/FreeFlickSettingsDeviceTest.kt @@ -0,0 +1,120 @@ +package com.kazumaproject.markdownhelperkeyboard + +import android.content.Intent +import android.os.SystemClock +import android.view.View +import android.view.ViewGroup +import android.view.inspector.WindowInspector +import android.widget.Button +import android.widget.EditText +import android.widget.TextView +import androidx.navigation.fragment.NavHostFragment +import androidx.preference.ListPreference +import androidx.preference.Preference +import androidx.preference.PreferenceFragmentCompat +import androidx.preference.PreferenceManager +import androidx.preference.SwitchPreferenceCompat +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry +import androidx.test.runner.lifecycle.Stage +import com.google.android.material.button.MaterialButton +import com.kazumaproject.custom_keyboard.data.SumirePopupDefaults +import com.kazumaproject.markdownhelperkeyboard.setting_activity.MainActivity +import com.kazumaproject.markdownhelperkeyboard.sumire_popup.* +import org.junit.Assert.* +import org.junit.Assume.assumeTrue +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class FreeFlickSettingsDeviceTest { + private val ins=InstrumentationRegistry.getInstrumentation() + private val context get()=ins.targetContext + private fun activity()=ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).filterIsInstance().firstOrNull() + private fun nav()=activity()!!.supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment + private fun all(view: View): List = listOf(view)+if(view is ViewGroup) (0 until view.childCount).flatMap {all(view.getChildAt(it))} else emptyList() + private fun views()=activity()?.window?.decorView?.let(::all).orEmpty() + private fun preferences()=nav().childFragmentManager.primaryNavigationFragment as? PreferenceFragmentCompat + private fun await(test: ()->Boolean) { + repeat(400) {var ready=false;ins.runOnMainSync {ready=test()};if(ready)return;SystemClock.sleep(50)} + fail("Free Flick UI did not reach expected state") + } + private fun start() { + assumeTrue(context.packageName.endsWith(".popuptest")) + ins.startActivitySync(Intent(context,MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + await {activity()!=null} + } + @Test fun nativeSettingsAndSearchShareOptionsAndPopupLabelsAreReadable() { + val prefs=PreferenceManager.getDefaultSharedPreferences(context) + prefs.edit().remove(FreeFlickPreferences.NEAREST).remove(FreeFlickPreferences.TEXT) + .remove(FreeFlickPreferences.SWITCH).remove(FreeFlickPreferences.BACK).remove(FreeFlickPreferences.PRESENTATION).commit() + start() + ins.runOnMainSync {nav().navController.navigate(R.id.sumirePreferenceFragment)} + await {preferences()?.findPreference("sumire_free_flick_settings")!=null} + ins.runOnMainSync {preferences()!!.findPreference("sumire_free_flick_settings")!!.performClick()} + await {preferences()?.findPreference(FreeFlickPreferences.NEAREST)!=null} + ins.runOnMainSync { + val screen=preferences()!! + assertTrue(screen.findPreference(FreeFlickPreferences.NEAREST)!!.isChecked) + assertTrue(screen.findPreference(FreeFlickPreferences.TEXT)!!.isChecked) + assertFalse(screen.findPreference(FreeFlickPreferences.SWITCH)!!.isChecked) + assertFalse(screen.findPreference(FreeFlickPreferences.BACK)!!.isChecked) + screen.findPreference(FreeFlickPreferences.SWITCH)!!.isChecked=true + screen.findPreference(FreeFlickPreferences.NEAREST)!!.isChecked=false + assertFalse(screen.findPreference(FreeFlickPreferences.TEXT)!!.isEnabled) + assertFalse(screen.findPreference(FreeFlickPreferences.SWITCH)!!.isEnabled) + assertTrue(screen.findPreference(FreeFlickPreferences.SWITCH)!!.isChecked) + screen.findPreference(FreeFlickPreferences.NEAREST)!!.isChecked=true + screen.findPreference(FreeFlickPreferences.PRESENTATION)!!.value="guide_above_key" + activity()!!.recreate() + } + await {preferences()?.findPreference(FreeFlickPreferences.PRESENTATION)?.value=="guide_above_key"} + assertTrue(FreeFlickPreferences.read(context).nearestSwitch) + ins.runOnMainSync {nav().navController.navigate(R.id.settingSearchFragment)} + await {activity()?.findViewById(R.id.setting_search_input)!=null} + ins.runOnMainSync {activity()!!.findViewById(R.id.setting_search_input).setText(context.getString(R.string.free_flick_nearest_back))} + await {views().filterIsInstance().any {it.id==R.id.setting_search_result_title && it.text==context.getString(R.string.free_flick_nearest_back)}} + ins.runOnMainSync {views().filterIsInstance().firstOrNull {it.id==R.id.setting_search_result_title && it.text==context.getString(R.string.free_flick_nearest_back)}?.let { title -> + generateSequence(title.parent as? View) {it.parent as? View}.first {it.isClickable}.performClick() + }} + await {preferences()?.findPreference(FreeFlickPreferences.BACK)!=null} + ins.runOnMainSync {nav().navController.navigate(R.id.flickKeyboardPopupStyleListFragment)} + await {views().filterIsInstance().any {it.text==context.getString(R.string.popup_style)}} + ins.runOnMainSync { + assertFalse(views().filterIsInstance().any {"3段" in it.text || "3段" in it.text}) + val row=views().filterIsInstance().first {it.text==context.getString(R.string.popup_style)} + generateSequence(row.parent as? View) {it.parent as? View}.first {it.isClickable}.performClick() + } + await {preferences()?.findPreference(FreeFlickPreferences.NEAREST)!=null} + ins.runOnMainSync {activity()!!.finish()} + } + @Test fun templateConfirmationUndoAndSavePreserveOtherKeys() { + val repository=SumirePopupRepository(context) + val original=LegacyPopupFixture.create("は") + repository.save(original) + val other=repository.load("か") + start();ins.runOnMainSync {nav().navController.navigate(R.id.popupMapEditorFragment)} + await {views().filterIsInstance().isNotEmpty()} + fun apply() { + ins.runOnMainSync {views().filterIsInstance().single {it.text==context.getString(R.string.free_flick_template)}.performClick()} + await {WindowInspector.getGlobalWindowViews().flatMap(::all).filterIsInstance