From 462706d46d3ff5a68d44842df324555c4ed2e8ce Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Sat, 14 Nov 2026 08:19:06 -0500 Subject: [PATCH 1/2] Fix Free Flick popup placement with sensitivity-sized taps --- .../sumire_popup/PopupMapEditorCanvas.kt | 11 +- .../PopupMapEditorCanvasTouchTest.kt | 46 ++++++++ .../FreeFlickPopupPositionInstrumentedTest.kt | 108 ++++++++++++++++++ .../controller/PopupMapInputController.kt | 19 ++- .../custom_keyboard/data/PopupMap.kt | 19 ++- .../controller/PopupMapTapSensitivityTest.kt | 39 ++++++- .../custom_keyboard/data/PopupTapAreaTest.kt | 37 ++++++ 7 files changed, 254 insertions(+), 25 deletions(-) create mode 100644 custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/controller/FreeFlickPopupPositionInstrumentedTest.kt 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 index 23bb76e03..6ca96ed8e 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvas.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvas.kt @@ -112,9 +112,7 @@ class PopupMapEditorCanvas(context: Context) : PopupMapView(context) { } fun canPlace(value: PopupKeyConfig, bounds: PopupBounds): Boolean = inViewport(bounds) && PopupMapValidator.conflicts(value).isEmpty() override fun onDraw(canvas: Canvas) { - val savedDrawing=canvas.save() val above=trying && trialVisibility?.visible==true && inputOptions.presentation==PopupMapPresentation.GUIDE_ABOVE_KEY - if(!above) canvas.translate(trialOffsetX,trialOffsetY) if (!trying || (trialVisibility?.visible==true && inputOptions.presentation == PopupMapPresentation.AROUND_KEY)) { super.onDraw(canvas) } else if(trialVisibility?.visible==true) { @@ -168,7 +166,6 @@ class PopupMapEditorCanvas(context: Context) : PopupMapView(context) { 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}" - canvas.restoreToCount(savedDrawing) } override fun performClick(): Boolean { super.performClick(); return true } override fun onTouchEvent(event: MotionEvent): Boolean { @@ -183,7 +180,7 @@ class PopupMapEditorCanvas(context: Context) : PopupMapView(context) { updateTapArea() trialOffsetX=if(tapArea.followsSensitivity) event.x-originX else 0f trialOffsetY=if(tapArea.followsSensitivity) event.y-originY else 0f - trial=PopupMapSession(value,keyWidth,keyHeight,inputOptions,tapArea) + trial=PopupMapSession(value,keyWidth,keyHeight,inputOptions,tapArea,trialOffsetX/keyWidth,trialOffsetY/keyHeight) fingerPosition=(event.x-originX-trialOffsetX)/keyWidth to (event.y-originY-trialOffsetY)/keyHeight val settings=FreeFlickPreferences.gestureConfig(context) trialVisibility=PopupMapVisibility(settings,event.x,event.y,inputOptions.presentation) @@ -191,7 +188,7 @@ class PopupMapEditorCanvas(context: Context) : PopupMapView(context) { } MotionEvent.ACTION_MOVE -> trial?.let { active -> for(i in 0 until event.historySize) { - val hx=(event.getHistoricalX(i)-originX-trialOffsetX)/keyWidth;val hy=(event.getHistoricalY(i)-originY-trialOffsetY)/keyHeight + val hx=(event.getHistoricalX(i)-originX)/keyWidth;val hy=(event.getHistoricalY(i)-originY)/keyHeight trialVisibility?.move(event.getHistoricalX(i),event.getHistoricalY(i)) active.move(hx,hy) } @@ -199,10 +196,10 @@ class PopupMapEditorCanvas(context: Context) : PopupMapView(context) { if(trialVisibility?.longPressEligible==false) removeCallbacks(expandTrial) val tx=(event.x-originX-trialOffsetX)/keyWidth;val ty=(event.y-originY-trialOffsetY)/keyHeight fingerPosition=tx to ty - active.move(tx,ty) + active.move(x,y) } MotionEvent.ACTION_UP -> trial?.let { active -> - val output=active.release((event.x-originX-trialOffsetX)/keyWidth,(event.y-originY-trialOffsetY)/keyHeight);onTrial(output,active) + val output=active.release(x,y);onTrial(output,active) cancelTrial() } MotionEvent.ACTION_CANCEL -> {cancelTrial()} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvasTouchTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvasTouchTest.kt index e3f48128a..44bcf07ba 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvasTouchTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorCanvasTouchTest.kt @@ -1,16 +1,20 @@ package com.kazumaproject.markdownhelperkeyboard.sumire_popup +import android.graphics.Bitmap +import android.graphics.Canvas import android.view.ContextThemeWrapper import android.view.MotionEvent import android.view.View import android.widget.FrameLayout import androidx.test.core.app.ApplicationProvider import com.kazumaproject.custom_keyboard.data.* +import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode @RunWith(RobolectricTestRunner::class) @Config(sdk=[35]) @@ -50,4 +54,46 @@ class PopupMapEditorCanvasTouchTest { assertEquals(initial.left,result.left,0f);assertEquals(initial.right,result.right,0f) assertTrue(result.top() + canvas.onTrial={text,_->if(text!=null) output+=text} + touch(canvas,MotionEvent.ACTION_DOWN,-.375f,.25f) + touch(canvas,MotionEvent.ACTION_UP,-.375f,.25f) + assertEquals(listOf("は"),output) + touch(canvas,MotionEvent.ACTION_DOWN,-.375f,.25f) + touch(canvas,MotionEvent.ACTION_MOVE,.8f,0f) + touch(canvas,MotionEvent.ACTION_UP,.8f,0f) + assertEquals(listOf("は","へ"),output) + } + } } diff --git a/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/controller/FreeFlickPopupPositionInstrumentedTest.kt b/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/controller/FreeFlickPopupPositionInstrumentedTest.kt new file mode 100644 index 000000000..6f1aa7f5f --- /dev/null +++ b/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/controller/FreeFlickPopupPositionInstrumentedTest.kt @@ -0,0 +1,108 @@ +package com.kazumaproject.custom_keyboard.controller + +import android.content.Intent +import android.os.SystemClock +import android.view.InputDevice +import android.view.MotionEvent +import android.view.WindowManager +import android.widget.PopupWindow +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.kazumaproject.core.data.popup.TfbiPopupPresentationMode +import com.kazumaproject.custom_keyboard.data.* +import com.kazumaproject.custom_keyboard.layout.KeyboardDefaultLayouts +import com.kazumaproject.custom_keyboard.view.PopupMapView +import com.kazumaproject.custom_keyboard.view.SumireFlickRotationTestActivity +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +/** Exercises the production keyboard touch router and native popup windows without changing the IME. */ +@RunWith(AndroidJUnit4::class) +class FreeFlickPopupPositionInstrumentedTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + + @Test fun sensitivityKeepsPopupPlacementAndDirectHitsKeyRelative() { + val intent = Intent(instrumentation.context, SumireFlickRotationTestActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ActivityScenario.launch(intent).use { scenario -> + scenario.onActivity { activity -> + activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + activity.configure(SumirePopupDefaults.STYLE, TfbiFlickRotation.DEFAULT, TfbiPopupPresentationMode.LEGACY_GRID) + val layout = KeyboardDefaultLayouts.createFinalLayout( + KeyboardInputMode.HIRAGANA, emptyMap(), "flick", SumirePopupDefaults.STYLE) + val config = PopupKeyConfig("か", "normal", listOf(PopupMap("normal", "通常", "か", listOf( + PopupRegion("small", PopupBounds(.7f, -.1f, .9f, .1f), PopupAction(text = "○")))))) + activity.keyboard.setKeyboard(layout.copyWithKeys(layout.keys.map { + if (it.label == "か") it.copy(popupMapConfig = config) else it + }), origin = KeyboardLayoutOrigin.BUILT_IN) + } + instrumentation.waitForIdleSync() + for (presentation in PopupMapPresentation.entries) for (sensitivity in listOf(1, 100, 200)) { + scenario.onActivity { + it.keyboard.setPopupMapOptions(PopupMapInputOptions(nearestEnabled = false, + presentation = presentation, tapSizeMode = PopupTapSizeMode.FLICK_SENSITIVITY)) + it.keyboard.setFlickSensitivityValue(sensitivity) + } + event(scenario, MotionEvent.ACTION_DOWN, 0f, 0f) + val centered = popupOrigin(scenario, presentation) + event(scenario, MotionEvent.ACTION_CANCEL, 0f, 0f) + event(scenario, MotionEvent.ACTION_DOWN, -.375f, .25f) + val offCenter = popupOrigin(scenario, presentation) + assertEquals("$presentation / $sensitivity: popup X", centered.first, offCenter.first, 1f) + assertEquals("$presentation / $sensitivity: popup Y", centered.second, offCenter.second, 1f) + event(scenario, MotionEvent.ACTION_UP, -.375f, .25f) + scenario.onActivity { assertEquals(listOf(KeyAction.Text("か")), it.actions) } + + event(scenario, MotionEvent.ACTION_DOWN, -.375f, .25f) + event(scenario, MotionEvent.ACTION_MOVE, .8f, 0f) + event(scenario, MotionEvent.ACTION_UP, .8f, 0f) + scenario.onActivity { assertEquals("$presentation / $sensitivity: direct hit", + listOf(KeyAction.Text("○")), it.actions) } + } + } + } + + private fun event(scenario: ActivityScenario, action: Int, x: Float, y: Float) { + scenario.onActivity { activity -> + if (action == MotionEvent.ACTION_DOWN) activity.actions.clear() + val key = activity.kaKey() + val keyLocation = IntArray(2).also(key::getLocationOnScreen) + val keyboardLocation = IntArray(2).also(activity.keyboard::getLocationOnScreen) + val event = MotionEvent.obtain(0L, SystemClock.uptimeMillis(), action, + keyLocation[0] + (.5f + x) * key.width, + keyLocation[1] + (.5f + y) * key.height, 0) + event.source = InputDevice.SOURCE_TOUCHSCREEN + event.offsetLocation(-keyboardLocation[0].toFloat(), -keyboardLocation[1].toFloat()) + try { assertTrue(activity.keyboard.dispatchTouchEvent(event)) } finally { event.recycle() } + } + instrumentation.waitForIdleSync() + } + + private fun field(target: Any, name: String): Any? = target.javaClass.getDeclaredField(name) + .apply { isAccessible = true }.get(target) + + private fun popupOrigin(scenario: ActivityScenario, presentation: PopupMapPresentation): Pair { + var origin: Pair? = null + scenario.onActivity { activity -> + val controllers = field(activity.keyboard, "popupMapControllers") as List<*> + val controller = controllers.filterNotNull().single { field(it, "anchor") === activity.kaKey() } + val drawing: PopupMapView + val window: PopupWindow + if (presentation == PopupMapPresentation.AROUND_KEY) { + drawing = field(controller, "content") as PopupMapView + window = field(controller, "popup") as PopupWindow + } else { + val host = field(controller, "guideHost")!! + drawing = field(host, "view") as PopupMapView + window = field(host, "window") as PopupWindow + } + assertTrue("Native popup must be showing", window.isShowing) + assertTrue(drawing.isAttachedToWindow) + val location = IntArray(2).also(drawing::getLocationOnScreen) + origin = location[0] + drawing.originX to location[1] + drawing.originY + } + return requireNotNull(origin) + } +} 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 index 382e86600..bb0804510 100644 --- 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 @@ -64,12 +64,11 @@ class PopupMapInputController( if (inputOptions != value) { cancel(); inputOptions = value } } private fun sample(x: Float, y: Float) { - fingerPosition = coordinateX(x) to coordinateY(y) + val active=session ?: return + fingerPosition = coordinateX(x)-active.tapOriginX to coordinateY(y)-active.tapOriginY } - private var inputOriginX = 0f - private var inputOriginY = 0f - private fun coordinateX(x: Float) = (x - inputOriginX) / width - private fun coordinateY(y: Float) = (y - inputOriginY) / height + private fun coordinateX(x: Float) = x / width - .5f + private fun coordinateY(y: Float) = y / height - .5f private var observingAttachment = false private val attachmentListener = object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) = Unit @@ -112,9 +111,9 @@ class PopupMapInputController( val settings=gestureConfigSource?.snapshot() ?: GestureSessionConfig(0L,100, ViewConfiguration.get(view.context).scaledTouchSlop*3.5f,300L) val tapArea=PopupTapArea.resolve(inputOptions.tapSizeMode,width.toFloat(),height.toFloat(),settings.flickThresholdPx) - inputOriginX=if(tapArea.followsSensitivity) event.x else width/2f - inputOriginY=if(tapArea.followsSensitivity) event.y else height/2f - session = PopupMapSession(config, width.toFloat(), height.toFloat(), inputOptions, tapArea) + session = PopupMapSession(config, width.toFloat(), height.toFloat(), inputOptions, tapArea, + if(tapArea.followsSensitivity) coordinateX(event.x) else 0f, + if(tapArea.followsSensitivity) coordinateY(event.y) else 0f) sample(event.x,event.y) visibility=PopupMapVisibility(settings,event.x,event.y,inputOptions.presentation) if(inputOptions.presentation==PopupMapPresentation.AROUND_KEY) handler.postDelayed(longPress,settings.longPressTimeoutMillis) @@ -209,8 +208,8 @@ class PopupMapInputController( setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) }.also { popup = it } val location = getLocationRelativeToWindowAnchor(key, host) - val x = (location[0] + inputOriginX + left).toInt() - val y = (location[1] + inputOriginY + top).toInt() + val x = location[0] + width / 2 + left + val y = location[1] + height / 2 + top val placement=listOf(x,y,right-left,bottom-top) if (window.isShowing) { if(lastPlacement!=placement) window.update(x,y,right-left,bottom-top) 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 index 507977017..377183d02 100644 --- 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 @@ -124,7 +124,10 @@ class PopupMapSession( private val keyWidth: Float = 1f, private val keyHeight: Float = 1f, val options: PopupMapInputOptions = PopupMapInputOptions(), - val tapArea: PopupTapArea = PopupTapArea.KEY + val tapArea: PopupTapArea = PopupTapArea.KEY, + // Only sensitivity-based tap detection follows the initial touch. Map coordinates stay key-relative. + val tapOriginX: Float = 0f, + val tapOriginY: Float = 0f ) { private val history = mutableListOf(config.startMapId) val currentMap get() = requireNotNull(config.map(history.last())) @@ -133,7 +136,7 @@ class PopupMapSession( var selectedText: String? = null; private set var isTap = true; private set private var arrivalControl: String? = null - init { require(PopupMapValidator.conflicts(config).isEmpty()); select(0f, 0f) } + init { require(PopupMapValidator.conflicts(config).isEmpty()); select(tapOriginX, tapOriginY) } fun move(x: Float, y: Float) { if (!x.isFinite() || !y.isFinite()) return val region = resolve(x, y) @@ -154,7 +157,7 @@ class PopupMapSession( select(x, y) } fun release(x: Float, y: Float): String? { select(x, y); return selectedText?.takeIf { it.isNotEmpty() } } - private fun insideKey(x: Float, y: Float) = tapArea.contains(x, y, keyWidth, keyHeight) + private fun insideKey(x: Float, y: Float) = tapArea.contains(x-tapOriginX, y-tapOriginY, keyWidth, keyHeight) private fun resolve(x: Float, y: Float): PopupRegion? { if (!x.isFinite() || !y.isFinite() || insideKey(x,y)) return null currentMap.regions.firstOrNull { it.contains(x, y, keyWidth, keyHeight) }?.let { return it } @@ -162,9 +165,13 @@ class PopupMapSession( // The sensitivity box can leave a gap inside the reserved key. Project that motion // to the key's edge, so a short horizontal flick does not pick a nearer top/bottom // popup simply because the physical key is wider than it is tall. - val extent=maxOf(abs(x),abs(y)) - val scale=if(tapArea.followsSensitivity && extent>0f && extent<.5f) .5f/extent else 1f - val distances = candidates.map { it to it.distanceTo(x*scale,y*scale,keyWidth,keyHeight) } + val dx=x-tapOriginX;val dy=y-tapOriginY + val extent=maxOf(abs(dx),abs(dy)) + val projectFromTouch=tapArea.followsSensitivity && extent>0f && abs(x)<=.5f && abs(y)<=.5f + val scale=if(projectFromTouch) .5f/extent else 1f + val nearestX=if(projectFromTouch) dx*scale else x + val nearestY=if(projectFromTouch) dy*scale else y + val distances = candidates.map { it to it.distanceTo(nearestX,nearestY,keyWidth,keyHeight) } val minimum = distances.minOfOrNull { it.second } ?: return null val tied = distances.filter { abs(it.second - minimum) < .001f }.map { it.first } return tied.firstOrNull { it.id == selectedRegionId } ?: tied.firstOrNull() diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/controller/PopupMapTapSensitivityTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/controller/PopupMapTapSensitivityTest.kt index ec946278f..360102611 100644 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/controller/PopupMapTapSensitivityTest.kt +++ b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/controller/PopupMapTapSensitivityTest.kt @@ -22,6 +22,8 @@ import org.robolectric.annotation.Config @Config(sdk=[35]) class PopupMapTapSensitivityTest { private fun verify(presentation: PopupMapPresentation, settings: GestureSessionConfig=GestureSessionConfig(0,1,20f,300), + config: PopupKeyConfig=SumirePopupDefaults.create("は"),nearestEnabled: Boolean=true, + tapSizeMode: PopupTapSizeMode=PopupTapSizeMode.FLICK_SENSITIVITY, block: (TextView,PopupMapInputController,MutableList)->Unit) { val activity=Robolectric.buildActivity(Activity::class.java).setup().get() activity.setTheme(com.google.android.material.R.style.Theme_Material3_DayNight) @@ -31,8 +33,8 @@ class PopupMapTapSensitivityTest { frame.measure(View.MeasureSpec.makeMeasureSpec(600,View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(400,View.MeasureSpec.EXACTLY)) frame.layout(0,0,600,400);key.layout(200,200,400,300) val output=mutableListOf() - val controller=PopupMapInputController(SumirePopupDefaults.create("は"),{frame},{it},{},{_,_->},{text,_->output+=text},{}, - PopupMapInputOptions(presentation=presentation,tapSizeMode=PopupTapSizeMode.FLICK_SENSITIVITY), + val controller=PopupMapInputController(config,{frame},{it},{},{_,_->},{text,_->output+=text},{}, + PopupMapInputOptions(nearestEnabled=nearestEnabled,presentation=presentation,tapSizeMode=tapSizeMode), GestureSessionConfigSource {settings}) controller.attach(key) try {block(key,controller,output)} finally {controller.cancel();activity.finish()} @@ -72,6 +74,39 @@ class PopupMapTapSensitivityTest { key.event(MotionEvent.ACTION_CANCEL,25f,75f) } } + @Test fun aroundKeyPopupStaysCenteredOnTheKeyForOffCenterPresses() { + for(mode in PopupTapSizeMode.entries) verify(PopupMapPresentation.AROUND_KEY,tapSizeMode=mode) { key,controller,_ -> + for((x,y) in listOf(25f to 75f,199f to 1f,100f to 50f)) { + key.event(MotionEvent.ACTION_DOWN,x,y) + val drawing=controller.javaClass.getDeclaredField("content").apply {isAccessible=true}.get(controller) as PopupMapView + @Suppress("UNCHECKED_CAST") + val placement=controller.javaClass.getDeclaredField("lastPlacement").apply {isAccessible=true}.get(controller) as List + val location=getLocationRelativeToWindowAnchor(key,key.parent as View) + assertEquals("Popup X must stay at the key center for press ($x,$y)",location[0]+100f,placement[0]+drawing.originX,.5f) + assertEquals("Popup Y must stay at the key center for press ($x,$y)",location[1]+50f,placement[1]+drawing.originY,.5f) + key.event(MotionEvent.ACTION_CANCEL,x,y) + } + } + } + @Test fun directSelectionUsesDisplayedKeyRelativeRegionsAfterAnOffCenterPress() { + val config=PopupKeyConfig("は","normal",listOf(PopupMap("normal","通常","は",listOf( + PopupRegion("small",PopupBounds(.7f,-.1f,.9f,.1f),PopupAction(text="へ")))))) + for(presentation in PopupMapPresentation.entries) verify(presentation,config=config,nearestEnabled=false) {key,_,output -> + key.event(MotionEvent.ACTION_DOWN,25f,75f) + key.event(MotionEvent.ACTION_MOVE,260f,50f) + key.event(MotionEvent.ACTION_UP,260f,50f) + assertEquals(listOf("へ"),output) + } + } + @Test fun aboveKeyPointerUsesMovementFromInitialTouchRatherThanTheKeyCenter() { + verify(PopupMapPresentation.GUIDE_ABOVE_KEY) { key,controller,_ -> + key.event(MotionEvent.ACTION_DOWN,25f,75f) + key.event(MotionEvent.ACTION_MOVE,49f,75f) + val host=controller.javaClass.getDeclaredField("guideHost").apply {isAccessible=true}.get(controller)!! + val view=host.javaClass.getDeclaredField("view").apply {isAccessible=true}.get(host) as PopupMapGuideView + assertEquals(com.kazumaproject.custom_keyboard.view.TfbiFlickDirection.RIGHT,view.pointerDirection()) + } + } @Test fun disablingBothPopupFlagsStillAllowsInputWithoutShowingAnAboveGuide() { verify(PopupMapPresentation.GUIDE_ABOVE_KEY,GestureSessionConfig(0,1,20f,300,showFlickPopup=false,showLongPressPopup=false)) {key,controller,output -> key.event(MotionEvent.ACTION_DOWN,199f,99f) diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/PopupTapAreaTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/PopupTapAreaTest.kt index 428c57d2c..08564001b 100644 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/PopupTapAreaTest.kt +++ b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/data/PopupTapAreaTest.kt @@ -43,6 +43,43 @@ class PopupTapAreaTest { assertFalse(session.isTap) assertEquals("ふ",session.release(0f,-.21f)) } + @Test fun offCenterSensitivityTapsAndShortFlicksUseTheInitialTouch() { + val area=PopupTapArea.resolve(PopupTapSizeMode.FLICK_SENSITIVITY,200f,100f,20f) + for((x,y) in listOf(-.49f to -.49f,.49f to .49f,0f to 0f)) { + val session=PopupMapSession(SumirePopupDefaults.create("は"),200f,100f,tapArea=area,tapOriginX=x,tapOriginY=y) + assertTrue(session.isTap) + assertEquals("は",session.release(x,y)) + assertEquals("は",session.release(x+.09f,y)) + assertEquals("へ",session.release(x+.11f,y)) + assertFalse(session.isTap) + } + } + @Test fun horizontalMovementAcrossTheReservedKeyKeepsItsDirectionAfterAnEdgePress() { + val area=PopupTapArea.resolve(PopupTapSizeMode.FLICK_SENSITIVITY,200f,100f,20f) + for(originX in listOf(-.49f,.49f)) for(y in listOf(-.49f,.49f)) { + val session=PopupMapSession(SumirePopupDefaults.create("は"),200f,100f,tapArea=area,tapOriginX=originX,tapOriginY=y) + val direction=if(originX<0f) 1f else -1f + val expected=if(direction>0f) "へ" else "ひ" + for(distance in listOf(.11f,.5f,.98f)) { + assertEquals("Movement from ($originX,$y) by $distance is horizontal",expected,session.release(originX+direction*distance,y)) + } + } + } + @Test fun offCenterPressDoesNotShiftDirectShapeHitsOrMapTransitions() { + val area=PopupTapArea.resolve(PopupTapSizeMode.FLICK_SENSITIVITY,200f,100f,20f) + val bounds=PopupBounds(.7f,-.2f,1.1f,.2f) + val config=PopupKeyConfig("は","normal",listOf( + PopupMap("normal","通常","は",listOf(PopupRegion("switch",bounds,PopupAction(PopupActionType.SWITCH,targetMapId="next")))), + PopupMap("next","次","ば",listOf(PopupRegion("text",bounds,PopupAction(text="○"),outline=PopupOutline())))),version=2) + val session=PopupMapSession(config,200f,100f,PopupMapInputOptions(nearestEnabled=false),area,-.375f,.25f) + // A point outside the actual contour must not switch the map. + session.move(.71f,.19f) + assertEquals("normal",session.currentMap.id) + session.move(.9f,0f) + assertEquals("next",session.currentMap.id) + assertEquals("○",session.release(.9f,0f)) + assertEquals("ば",session.release(-.375f,.25f)) + } @Test fun aGestureKeepsItsFrozenTapAreaWhenSettingsChange() { val first=PopupTapArea.resolve(PopupTapSizeMode.FLICK_SENSITIVITY,200f,100f,12f) val session=PopupMapSession(SumirePopupDefaults.create("は"),200f,100f,tapArea=first) From 5d295af1035dab09e63573ac103a84b9be7ae456 Mon Sep 17 00:00:00 2001 From: Codex Mozc Autonomy Date: Sat, 14 Nov 2026 20:31:05 -0500 Subject: [PATCH 2/2] Add custom Free Flick keys and remove three-stage flick --- .../CustomFreeFlickKeyDeviceTest.kt | 230 ++++++++++++++++++ .../FastInputMatrixInstrumentedTest.kt | 1 - .../SumireFlickRotationDeviceTest.kt | 26 +- .../ThreeStageFlickSuspensionDeviceTest.kt | 165 ------------- .../custom_keyboard/data/KeyDefinition.kt | 2 +- .../import_export/KeyboardBackupPipeline.kt | 14 +- .../import_export/KeyboardLayoutExportDtos.kt | 4 +- .../KeyboardLayoutJsonExporter.kt | 2 +- .../KeyboardLayoutJsonImporter.kt | 2 +- .../ui/CustomFreeFlickEditorDialog.kt | 51 ++++ .../custom_keyboard/ui/KeyEditorFragment.kt | 86 ++++++- .../ui/KeyboardEditorViewModel.kt | 19 +- .../database/AppDatabase.kt | 41 +++- .../ime_service/IMEService.kt | 16 +- .../ime_service/ImePreferencesSnapshot.kt | 12 +- .../ime_service/di/AppModule.kt | 2 + .../repository/KeyboardRepository.kt | 15 +- .../setting_activity/AppPreference.kt | 40 ++- .../ui/setting/SumirePreferenceFragment.kt | 3 - .../sumire_popup/FreeFlickKeyPicker.kt | 2 +- .../sumire_popup/FreeFlickKeyboardPreview.kt | 2 +- .../sumire_popup/PopupMapEditorFragment.kt | 77 ++++-- .../main/res/layout/fragment_key_editor.xml | 14 ++ app/src/main/res/values-ja/strings.xml | 27 +- app/src/main/res/values/arrays.xml | 10 - app/src/main/res/values/ids.xml | 1 + app/src/main/res/values/strings.xml | 27 +- app/src/main/res/xml/pref_sumire.xml | 4 - .../database/FreeFlickKeyMigrationTest.kt | 69 ++++++ ...est.kt => LegacyKeySchemaMigrationTest.kt} | 12 +- .../database/QwertyKeyMigrationTest.kt | 6 +- .../KeyboardLayoutJsonImporterTest.kt | 2 +- .../ui/CustomFreeFlickEditorDialogTest.kt | 64 +++++ .../ui/CustomFreeFlickPersistenceTest.kt | 78 ++++++ ...ardEditorViewModelFlexiblePlacementTest.kt | 6 - .../ui/ThreeStageFlickPersistenceTest.kt | 107 -------- .../RomajiBehaviorPersistenceTest.kt | 4 +- .../IMEServiceSumireFlickRotationTest.kt | 1 - .../ng_word/database/NgWordMigrationTest.kt | 6 +- .../AppPreferenceSumireFlickInputModeTest.kt | 89 ------- .../RemovedFlickPreferencesMigrationTest.kt | 31 +++ .../data/popup/TfbiPopupPresentationMode.kt | 2 +- core/src/main/res/values-ja/strings.xml | 3 +- core/src/main/res/values/strings.xml | 3 +- .../FreeFlickPopupPositionInstrumentedTest.kt | 50 +++- .../SumireFlickRotationInstrumentedTest.kt | 12 +- ...reeStageFlickSuspensionInstrumentedTest.kt | 75 ------ .../data/CustomFlickSuspension.kt | 10 - .../custom_keyboard/data/KeyModels.kt | 4 +- .../data/KeyboardLayoutOrigin.kt | 4 + .../data/PopupKeyConfigCodec.kt | 32 +++ .../data/SumireFlickInputMode.kt | 13 - .../layout/KeyboardDefaultLayouts.kt | 12 +- .../custom_keyboard/view/FlickKeyboardView.kt | 21 +- ...eyboardDefaultLayoutsFlickInputModeTest.kt | 37 --- .../view/CustomThreeStageFlickTest.kt | 89 ------- .../view/FlickKeyboardViewLifecycleTest.kt | 4 +- .../view/SumireModeKeyHighlightTest.kt | 2 +- 58 files changed, 878 insertions(+), 865 deletions(-) create mode 100644 app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/CustomFreeFlickKeyDeviceTest.kt delete mode 100644 app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/ThreeStageFlickSuspensionDeviceTest.kt create mode 100644 app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickEditorDialog.kt create mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/FreeFlickKeyMigrationTest.kt rename app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/{HierarchicalFlickMigrationTest.kt => LegacyKeySchemaMigrationTest.kt} (88%) create mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickEditorDialogTest.kt create mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickPersistenceTest.kt delete mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/ThreeStageFlickPersistenceTest.kt delete mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreferenceSumireFlickInputModeTest.kt create mode 100644 app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/RemovedFlickPreferencesMigrationTest.kt delete mode 100644 custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/view/ThreeStageFlickSuspensionInstrumentedTest.kt delete mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/CustomFlickSuspension.kt create mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyboardLayoutOrigin.kt create mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/PopupKeyConfigCodec.kt delete mode 100644 custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/SumireFlickInputMode.kt delete mode 100644 custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayoutsFlickInputModeTest.kt delete mode 100644 custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/CustomThreeStageFlickTest.kt diff --git a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/CustomFreeFlickKeyDeviceTest.kt b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/CustomFreeFlickKeyDeviceTest.kt new file mode 100644 index 000000000..45d22bd51 --- /dev/null +++ b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/CustomFreeFlickKeyDeviceTest.kt @@ -0,0 +1,230 @@ +package com.kazumaproject.markdownhelperkeyboard + +import android.content.Intent +import android.graphics.Rect +import android.os.Bundle +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.inspector.WindowInspector +import android.widget.TextView +import androidx.navigation.fragment.NavHostFragment +import androidx.preference.PreferenceManager +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +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.custom_keyboard.data.* +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui.KeyboardEditorFragment +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui.KeyEditorFragment +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui.CustomFreeFlickEditorDialog +import com.kazumaproject.markdownhelperkeyboard.sumire_popup.PopupMapEditorFragment +import com.kazumaproject.markdownhelperkeyboard.sumire_popup.FreeFlickPreferences +import com.kazumaproject.markdownhelperkeyboard.setting_activity.MainActivity +import com.kazumaproject.custom_keyboard.view.FlickKeyboardView +import com.kazumaproject.markdownhelperkeyboard.ime_service.di.AppModule +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 + +/** Exercises production editing and IME input in an isolated install. */ +@RunWith(AndroidJUnit4::class) +@SdkSuppress(minSdkVersion = 29) +class CustomFreeFlickKeyDeviceTest { + private val ins = InstrumentationRegistry.getInstrumentation() + private fun shell(command: String) = ParcelFileDescriptor.AutoCloseInputStream( + ins.uiAutomation.executeShellCommand(command)).bufferedReader().use { it.readText().trim() } + private fun main(block: () -> Unit) = ins.runOnMainSync(block) + private fun descendants(view: View): Sequence = sequence { + yield(view) + if (view is ViewGroup) for (i in 0 until view.childCount) yieldAll(descendants(view.getChildAt(i))) + } + private fun views() = WindowInspector.getGlobalWindowViews().asSequence().flatMap(::descendants) + .filter { it.isAttachedToWindow && it.isShown && it.width > 0 && it.height > 0 && + generateSequence(it as View?) { parent -> parent.parent as? View }.all { parent -> parent.alpha > 0.9f } && + it.getGlobalVisibleRect(Rect()) } + private fun await(message: String, predicate: () -> Boolean) { + val deadline = SystemClock.uptimeMillis() + 15000 + while (SystemClock.uptimeMillis() < deadline) { + var ready = false + main { ready = predicate() } + if (ready) return + SystemClock.sleep(50) + } + var details = "" + main { + details = views().filterIsInstance().joinToString { "surface=${it.id}/${it.width}x${it.height}" } + } + error("$message: $details") + } + private fun key(label: String): Rect { + var result: Rect? = null + await("Missing key $label") { + result = views().filterIsInstance().flatMap(::descendants) + .firstOrNull { it.isShown && ((it as? TextView)?.text?.toString() == label || it.contentDescription == label) } + ?.let { view -> IntArray(2).also(view::getLocationOnScreen).let { Rect(it[0], it[1], it[0] + view.width, it[1] + view.height) } } + result != null + } + return result!! + } + private var downTime = 0L + private fun send(action: Int, x: Float, y: Float) { + if (action == MotionEvent.ACTION_DOWN) downTime = SystemClock.uptimeMillis() + val event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action, x, y, 0) + event.source = InputDevice.SOURCE_TOUCHSCREEN + try { check(ins.uiAutomation.injectInputEvent(event, true)) } finally { event.recycle() } + } + private fun tap(label: String) { + val bounds = key(label) + send(MotionEvent.ACTION_DOWN, bounds.exactCenterX(), bounds.exactCenterY()) + SystemClock.sleep(40) + send(MotionEvent.ACTION_UP, bounds.exactCenterX(), bounds.exactCenterY()) + SystemClock.sleep(120) + } + @Test fun editorConvertsKeyAndRestoresTheMapDraftAcrossRecreation() = runBlocking { + val context = ins.targetContext + check(context.packageName.endsWith(".customfreeflicktest")) + val db = AppModule.providesLearnDatabase(context) + val repository = KeyboardRepository(db.keyboardLayoutDao()) + val original = KeyData("Old", 0, 0, false, KeyAction.Text("a"), keyId = "editor-key") + val id = repository.saveLayout(KeyboardLayout(listOf(original), emptyMap(), 1, 1), "Free Flick editor verification", null) + try { + ActivityScenario.launch(Intent(context, MainActivity::class.java)).use { scenario -> + scenario.onActivity { it.window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } + fun host(): NavHostFragment = ActivityLifecycleMonitorRegistry.getInstance() + .getActivitiesInStage(Stage.RESUMED).filterIsInstance().first() + .supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment + fun keyEditor() = host().childFragmentManager.primaryNavigationFragment as KeyEditorFragment + fun mapEditor(): PopupMapEditorFragment? { + val dialog = keyEditor().childFragmentManager.findFragmentByTag("freeFlickEditor") as? CustomFreeFlickEditorDialog + return dialog?.childFragmentManager?.findFragmentById(R.id.custom_free_flick_editor_host) as? PopupMapEditorFragment + } + await("Settings initialized") { runCatching { host().navController.currentDestination != null }.getOrDefault(false) } + main { host().navController.navigate(R.id.keyboardEditorFragment, Bundle().apply { putLong("layoutId", id) }) } + await("Layout editor loaded") { + val fragment = host().childFragmentManager.primaryNavigationFragment as? KeyboardEditorFragment + fragment?.view?.let { descendants(it).filterIsInstance().any { text -> text.text.toString() == "Old" } } == true + } + main { + val editor = host().childFragmentManager.primaryNavigationFragment as KeyboardEditorFragment + editor.onKeySelected("editor-key"); editor.onKeySelected("editor-key") + } + await("Key editor initialized") { runCatching { keyEditor().view?.findViewById(R.id.button_done)?.isEnabled == true }.getOrDefault(false) } + main { + keyEditor().requireView().findViewById(R.id.chip_free_flick).performClick() + keyEditor().requireView().findViewById(R.id.edit_free_flick_map).performClick() + } + await("Map editor opened") { runCatching { mapEditor()?.view != null }.getOrDefault(false) } + main { + descendants(mapEditor()!!.requireView()).filterIsInstance() + .single { it.hint == context.getString(R.string.popup_input) }.editText!!.setText("edited😀") + } + scenario.recreate() + await("Map draft restored") { runCatching { + descendants(mapEditor()!!.requireView()).filterIsInstance() + .any { it.hint == context.getString(R.string.popup_input) && it.editText?.text.toString() == "edited😀" } + }.getOrDefault(false) } + main { + descendants(mapEditor()!!.requireView()).filterIsInstance() + .single { it.text == context.getString(R.string.popup_apply) }.performClick() + } + await("Map applied to key draft") { keyEditor().childFragmentManager.findFragmentByTag("freeFlickEditor") == null } + scenario.recreate() + await("Key type restored") { runCatching { + keyEditor().requireView().findViewById(R.id.chip_free_flick).isChecked && + keyEditor().requireView().findViewById(R.id.button_done).isEnabled + }.getOrDefault(false) } + main { keyEditor().requireView().findViewById(R.id.button_done).performClick() } + await("Returned to layout editor") { host().childFragmentManager.primaryNavigationFragment is KeyboardEditorFragment } + await("Save action ready") { views().any { it.id == R.id.action_save } } + main { views().first { it.id == R.id.action_save }.performClick() } + val deadline = SystemClock.uptimeMillis() + 10000 + var saved: KeyboardLayout + do { + saved = repository.getFullLayout(id).first() + if (saved.keys.single().keyType == KeyType.FREE_FLICK) break + SystemClock.sleep(100) + } while (SystemClock.uptimeMillis() < deadline) + val key = saved.keys.single() + assertEquals(KeyType.FREE_FLICK, key.keyType) + assertEquals("edited😀", key.popupMapConfig!!.map(key.popupMapConfig!!.startMapId)!!.tapText) + assertEquals("editor-key", key.keyId) + } + } finally { repository.deleteLayoutConfirmed(id); db.close() } + } + + @Test fun actualCustomImeCommitsTapTextAndMapTransitionsInBothPresentations() = runBlocking { + val context = ins.targetContext + check(context.packageName.endsWith(".customfreeflicktest")) + val ime = "${context.packageName}/com.kazumaproject.markdownhelperkeyboard.ime_service.IMEService" + val oldIme = shell("settings get secure default_input_method") + val wasEnabled = shell("ime list -s").lines().contains(ime) + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + val db = AppModule.providesLearnDatabase(context) + val repository = KeyboardRepository(db.keyboardLayoutDao()) + val config = PopupKeyConfig("free", "base", listOf( + PopupMap("base", "Base", "tap😀", listOf( + PopupRegion("text", PopupBounds(-1.5f, -.5f, -.5f, .5f), PopupAction(text = "left")), + PopupRegion("switch", PopupBounds(.5f, -.5f, 1.5f, .5f), PopupAction(PopupActionType.SWITCH, targetMapId = "next")))), + PopupMap("next", "Next", "nextかな", listOf( + PopupRegion("back", PopupBounds(-.5f, -1.5f, .5f, -.5f), PopupAction(PopupActionType.BACK)))))) + val keys = (0 until 6).map { index -> + if (index == 4) KeyData("FREE", 1, 1, true, KeyAction.Text("tap😀"), keyType = KeyType.FREE_FLICK, + keyId = "free", popupMapConfig = config) + else KeyData("P$index", index / 3, index % 3, false, KeyAction.Text("p"), keyId = "plain$index") + } + val id = repository.saveLayout(KeyboardLayout(keys, emptyMap(), 3, 2), "Free Flick input verification", null) + try { + val stableId = repository.getLayoutsNotFlow().single { it.layoutId == id }.stableId + shell("ime enable $ime"); shell("ime set $ime") + for (presentation in PopupMapPresentation.entries) { + check(prefs.edit().clear().putString("keyboard_order_preference", "[\"CUSTOM\"]") + .putBoolean("save_last_used_keyboard", false).putBoolean("keyboard_floating_preference", false) + .putBoolean("remember_last_custom_keyboard_preference", true).putString("last_used_custom_keyboard_stable_id", stableId) + .putBoolean("live_conversion_preference", false).putBoolean("clipboard_preview_enable_preference", false) + .putBoolean(FreeFlickPreferences.NEAREST, false).putString(FreeFlickPreferences.PRESENTATION, presentation.preferenceValue).commit()) + ActivityScenario.launch(Intent(context, FastInputHostActivity::class.java)).use { scenario -> + scenario.onActivity { it.window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } + await("Custom keyboard visible") { views().filterIsInstance().any { it.text == "FREE" } } + SystemClock.sleep(500) + fun gesture(vararg points: Pair, cancel: Boolean = false) { + val bounds = key("FREE") + send(MotionEvent.ACTION_DOWN, bounds.exactCenterX(), bounds.exactCenterY()) + points.forEach { (x, y) -> send(MotionEvent.ACTION_MOVE, + bounds.exactCenterX() + x * bounds.width(), bounds.exactCenterY() + y * bounds.height()); SystemClock.sleep(40) } + val last = points.lastOrNull() ?: (0f to 0f) + send(if (cancel) MotionEvent.ACTION_CANCEL else MotionEvent.ACTION_UP, + bounds.exactCenterX() + last.first * bounds.width(), bounds.exactCenterY() + last.second * bounds.height()) + } + var expected = "" + fun text(value: String) { + expected += value + await("IME output $expected") { + var actual = ""; scenario.onActivity { actual = it.editText.text.toString() }; actual == expected + } + } + gesture(); text("tap😀") + gesture(-1f to 0f); text("left") + gesture(1f to 0f, 0f to 0f); text("nextかな") + gesture(1f to 0f, 0f to -1f, 0f to 0f); text("tap😀") + gesture(-1f to 0f, cancel = true); text("") + } + } + } finally { + repository.deleteLayoutConfirmed(id) + if (oldIme.isNotEmpty() && oldIme != "null") shell("ime set $oldIme") + if (!wasEnabled) shell("ime disable $ime") + db.close() + } + } +} diff --git a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/FastInputMatrixInstrumentedTest.kt b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/FastInputMatrixInstrumentedTest.kt index 634cb7e8a..a9bc2a71b 100644 --- a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/FastInputMatrixInstrumentedTest.kt +++ b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/FastInputMatrixInstrumentedTest.kt @@ -414,7 +414,6 @@ class FastInputMatrixInstrumentedTest { "default", "circle", "second-flick", - "third-flick", "sumire", ) val functionalCases = buildList { diff --git a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumireFlickRotationDeviceTest.kt b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumireFlickRotationDeviceTest.kt index 2ee45eb29..e0ebd3f71 100644 --- a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumireFlickRotationDeviceTest.kt +++ b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/SumireFlickRotationDeviceTest.kt @@ -19,7 +19,6 @@ import androidx.test.runner.lifecycle.Stage import com.kazumaproject.custom_keyboard.data.TfbiFlickRotation import com.kazumaproject.custom_keyboard.data.KeyType import com.kazumaproject.custom_keyboard.data.KeyboardLayout -import com.kazumaproject.custom_keyboard.data.SumireFlickInputMode import com.kazumaproject.custom_keyboard.view.FlickKeyboardView import com.kazumaproject.custom_keyboard.view.TfbiFlickDirection import com.kazumaproject.custom_keyboard.view.TfbiFlickDirection.* @@ -62,7 +61,6 @@ class SumireFlickRotationDeviceTest { .putString("sumire_input_method_preference", "flick") .putString("sumire_keyboard_style_preference", "second-flick") .putString(AppPreference.SUMIRE_FLICK_ROTATION_KEY, "default") - .putString(AppPreference.SUMIRE_FLICK_INPUT_MODE_KEY, "all") .putString(AppPreference.FLICK_TFBI_POPUP_PRESENTATION_KEY, "legacy_grid") .putString(AppPreference.TFBI_DIAGONAL_RECOGNITION_MODE_KEY, "legacy") .putInt(AppPreference.FLICK_SENSITIVITY_KEY, 1) @@ -106,25 +104,6 @@ class SumireFlickRotationDeviceTest { awaitText(expected, "$style $rotation $first/$second") } } - if (style == "third-flick") { - for (mode in listOf(SumireFlickInputMode.CONTRACTED, SumireFlickInputMode.VOICED, - SumireFlickInputMode.ALL)) { - instrumentation.runOnMainSync { - check(preferences.edit().putString(AppPreference.SUMIRE_FLICK_INPUT_MODE_KEY, - mode.preferenceValue).commit()) - } - awaitLayout(style, TfbiFlickRotation.COUNTERCLOCKWISE, mode) - val output = if (mode == SumireFlickInputMode.VOICED) { - flick(key("か"), style, LEFT, DOWN_LEFT) - "ぎ" - } else { - flick(key("か"), style, LEFT, UP, UP_LEFT) - "きゅう" - } - expected += output - awaitText(expected, "Active three-step input mode $mode") - } - } } } finally { instrumentation.runOnMainSync { @@ -210,8 +189,7 @@ class SumireFlickRotationDeviceTest { error("Sumire key $label did not become visible with stable screen bounds") } - private fun awaitLayout(style: String, rotation: TfbiFlickRotation, - mode: SumireFlickInputMode = SumireFlickInputMode.ALL) { + private fun awaitLayout(style: String, rotation: TfbiFlickRotation) { val deadline = SystemClock.uptimeMillis() + 15000 var ready = false while (!ready && SystemClock.uptimeMillis() < deadline) { @@ -229,7 +207,7 @@ class SumireFlickRotationDeviceTest { } if (!ready) SystemClock.sleep(50) } - assertTrue("Visible IME did not load $style / $rotation / $mode", ready) + assertTrue("Visible IME did not load $style / $rotation", ready) } private fun withHost(action: (FastInputHostActivity) -> Unit) { diff --git a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/ThreeStageFlickSuspensionDeviceTest.kt b/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/ThreeStageFlickSuspensionDeviceTest.kt deleted file mode 100644 index e93216055..000000000 --- a/app/src/androidTest/java/com/kazumaproject/markdownhelperkeyboard/ThreeStageFlickSuspensionDeviceTest.kt +++ /dev/null @@ -1,165 +0,0 @@ -package com.kazumaproject.markdownhelperkeyboard - -import android.accessibilityservice.AccessibilityServiceInfo -import android.content.Intent -import android.graphics.Rect -import android.os.ParcelFileDescriptor -import android.os.SystemClock -import android.view.InputDevice -import android.view.MotionEvent -import android.view.accessibility.AccessibilityNodeInfo -import androidx.preference.PreferenceManager -import androidx.test.core.app.ActivityScenario -import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.platform.app.InstrumentationRegistry -import com.kazumaproject.custom_keyboard.data.* -import com.kazumaproject.custom_keyboard.view.TfbiFlickDirection -import com.kazumaproject.markdownhelperkeyboard.ime_service.di.AppModule -import com.kazumaproject.markdownhelperkeyboard.repository.KeyboardRepository -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking -import org.junit.Assert.* -import org.junit.Assume.assumeTrue -import org.junit.Test -import org.junit.runner.RunWith - -/** Explicit opt-in is required because this exercises the real IME on an isolated emulator. */ -@RunWith(AndroidJUnit4::class) -class ThreeStageFlickSuspensionDeviceTest { - private val instrumentation = InstrumentationRegistry.getInstrumentation() - private val automation get() = instrumentation.uiAutomation - private fun shell(command: String) = ParcelFileDescriptor.AutoCloseInputStream( - automation.executeShellCommand(command)).bufferedReader().use { it.readText() } - - private fun key(label: String, floating: Boolean): AccessibilityNodeInfo { - fun collect(node: AccessibilityNodeInfo): List = listOf(node) + - (0 until node.childCount).flatMap { node.getChild(it)?.let(::collect).orEmpty() } - val surfaceId = if (floating) "custom_layout_floating" else "custom_layout_default" - val deadline = SystemClock.uptimeMillis() + 15000 - while (SystemClock.uptimeMillis() < deadline) { - val nodes = automation.windows.flatMap { it.root?.let(::collect).orEmpty() } - nodes.filter { it.isVisibleToUser && it.viewIdResourceName?.endsWith("/$surfaceId") == true } - .flatMap(::collect).firstOrNull { - it.isVisibleToUser && it.text?.toString()?.lineSequence()?.firstOrNull()?.trim() == label - }?.let { return it } - SystemClock.sleep(100) - } - error("Missing key $label on $surfaceId") - } - - private fun tap(node: AccessibilityNodeInfo, hold: Boolean = false) { - val bounds = Rect().also(node::getBoundsInScreen) - val start = SystemClock.uptimeMillis() - for (action in listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP)) { - val event = MotionEvent.obtain(start, SystemClock.uptimeMillis(), action, - bounds.exactCenterX(), bounds.exactCenterY(), 0) - event.source = InputDevice.SOURCE_TOUCHSCREEN - try { check(automation.injectInputEvent(event, true)) } finally { event.recycle() } - SystemClock.sleep(if (hold && action == MotionEvent.ACTION_DOWN) 600 else 50) - } - } - - private fun awaitText(scenario: ActivityScenario, expected: String) { - val deadline = SystemClock.uptimeMillis() + 5000 - var text = "" - do { - scenario.onActivity { text = it.editText.text.toString() } - if (text == expected) return - SystemClock.sleep(50) - } while (SystemClock.uptimeMillis() < deadline) - assertEquals(expected, text) - } - - @Test fun threeStageStaysSuspendedAndTwoStepWorksOnDockedAndFloatingIme() = runBlocking { - assumeTrue(InstrumentationRegistry.getArguments().getString("suspensionIsolatedEmulator") == "true" && - shell("getprop ro.kernel.qemu").trim() == "1") - val context = instrumentation.targetContext - val ime = "${context.packageName}/com.kazumaproject.markdownhelperkeyboard.ime_service.IMEService" - val oldIme = shell("settings get secure default_input_method").trim() - val wasEnabled = shell("ime list -s").lineSequence().any { it.trim() == ime } - val prefs = PreferenceManager.getDefaultSharedPreferences(context) - val originalPrefs = prefs.all.toMap() - val db = AppModule.providesLearnDatabase(context) - val repository = KeyboardRepository(db.keyboardLayoutDao()) - var createdId: Long? = null - try { - automation.serviceInfo = automation.serviceInfo.apply { - flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS or - AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS - } - val blockedTypes = listOf(KeyType.HIERARCHICAL_FLICK) - val blocked = blockedTypes.mapIndexed { index, type -> - KeyData("PausedKey$index", 0, index, true, action = KeyAction.Text("blocked"), - keyType = type, keyId = "paused-key$index") - } - val ordinary = KeyData("WorkingKey", 0, 1, false, action = KeyAction.Text("あ"), keyId = "working-key") - val twoStep = KeyData("TwoStepKey", 0, 2, true, keyType = KeyType.TWO_STEP_FLICK, keyId = "two-step") - val sticky = KeyData("StickyKey", 0, 3, true, keyType = KeyType.STICKY_TWO_STEP_FLICK, keyId = "sticky") - val twoStepMaps = mapOf( - "two-step" to mapOf(TfbiFlickDirection.TAP to mapOf(TfbiFlickDirection.TAP to "い")), - "sticky" to mapOf(TfbiFlickDirection.TAP to mapOf(TfbiFlickDirection.TAP to "う")) - ) - val definition = """{"normal":{"TAP":{"type":"input","output":"preserved"}}}""" - createdId = repository.saveLayout(KeyboardLayout(blocked + ordinary + twoStep + sticky, emptyMap(), 4, 1, - twoStepFlickKeyMaps = twoStepMaps, - preservedFlickDefinitions = mapOf("paused-key0" to definition)), "Suspension device verification", null) - val saved = repository.getFullLayout(createdId!!).first() - val stableId = repository.getLayoutsNotFlow().single { it.layoutId == createdId }.stableId - shell("ime enable $ime"); shell("ime set $ime") - for (floating in listOf(false, true)) { - check(prefs.edit().putString("keyboard_order_preference", "[\"CUSTOM\"]") - .putBoolean("save_last_used_keyboard", false) - .putBoolean("remember_last_custom_keyboard_preference", true) - .putString("last_used_custom_keyboard_stable_id", stableId) - .putBoolean("keyboard_floating_preference", floating) - .putBoolean("live_conversion_preference", false).commit()) - ActivityScenario.launch(Intent(context, FastInputHostActivity::class.java)).use { scenario -> - scenario.onActivity { it.restartEditorInput(clearText = true) } - blockedTypes.indices.forEach { index -> - val stopped = key("PausedKey$index", floating) - assertFalse(stopped.isEnabled) - tap(stopped); tap(stopped); tap(stopped, hold = true) - awaitText(scenario, "") - } - tap(key("WorkingKey", floating)) - awaitText(scenario, "あ") - tap(key("TwoStepKey", floating)) - awaitText(scenario, "あい") - tap(key("StickyKey", floating)) - awaitText(scenario, "あいう") - } - assertEquals(saved.preservedFlickDefinitions, repository.getFullLayout(createdId!!).first().preservedFlickDefinitions) - check(prefs.edit().putString("keyboard_order_preference", "[\"SUMIRE\"]") - .putString("sumire_keyboard_style_preference", "third-flick") - .putString("sumire_input_method_preference", "toggle").commit()) - ActivityScenario.launch(Intent(context, FastInputHostActivity::class.java)).use { scenario -> - scenario.onActivity { it.restartEditorInput(clearText = true) } - tap(key("あ", floating)) - awaitText(scenario, "あ") - } - assertEquals("third-flick", prefs.getString("sumire_keyboard_style_preference", null)) - check(prefs.edit().putString("sumire_keyboard_style_preference", "second-flick").commit()) - ActivityScenario.launch(Intent(context, FastInputHostActivity::class.java)).use { scenario -> - scenario.onActivity { it.restartEditorInput(clearText = true) } - tap(key("あ", floating)) - awaitText(scenario, "あ") - } - } - } finally { - createdId?.let { repository.deleteLayoutConfirmed(it) } - prefs.edit().clear().apply { - for ((key, value) in originalPrefs) when (value) { - is String -> putString(key, value) - is Boolean -> putBoolean(key, value) - is Int -> putInt(key, value) - is Long -> putLong(key, value) - is Float -> putFloat(key, value) - is Set<*> -> putStringSet(key, value.filterIsInstance().toSet()) - } - }.commit() - if (oldIme.isNotEmpty() && oldIme != "null") shell("ime set $oldIme") - if (!wasEnabled) shell("ime disable $ime") - db.close() - } - } -} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/data/KeyDefinition.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/data/KeyDefinition.kt index 23e8c3756..3f5b97e8c 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/data/KeyDefinition.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/data/KeyDefinition.kt @@ -46,6 +46,6 @@ data class KeyDefinition( val doubleTapAction: String? = null, val doubleTapPolicy: String? = null, val textInputBehavior: String = KeyTextInputBehavior.NORMAL.dbValue, - val hierarchicalFlickJson: String? = null, + val popupMapConfigJson: String? = null, val qwertyConfigJson: String? = null ) diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardBackupPipeline.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardBackupPipeline.kt index ca8a13ac0..c0c70a1d7 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardBackupPipeline.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardBackupPipeline.kt @@ -1,5 +1,6 @@ package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.import_export +import com.kazumaproject.custom_keyboard.data.PopupKeyConfigCodec import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.JsonObject @@ -295,6 +296,12 @@ object KeyboardBackupNormalizer { "Invalid QWERTY configuration for key ${keyIndex + 1}") return@mapIndexedNotNull null } + val freeFlickConfig = PopupKeyConfigCodec.decode(keyDto.freeFlick?.toString()) + if (keyDto.keyType == KeyType.FREE_FLICK.name && freeFlickConfig == null) { + errors += KeyboardLayoutImportError.ValidationFailed(layoutIndex, + "Invalid Free Flick configuration for key ${keyIndex + 1}") + return@mapIndexedNotNull null + } val identifier = keyDto.keyIdentifier ?.takeIf { it.isNotBlank() && it !in usedKeyIdentifiers } ?: UUID.randomUUID().toString().also { @@ -345,10 +352,6 @@ object KeyboardBackupNormalizer { ).serializedName } - // Preserve suspended definitions verbatim without interpreting input stages. - val hierarchicalFlickJson = keyDto.hierarchicalFlick - ?.takeUnless { it.isJsonNull }?.toString() - val normalizedKey = KeyDefinition( keyId = 0, ownerLayoutId = 0, @@ -383,7 +386,8 @@ object KeyboardBackupNormalizer { .dbValue, doubleTapAction = normalizedDoubleTapAction, doubleTapPolicy = normalizedDoubleTapPolicy, - hierarchicalFlickJson = hierarchicalFlickJson, + popupMapConfigJson = freeFlickConfig?.takeIf { keyDto.keyType == KeyType.FREE_FLICK.name } + ?.copy(keyId = identifier)?.let(PopupKeyConfigCodec::encode), qwertyConfigJson = qwertyConfig?.let(QwertyKeyConfigCodec::encode), textInputBehavior = KeyTextInputBehavior .fromDbValue(keyDto.textInputBehavior) diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutExportDtos.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutExportDtos.kt index ab8638258..63e0a8c5f 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutExportDtos.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutExportDtos.kt @@ -113,8 +113,8 @@ data class KeyDefinitionDto( val specialKeyColorStyle: String? = null, @SerializedName("textInputBehavior") val textInputBehavior: String? = null, - @SerializedName("hierarchicalFlick") - val hierarchicalFlick: JsonElement? = null, + @SerializedName("freeFlick") + val freeFlick: JsonElement? = null, @SerializedName("qwerty") val qwerty: JsonElement? = null ) diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonExporter.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonExporter.kt index a99d9f7c0..b0e9a8717 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonExporter.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonExporter.kt @@ -120,7 +120,7 @@ internal fun KeyWithFlicks.toExportDto(): KeyWithFlicksExportDto { rowSpanUnits = this.key.rowSpanUnits, columnSpanUnits = this.key.columnSpanUnits, specialKeyColorStyle = this.key.specialKeyColorStyle, - hierarchicalFlick = this.key.hierarchicalFlickJson?.let { + freeFlick = this.key.popupMapConfigJson?.let { JsonParser.parseString(it) }, qwerty = this.key.qwertyConfigJson?.let(JsonParser::parseString), diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonImporter.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonImporter.kt index b76c7ad20..72ecd9274 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonImporter.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonImporter.kt @@ -24,7 +24,7 @@ object KeyboardLayoutJsonImporter { /** * 想定する最新の schemaVersion。 */ - const val LATEST_SCHEMA_VERSION: Int = 6 + const val LATEST_SCHEMA_VERSION: Int = 7 internal val gson: Gson by lazy { GsonBuilder() diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickEditorDialog.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickEditorDialog.kt new file mode 100644 index 000000000..776d13984 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickEditorDialog.kt @@ -0,0 +1,51 @@ +package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui + +import android.app.Dialog +import android.os.Bundle +import android.view.KeyEvent +import android.view.ViewGroup +import android.widget.FrameLayout +import androidx.core.os.bundleOf +import androidx.fragment.app.DialogFragment +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.sumire_popup.PopupMapEditorFragment + +/** Edits a key draft without leaving the key editor or writing a built-in layout. */ +class CustomFreeFlickEditorDialog : DialogFragment() { + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val host = FrameLayout(requireContext()).apply { id = R.id.custom_free_flick_editor_host } + childFragmentManager.setFragmentResultListener(RESULT, this) { _, result -> + parentFragmentManager.setFragmentResult(RESULT, result) + } + return Dialog(requireContext(), com.google.android.material.R.style.Theme_Material3_DayNight_NoActionBar).apply { + setContentView(host) + setOnKeyListener { _, keyCode, event -> + if (keyCode == KeyEvent.KEYCODE_BACK) { + if (event.action == KeyEvent.ACTION_UP) { + (childFragmentManager.findFragmentById(host.id) as? PopupMapEditorFragment)?.leaveEditor() + } + true + } else false + } + setCanceledOnTouchOutside(false) + } + } + + override fun onStart() { + super.onStart() + dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + if (childFragmentManager.findFragmentById(R.id.custom_free_flick_editor_host) == null) { + childFragmentManager.beginTransaction().replace(R.id.custom_free_flick_editor_host, + PopupMapEditorFragment().apply { arguments = this@CustomFreeFlickEditorDialog.arguments }).commitNow() + } + } + + companion object { + const val ARG_CONFIG = "customFreeFlickConfig" + const val ARG_KEY_LABEL = "customFreeFlickKeyLabel" + const val RESULT = "customFreeFlickResult" + fun create(json: String, keyLabel: String = "") = CustomFreeFlickEditorDialog().apply { + arguments = bundleOf(ARG_CONFIG to json, ARG_KEY_LABEL to keyLabel) + } + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyEditorFragment.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyEditorFragment.kt index f1c5cc157..6e291e6a4 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyEditorFragment.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyEditorFragment.kt @@ -1,6 +1,7 @@ package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui -import com.kazumaproject.custom_keyboard.data.CustomFlickSuspension +import com.kazumaproject.custom_keyboard.data.PopupKeyConfig +import com.kazumaproject.custom_keyboard.data.PopupKeyConfigCodec import android.Manifest import android.graphics.Bitmap import android.graphics.BitmapFactory @@ -107,6 +108,8 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { private var _binding: FragmentKeyEditorBinding? = null private val binding get() = _binding!! + private var freeFlickDraft: PopupKeyConfig? = null + private var restoredInputStyleId: Int? = null private var currentKeyData: KeyData? = null private var qwertyDraftInitialized = false private var editingKeyIdentifier: String? = null @@ -188,6 +191,16 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { restoredEditingKeyIdentifier = savedInstanceState?.getString("qwertyEditingKey") savedQwertyDraft = QwertyKeyConfigCodec.decode(savedInstanceState?.getString("qwertyDraft"), requireOutput = false) binding.qwertyKeyEditor.onChanged = { updateDoneButtonState() } + freeFlickDraft = PopupKeyConfigCodec.decode(savedInstanceState?.getString("freeFlickDraft")) ?: freeFlickDraft + restoredInputStyleId = savedInstanceState?.getInt("freeFlickInputStyle")?.takeIf { it != View.NO_ID } + childFragmentManager.setFragmentResultListener(CustomFreeFlickEditorDialog.RESULT, viewLifecycleOwner) { _, result -> + freeFlickDraft = PopupKeyConfigCodec.decode(result.getString(CustomFreeFlickEditorDialog.ARG_CONFIG)) + updateDoneButtonState() + } + binding.editFreeFlickMap.setOnClickListener { + val config = ensureFreeFlickDraft() ?: return@setOnClickListener + CustomFreeFlickEditorDialog.create(PopupKeyConfigCodec.encode(config), binding.keyLabelEdittext.text.toString()).show(childFragmentManager, "freeFlickEditor") + } setupToolbarAndMenu() setupGridEditor() setupUIListeners() @@ -349,6 +362,7 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { binding.outputModeChipGroup.isVisible = !isSpecialKey if (isSpecialKey) { + binding.editFreeFlickMap.isVisible = false // Default category = single if none selected yet if (binding.specialCategoryChipGroup.checkedChipId == View.NO_ID) { binding.specialCategoryChipGroup.check(R.id.chip_special_single) @@ -603,8 +617,36 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { } } + private fun ensureFreeFlickDraft(): PopupKeyConfig? { + val key = currentKeyData ?: return null + if (freeFlickDraft == null) { + val tap = currentFlickItems.firstOrNull { it.direction == FlickDirection.TAP }?.output + ?.takeIf { it.isNotEmpty() } ?: textOutputFromAction(key.action).ifEmpty { key.label } + freeFlickDraft = key.popupMapConfig ?: PopupKeyConfigCodec.create(key.keyId ?: return null, tap) + } + return freeFlickDraft + } + private fun handleInputStyleUi() { val selectedStyle = binding.inputStyleChipGroup.checkedChipId + val isFreeFlick = selectedStyle == R.id.chip_free_flick + binding.editFreeFlickMap.isVisible = isFreeFlick + if (isFreeFlick) { + ensureFreeFlickDraft() + binding.qwertyKeyEditor.isVisible = false + binding.keyLabelLayout.isVisible = true + binding.flickGridEditorView.isVisible = false + binding.circularFlickEditorGroup.isVisible = false + binding.specialFlickEditorGroup.isVisible = false + binding.textSelectedDirection.isVisible = false + binding.textCharInputLayout.isVisible = false + binding.textOutputModeTitle.isVisible = false + binding.outputModeChipGroup.isVisible = false + binding.customKeyboardTargetLayout.isVisible = false + currentCellMode = null + updateIconOverrideVisibility() + return + } val isQwerty = selectedStyle == R.id.chip_qwerty binding.qwertyKeyEditor.isVisible = isQwerty if (isQwerty) { @@ -1138,6 +1180,14 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { if (outputEditMode != OutputEditMode.TOGGLE) { binding.textCharInputLayout.error = null } + if (binding.keyTypeChipGroup.checkedChipId == R.id.chip_normal && + binding.inputStyleChipGroup.checkedChipId == R.id.chip_free_flick) { + binding.buttonDone.isEnabled = ensureFreeFlickDraft()?.let { config -> + com.kazumaproject.custom_keyboard.data.PopupMapValidator.conflicts(config).isEmpty() && + config.maps.any { map -> map.tapText.isNotEmpty() || map.regions.any { it.action.text.isNotEmpty() } } + } == true + return + } if (binding.keyTypeChipGroup.checkedChipId == R.id.chip_normal && binding.inputStyleChipGroup.checkedChipId == R.id.chip_qwerty) { binding.buttonDone.isEnabled = binding.qwertyKeyEditor.isInputValid @@ -1236,7 +1286,7 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { // legacy KeyData.keyId. selectedKeyIdentifier carries item.id for // flexible layouts (so half-cell keys and editor-created keys // resolve correctly even when keyData.keyId is null/blank). - val selectedId = state.selectedKeyIdentifier ?: restoredEditingKeyIdentifier.takeIf { savedQwertyDraft != null } + val selectedId = state.selectedKeyIdentifier ?: restoredEditingKeyIdentifier.takeIf { savedQwertyDraft != null || freeFlickDraft != null } editingKeyIdentifier = selectedId val selectedKeyItem = selectedId?.let { id -> state.layout.items @@ -1256,14 +1306,6 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { } val key = currentKeyData!! - if (CustomFlickSuspension.isSuspended(key.keyType)) { - AlertDialog.Builder(requireContext()) - .setMessage(com.kazumaproject.core.R.string.custom_flick_suspended) - .setPositiveButton(android.R.string.ok) { _, _ -> findNavController().popBackStack() } - .setOnCancelListener { findNavController().popBackStack() } - .show() - return@launch - } selectedIconRef = key.icon?.takeIf { it.isOverride() } originalIconRef = selectedIconRef key.doubleTapBinding @@ -1361,7 +1403,12 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { outputEditMode = OutputEditMode.NORMAL // Restore the supported editor. - if (key.keyType == KeyType.QWERTY || savedQwertyDraft != null) { + if (freeFlickDraft != null && restoredInputStyleId != null) { + binding.inputStyleChipGroup.check(restoredInputStyleId!!) + } else if (key.keyType == KeyType.FREE_FLICK) { + freeFlickDraft = freeFlickDraft ?: key.popupMapConfig + binding.inputStyleChipGroup.check(R.id.chip_free_flick) + } else if (key.keyType == KeyType.QWERTY || savedQwertyDraft != null) { binding.inputStyleChipGroup.check(R.id.chip_qwerty) } else if (key.keyType == KeyType.TWO_STEP_FLICK) { binding.inputStyleChipGroup.check(R.id.chip_two_step_flick) @@ -1831,7 +1878,6 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { private fun onDone() { val originalKey = currentKeyData ?: return - if (CustomFlickSuspension.isSuspended(originalKey.keyType)) return if ( binding.keyTypeChipGroup.checkedChipId == R.id.chip_normal && @@ -1969,7 +2015,15 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { val isFlickLongPress = binding.inputStyleChipGroup.checkedChipId == R.id.chip_flick_long_press - if (binding.inputStyleChipGroup.checkedChipId == R.id.chip_qwerty) { + if (binding.inputStyleChipGroup.checkedChipId == R.id.chip_free_flick) { + val config = ensureFreeFlickDraft() ?: return + if (!binding.buttonDone.isEnabled) return + newKeyType = KeyType.FREE_FLICK + newLabel = binding.keyLabelEdittext.text.toString().ifEmpty { config.map(config.startMapId)!!.tapText } + newAction = KeyAction.Text(config.map(config.startMapId)!!.tapText) + newLongPressFlickMap = emptyMap() + newTwoStepLongPressMap = emptyMap() + } else if (binding.inputStyleChipGroup.checkedChipId == R.id.chip_qwerty) { if (!binding.qwertyKeyEditor.isInputValid) return newQwertyConfig = binding.qwertyKeyEditor.config newKeyType = KeyType.QWERTY @@ -2132,6 +2186,7 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { // IMPORTANT: special flick should still be flickable (KeyType != NORMAL) isFlickable = newKeyType !in setOf(KeyType.NORMAL, KeyType.QWERTY), qwertyConfig = newQwertyConfig, + popupMapConfig = freeFlickDraft?.takeIf { newKeyType == KeyType.FREE_FLICK }, drawableResId = newDrawableResId, icon = savedIconRef, rowSpan = if (isFlexibleSizeEditing) { @@ -2191,6 +2246,11 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { override fun onSaveInstanceState(outState: Bundle) { + freeFlickDraft?.let { outState.putString("freeFlickDraft", PopupKeyConfigCodec.encode(it)) } + if (_binding != null && freeFlickDraft != null) { + outState.putString("qwertyEditingKey", editingKeyIdentifier) + outState.putInt("freeFlickInputStyle", binding.inputStyleChipGroup.checkedChipId) + } if (_binding != null && binding.keyTypeChipGroup.checkedChipId == R.id.chip_normal && binding.inputStyleChipGroup.checkedChipId == R.id.chip_qwerty) { outState.putString("qwertyDraft", QwertyKeyConfigCodec.encode(binding.qwertyKeyEditor.config)) 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 0b40a1cae..99b3c0faa 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 @@ -1,6 +1,5 @@ package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui -import com.kazumaproject.custom_keyboard.data.CustomFlickSuspension import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.kazumaproject.custom_keyboard.data.CircularFlickDirection @@ -793,7 +792,6 @@ class KeyboardEditorViewModel @Inject constructor( twoStepFlickKeyMaps = twoStepFlickKeyMaps.filterKeys { it !in removedKeyIds }, longPressFlickKeyMaps = longPressFlickKeyMaps.filterKeys { it !in removedKeyIds }, twoStepLongPressKeyMaps = twoStepLongPressKeyMaps.filterKeys { it !in removedKeyIds }, - preservedFlickDefinitions = preservedFlickDefinitions.filterKeys { it !in removedKeyIds } ) } @@ -1014,7 +1012,6 @@ class KeyboardEditorViewModel @Inject constructor( flexibleRowSpanUnits: Int? = null, flexibleColumnSpanUnits: Int? = null ): Boolean { - if (CustomFlickSuspension.isSuspended(newKeyData.keyType)) return false val keyId = newKeyData.keyId ?: run { Timber.e("FATAL: updateKeyAndMappings received a KeyData with a null keyId!") return false @@ -1025,9 +1022,6 @@ class KeyboardEditorViewModel @Inject constructor( val layout = currentState.layout val oldKeyData = layout.keys.find { it.keyId == keyId } ?: return@update currentState - val finalHierarchicalMaps = layout.preservedFlickDefinitions.toMutableMap() - if (CustomFlickSuspension.isSuspended(oldKeyData.keyType)) return@update currentState - finalHierarchicalMaps.remove(keyId) val finalFlickMaps = layout.flickKeyMaps.toMutableMap() val finalCircularFlickMaps = layout.circularFlickKeyMaps.toMutableMap() val finalTwoStepMaps = layout.twoStepFlickKeyMaps.toMutableMap() @@ -1119,7 +1113,6 @@ class KeyboardEditorViewModel @Inject constructor( finalTwoStepMaps.remove(crushedKeyId) finalLongPressFlickMaps.remove(crushedKeyId) finalTwoStepLongPressMaps.remove(crushedKeyId) - finalHierarchicalMaps.remove(crushedKeyId) } val canonicalLayout = layout.copyWithItems(updatedItems).withCanonicalFlexibleBounds() @@ -1133,7 +1126,6 @@ class KeyboardEditorViewModel @Inject constructor( } val newLayout = canonicalLayout.copy( - preservedFlickDefinitions = finalHierarchicalMaps, flickKeyMaps = finalFlickMaps, circularFlickKeyMaps = finalCircularFlickMaps, twoStepFlickKeyMaps = finalTwoStepMaps, @@ -1166,11 +1158,9 @@ class KeyboardEditorViewModel @Inject constructor( finalTwoStepMaps.remove(it) finalLongPressFlickMaps.remove(it) finalTwoStepLongPressMaps.remove(it) - finalHierarchicalMaps.remove(it) } val newLayout = layout.copyWithKeys(finalKeys).copy( - preservedFlickDefinitions = finalHierarchicalMaps, flickKeyMaps = finalFlickMaps, circularFlickKeyMaps = finalCircularFlickMaps, twoStepFlickKeyMaps = finalTwoStepMaps, @@ -1198,7 +1188,7 @@ class KeyboardEditorViewModel @Inject constructor( finalTwoStepLongPressMaps: MutableMap>> ) { when (newKeyData.keyType) { - KeyType.HIERARCHICAL_FLICK -> { + KeyType.FREE_FLICK -> { finalFlickMaps.remove(keyId) finalCircularFlickMaps.remove(keyId) finalLongPressFlickMaps.remove(keyId) @@ -1650,12 +1640,6 @@ class KeyboardEditorViewModel @Inject constructor( if (newKeyId != null) newKeyId to flickActions else null }.toMap() - val reKeyedHierarchicalMaps = keysWithEnsuredIds.mapNotNull { key -> - val definition = templateLayout.preservedFlickDefinitions[key.keyId] - ?: templateLayout.preservedFlickDefinitions[key.label] - definition?.let { key.keyId!! to it } - }.toMap() - val reKeyedTwoStepMaps = templateLayout.twoStepFlickKeyMaps.mapNotNull { (labelKey, map) -> val newKeyId = labelToIdMap[labelKey] if (newKeyId != null) newKeyId to map else null @@ -1696,7 +1680,6 @@ class KeyboardEditorViewModel @Inject constructor( } val finalLayout = finalLayoutBase.copy( - preservedFlickDefinitions = reKeyedHierarchicalMaps, flickKeyMaps = reKeyedFlickMaps, circularFlickKeyMaps = reKeyedCircularFlickMaps, twoStepFlickKeyMaps = reKeyedTwoStepMaps, diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/database/AppDatabase.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/database/AppDatabase.kt index 674bc28ab..baf060a7a 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/database/AppDatabase.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/database/AppDatabase.kt @@ -84,7 +84,7 @@ import com.kazumaproject.markdownhelperkeyboard.zeroquery.custom.CustomZeroQuery CustomZeroQueryEntry::class, TextMacro::class, ], - version = 50, + version = 51, exportSchema = false ) @TypeConverters( @@ -116,6 +116,45 @@ abstract class AppDatabase : RoomDatabase() { abstract fun textMacroDao(): TextMacroDao companion object { + val MIGRATION_50_51 = object : Migration(50, 51) { + override fun migrate(db: SupportSQLiteDatabase) { + // Rebuild for SQLite versions before DROP COLUMN (Android 7+). + // Dropping the parent cascades, so preserve all five mapping tables first. + val mappingTables = listOf("flick_mappings", "circular_flick_mappings", + "two_step_flick_mappings", "long_press_flick_mappings", "two_step_long_press_mappings") + mappingTables.forEach { table -> + db.execSQL("CREATE TEMP TABLE `backup_$table` AS SELECT * FROM `$table`") + } + val columns = mutableListOf() + val definitions = mutableListOf() + db.query("PRAGMA table_info(`key_definitions`)").use { cursor -> + while (cursor.moveToNext()) { + val name = cursor.getString(1) + if (name == "hierarchicalFlickJson") continue + columns += "`$name`" + definitions += buildString { + append("`$name` ${cursor.getString(2)}") + if (cursor.getInt(5) != 0) append(" PRIMARY KEY AUTOINCREMENT") + if (cursor.getInt(3) != 0) append(" NOT NULL") + if (!cursor.isNull(4)) append(" DEFAULT ${cursor.getString(4)}") + } + } + } + definitions += "`popupMapConfigJson` TEXT" + definitions += "FOREIGN KEY(`ownerLayoutId`) REFERENCES `keyboard_layouts`(`layoutId`) ON DELETE CASCADE ON UPDATE NO ACTION" + db.execSQL("CREATE TABLE `key_definitions_new` (${definitions.joinToString()})") + db.execSQL("INSERT INTO `key_definitions_new` (${columns.joinToString()}) SELECT ${columns.joinToString()} FROM `key_definitions`") + db.execSQL("UPDATE `key_definitions_new` SET `keyType` = 'NORMAL' WHERE `keyType` = 'HIERARCHICAL_FLICK'") + db.execSQL("DROP TABLE `key_definitions`") + db.execSQL("ALTER TABLE `key_definitions_new` RENAME TO `key_definitions`") + db.execSQL("CREATE INDEX `index_key_definitions_ownerLayoutId` ON `key_definitions` (`ownerLayoutId`)") + mappingTables.forEach { table -> + db.execSQL("INSERT OR REPLACE INTO `$table` SELECT * FROM `backup_$table`") + db.execSQL("DROP TABLE `backup_$table`") + } + } + } + val MIGRATION_49_50 = object : Migration(49, 50) { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL("ALTER TABLE `key_definitions` ADD COLUMN `qwertyConfigJson` TEXT") 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 fc4aa7622..eb99631a2 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 @@ -208,7 +208,6 @@ import com.kazumaproject.custom_keyboard.data.KeyCharacterCase import com.kazumaproject.custom_keyboard.data.KeyboardInputMode import com.kazumaproject.custom_keyboard.data.KeyboardLayout import com.kazumaproject.custom_keyboard.data.KeyboardLayoutUsageMode -import com.kazumaproject.custom_keyboard.data.SumireFlickInputMode import com.kazumaproject.custom_keyboard.data.TfbiFlickRotation import com.kazumaproject.custom_keyboard.layout.KeyboardDefaultLayouts import com.kazumaproject.custom_keyboard.layout.KeyboardDefaultLayouts.DeleteKeyFlickSettings @@ -1044,7 +1043,6 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, AppPreference.FLICK_THRESHOLD_SHAPE_KEY, AppPreference.TFBI_DIAGONAL_RECOGNITION_MODE_KEY, AppPreference.SUMIRE_FLICK_ROTATION_KEY, - AppPreference.SUMIRE_FLICK_INPUT_MODE_KEY, AppPreference.SUMIRE_MODE_KEY_HIGHLIGHT_KEY, AppPreference.FLICK_EDITOR_PREVIEW_KEY, AppPreference.TENKEY_SHOW_FLICK_POPUP_KEY, @@ -2361,7 +2359,6 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, private var sumireInputKeyLayoutType: String? = "toggle" private var sumireInputStyle: String? = "default" private var sumireFlickRotation = TfbiFlickRotation.DEFAULT - private var sumireFlickInputMode = SumireFlickInputMode.ALL private var sumireModeKeyHighlight = false private var candidateColumns: String? = "1" private var candidateColumnsLandscape: String? = "1" @@ -2403,7 +2400,6 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, private var learningPausedForSession: Boolean = false private var circularFlickWindowScale: Float? = 1.0f private var circularFlickDirectionCount: Int? = 4 - private var hierarchicalFlickModeSwitchAngleMargin: Int? = 20 private var customKeyBorderWidth: Int? = 1 @@ -4457,9 +4453,6 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, val latestSumireFlickRotation = appPreference.sumire_flick_rotation_preference val sumireFlickRotationChanged = sumireFlickRotation != latestSumireFlickRotation sumireFlickRotation = latestSumireFlickRotation - val latestSumireFlickInputMode = appPreference.sumire_flick_input_mode_preference - val sumireFlickInputModeChanged = sumireFlickInputMode != latestSumireFlickInputMode - sumireFlickInputMode = latestSumireFlickInputMode val latestSumireModeKeyHighlight = appPreference.sumire_mode_key_highlight_preference val sumireModeKeyHighlightChanged = sumireModeKeyHighlight != latestSumireModeKeyHighlight sumireModeKeyHighlight = latestSumireModeKeyHighlight @@ -4560,9 +4553,7 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, syncKeyPopupVisibility() applyIndependentMultiTouchPreference() syncCustomKeyboardHitTestPreference() - if (sumireModeKeyHighlightChanged || sumireFlickRotationChanged || - (sumireFlickInputModeChanged && sumireInputStyle == "third-flick") - ) { + if (sumireModeKeyHighlightChanged || sumireFlickRotationChanged) { refreshSumireLayouts(hiraganaOnly = !sumireModeKeyHighlightChanged) } } @@ -4803,9 +4794,6 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, sumireFlickRotation = TfbiFlickRotation.fromPreferenceValue( preferences.tfbiFlickRotationPreferenceValue ) - sumireFlickInputMode = SumireFlickInputMode.fromPreferenceValue( - preferences.sumireFlickInputModePreferenceValue - ) sumireModeKeyHighlight = preferences.sumireModeKeyHighlight candidateColumns = preferences.candidateColumns candidateColumnsLandscape = preferences.candidateColumnsLandscape @@ -5047,7 +5035,6 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, preferences.learnDictionaryPredictionCandidateLimit.coerceIn(1, 8) circularFlickWindowScale = preferences.circularFlickWindowScale circularFlickDirectionCount = preferences.circularFlickDirectionCount - hierarchicalFlickModeSwitchAngleMargin = preferences.hierarchicalFlickModeSwitchAngleMargin customKeyBorderWidth = preferences.customKeyBorderWidth qwertySwitchNumberKeyWithoutNumberPreference = preferences.qwertySwitchNumberKeyWithoutNumberPreference @@ -11500,7 +11487,6 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, inputStyle = sumireInputStyle ?: "default", deleteKeyFlickSettings = currentDeleteKeyFlickSettings(), tfbiFlickRotation = sumireFlickRotation, - sumireFlickInputMode = sumireFlickInputMode, highlightSelectedMode = sumireModeKeyHighlight ), mode diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/ImePreferencesSnapshot.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/ImePreferencesSnapshot.kt index 95c7f72f7..2707f7df2 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/ImePreferencesSnapshot.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/ImePreferencesSnapshot.kt @@ -103,7 +103,6 @@ data class ImePreferencesSnapshot( val flickThresholdShapePreferenceValue: String, val tfbiDiagonalRecognitionModePreferenceValue: String, val tfbiFlickRotationPreferenceValue: String, - val sumireFlickInputModePreferenceValue: String, val sumireModeKeyHighlight: Boolean, val longPressTimeoutPreferenceValue: Int, val qwertyShowIMEButtonPreference: Boolean, @@ -263,7 +262,6 @@ data class ImePreferencesSnapshot( val learnDictionaryPredictionCandidateLimit: Int, val circularFlickWindowScale: Float, val circularFlickDirectionCount: Int, - val hierarchicalFlickModeSwitchAngleMargin: Int, val customKeyBorderWidth: Int, val qwertySwitchNumberKeyWithoutNumberPreference: Boolean, val customRomajiZenkakuConversionEnablePreference: Boolean, @@ -453,8 +451,6 @@ data class ImePreferencesSnapshot( appPreference.tfbi_diagonal_recognition_mode_preference.preferenceValue, tfbiFlickRotationPreferenceValue = appPreference.sumire_flick_rotation_preference.preferenceValue, - sumireFlickInputModePreferenceValue = - appPreference.sumire_flick_input_mode_preference.preferenceValue, sumireModeKeyHighlight = appPreference.sumire_mode_key_highlight_preference, longPressTimeoutPreferenceValue = appPreference.long_press_timeout_preference ?: 300, @@ -513,10 +509,8 @@ data class ImePreferencesSnapshot( keySoundVolumePercent = appPreference.key_sound_volume_percent_preference ?: 0, sumireInputKeyType = appPreference.sumire_input_selection_preference ?: "flick-default", - sumireInputKeyLayoutType = if (appPreference.sumire_keyboard_style == "third-flick") "flick" - else appPreference.sumire_input_method, - sumireInputStyle = if (appPreference.sumire_keyboard_style == "third-flick") "default" - else appPreference.sumire_keyboard_style, + sumireInputKeyLayoutType = appPreference.sumire_input_method, + sumireInputStyle = appPreference.sumire_keyboard_style, candidateColumns = appPreference.candidate_column_preference, candidateColumnsLandscape = appPreference.candidate_column_landscape_preference, candidateTabVisibility = appPreference.candidate_tab_preference, @@ -783,8 +777,6 @@ data class ImePreferencesSnapshot( appPreference.learn_dictionary_prediction_candidate_limit_preference, circularFlickWindowScale = appPreference.circular_flickWindow_scale, circularFlickDirectionCount = appPreference.circularFlickDirectionCount, - hierarchicalFlickModeSwitchAngleMargin = - appPreference.hierarchical_flick_mode_switch_angle_margin_preference, customKeyBorderWidth = appPreference.custom_theme_border_width, qwertySwitchNumberKeyWithoutNumberPreference = appPreference.qwerty_switch_number_key_without_number_preference, diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/di/AppModule.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/di/AppModule.kt index 347fcfa80..8f3455f19 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/di/AppModule.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/di/AppModule.kt @@ -61,6 +61,7 @@ import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase.Companion.M import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase.Companion.MIGRATION_44_45 import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase.Companion.MIGRATION_45_46 import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase.Companion.MIGRATION_47_48 +import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase.Companion.MIGRATION_50_51 import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase.Companion.MIGRATION_49_50 import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase.Companion.MIGRATION_48_49 import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase.Companion.MIGRATION_46_47 @@ -170,6 +171,7 @@ object AppModule { MIGRATION_47_48, MIGRATION_48_49, MIGRATION_49_50, + MIGRATION_50_51, ) .build() diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/repository/KeyboardRepository.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/repository/KeyboardRepository.kt index f2e88826b..1ce8a39e8 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/repository/KeyboardRepository.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/repository/KeyboardRepository.kt @@ -1,5 +1,6 @@ package com.kazumaproject.markdownhelperkeyboard.repository +import com.kazumaproject.custom_keyboard.data.PopupKeyConfigCodec import com.kazumaproject.custom_keyboard.data.CircularFlickDirection import com.kazumaproject.custom_keyboard.data.DoubleTapBinding import com.kazumaproject.custom_keyboard.data.FlickAction @@ -950,6 +951,8 @@ class KeyboardRepository @Inject constructor( specialKeyColorStyle = specialKeyColorStyle, doubleTapBinding = doubleTapBinding, qwertyConfig = QwertyKeyConfigCodec.decode(dbKey.qwertyConfigJson), + popupMapConfig = PopupKeyConfigCodec.decode(dbKey.popupMapConfigJson) + ?.takeIf { dbKey.keyType == KeyType.FREE_FLICK }?.copy(keyId = dbKey.keyIdentifier), textInputBehavior = KeyTextInputBehavior.fromDbValue(dbKey.textInputBehavior) ) } else { @@ -969,6 +972,8 @@ class KeyboardRepository @Inject constructor( specialKeyColorStyle = specialKeyColorStyle, doubleTapBinding = doubleTapBinding, qwertyConfig = QwertyKeyConfigCodec.decode(dbKey.qwertyConfigJson), + popupMapConfig = PopupKeyConfigCodec.decode(dbKey.popupMapConfigJson) + ?.takeIf { dbKey.keyType == KeyType.FREE_FLICK }?.copy(keyId = dbKey.keyIdentifier), textInputBehavior = KeyTextInputBehavior.fromDbValue(dbKey.textInputBehavior) ) } @@ -1051,11 +1056,6 @@ class KeyboardRepository @Inject constructor( } } }, - preservedFlickDefinitions = dbLayout.keysWithFlicks.mapNotNull { keyWithFlicks -> - keyWithFlicks.key.hierarchicalFlickJson?.let { json -> - keyWithFlicks.key.keyIdentifier to json - } - }.toMap(), twoStepFlickKeyMaps = twoStepMaps, longPressFlickKeyMaps = longPressFlickMaps, twoStepLongPressKeyMaps = twoStepLongPressMaps, @@ -1249,9 +1249,8 @@ class KeyboardRepository @Inject constructor( doubleTapBinding?.action ), doubleTapPolicy = doubleTapBinding?.policy?.serializedName, - hierarchicalFlickJson = if (keyData.keyType == KeyType.HIERARCHICAL_FLICK) { - uiLayout.preservedFlickDefinitions[keyIdentifier] - } else null, + popupMapConfigJson = keyData.popupMapConfig?.takeIf { keyData.keyType == KeyType.FREE_FLICK } + ?.let(PopupKeyConfigCodec::encode), qwertyConfigJson = keyData.qwertyConfig?.let(QwertyKeyConfigCodec::encode), textInputBehavior = keyData.textInputBehavior.dbValue ) 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 5d0458a48..c610da352 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 @@ -15,7 +15,6 @@ import com.kazumaproject.core.data.popup.TfbiFlickStartPositionMode import com.kazumaproject.core.data.popup.TfbiPopupPresentationMode import com.kazumaproject.custom_keyboard.data.CircularFlickDirection import com.kazumaproject.custom_keyboard.data.KeyboardInputMode -import com.kazumaproject.custom_keyboard.data.SumireFlickInputMode import com.kazumaproject.custom_keyboard.data.TfbiFlickRotation import com.kazumaproject.custom_keyboard.data.buildEvenCircularRanges import com.kazumaproject.domain.EmojiSkinToneSupport @@ -154,7 +153,6 @@ object AppPreference { const val FLICK_THRESHOLD_SHAPE_KEY = "flick_threshold_shape_preference" const val TFBI_DIAGONAL_RECOGNITION_MODE_KEY = "tfbi_diagonal_recognition_mode_preference" const val SUMIRE_FLICK_ROTATION_KEY = "sumire_flick_rotation_preference" - const val SUMIRE_FLICK_INPUT_MODE_KEY = "sumire_flick_input_mode_preference" const val SUMIRE_MODE_KEY_HIGHLIGHT_KEY = "sumire_mode_key_highlight_preference" const val FLICK_TFBI_POPUP_PRESENTATION_KEY = "flick_tfbi_popup_presentation_preference" const val FLICK_TFBI_FLICK_START_POSITION_KEY = @@ -361,8 +359,6 @@ object AppPreference { Pair("flick_guide_text_size_sp_preference", 9) private val FLICK_GUIDE_MAX_CHARACTERS_PREFERENCE = Pair("flick_guide_max_characters_preference", 1) - private val HIERARCHICAL_FLICK_MODE_SWITCH_ANGLE_MARGIN = - Pair("hierarchical_flick_mode_switch_angle_margin_preference", 20) private val CUSTOM_KEYBOARD_TWO_WORDS_OUTPUTS = Pair("custom_keyboard_two_words_preference", true) @@ -1083,6 +1079,7 @@ object AppPreference { migrateSumireKeymapGuideModesIfNeeded() migrateGojuonKeyboardTypeIfNeeded(context) migrateSumirePreferenceIfNeeded() + removeRetiredFlickPreferences() initialized = true initialization.complete(Unit) } catch (failure: Throwable) { @@ -1997,14 +1994,6 @@ object AppPreference { it.putString(SUMIRE_FLICK_ROTATION_KEY, value.preferenceValue) } - var sumire_flick_input_mode_preference: SumireFlickInputMode - get() = SumireFlickInputMode.fromPreferenceValue( - preferences.getString(SUMIRE_FLICK_INPUT_MODE_KEY, SumireFlickInputMode.ALL.preferenceValue) - ) - set(value) = preferences.edit { - it.putString(SUMIRE_FLICK_INPUT_MODE_KEY, value.preferenceValue) - } - val tenkey_show_flick_popup_preference: Boolean get() = preferences.getBoolean(TENKEY_SHOW_FLICK_POPUP_KEY, true) @@ -2021,18 +2010,6 @@ object AppPreference { get() = preferences.getBoolean(SUMIRE_MODE_KEY_HIGHLIGHT_KEY, false) set(value) = preferences.edit { it.putBoolean(SUMIRE_MODE_KEY_HIGHLIGHT_KEY, value) } - var hierarchical_flick_mode_switch_angle_margin_preference: Int - get() = preferences.getInt( - HIERARCHICAL_FLICK_MODE_SWITCH_ANGLE_MARGIN.first, - HIERARCHICAL_FLICK_MODE_SWITCH_ANGLE_MARGIN.second - ).coerceIn(0, 34) - set(value) = preferences.edit { - it.putInt( - HIERARCHICAL_FLICK_MODE_SWITCH_ANGLE_MARGIN.first, - value.coerceIn(0, 34) - ) - } - var independent_multi_touch_preference: Boolean get() = preferences.getBoolean(INDEPENDENT_MULTI_TOUCH_KEY, false) set(value) = preferences.edit { it.putBoolean(INDEPENDENT_MULTI_TOUCH_KEY, value) } @@ -2946,8 +2923,21 @@ object AppPreference { it.putString(SUMIRE_INPUT_SELECTION_PREFERENCE.first, value ?: "toggle-default") } + /** Remove retired settings on startup, including after restoring an old preferences backup. */ + private fun removeRetiredFlickPreferences() { + val oldMode = "sumire_flick_input_mode_preference" + val oldAngle = "hierarchical_flick_mode_switch_angle_margin_preference" + val oldStyle = preferences.getString(NEW_SUMIRE_STYLE_KEY, "default") == "third-flick" + if (!oldStyle && !preferences.contains(oldMode) && !preferences.contains(oldAngle)) return + preferences.edit { + it.remove(oldMode).remove(oldAngle) + if (oldStyle) it.putString(NEW_SUMIRE_STYLE_KEY, "default").putString(NEW_SUMIRE_METHOD_KEY, "flick") + } + } + var sumire_keyboard_style: String - get() = preferences.getString(NEW_SUMIRE_STYLE_KEY, "default") ?: "default" + get() = preferences.getString(NEW_SUMIRE_STYLE_KEY, "default") + ?.takeIf { it in setOf("default", "circle", "second-flick", "center-guide-flick", "sumire", "free-popup") } ?: "default" set(value) = preferences.edit { it.putString(NEW_SUMIRE_STYLE_KEY, value) } 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 5fd858e12..d1800ad4e 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 @@ -73,9 +73,6 @@ class SumirePreferenceFragment : AsyncPreferenceFragment() { } sumireStylePreference?.apply { - if (value == "third-flick") { - summary = getString(com.kazumaproject.core.R.string.three_stage_flick_suspended) - } // Summaryの初期設定 if (findIndexOfValue(value) >= 0) { summary = entries[findIndexOfValue(value)].toString() diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickKeyPicker.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickKeyPicker.kt index 7bb92f8e6..abeb739e3 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickKeyPicker.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickKeyPicker.kt @@ -42,7 +42,7 @@ class FreeFlickKeyPicker(context: Context) : LinearLayout(context) { val layout=KeyboardDefaultLayouts.createFinalLayout(KeyboardInputMode.HIRAGANA,emptyMap(), p.sumire_input_method,SumirePopupDefaults.STYLE, KeyboardDefaultLayouts.DeleteKeyFlickSettings(p.delete_key_left_flick_preference,p.delete_key_up_flick_preference,p.delete_key_down_flick_preference), - p.sumire_flick_rotation_preference,p.sumire_flick_input_mode_preference,p.sumire_mode_key_highlight_preference) + p.sumire_flick_rotation_preference, p.sumire_mode_key_highlight_preference) keyboard.setKeyboard(layout.copyWithKeys(layout.keys.map { key -> key.popupMapConfig?.let { original -> key.copy(popupMapConfig=keys.first { it.keyId==original.keyId }) } ?: key }),origin=KeyboardLayoutOrigin.BUILT_IN) diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickKeyboardPreview.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickKeyboardPreview.kt index a9e25f3d2..68eb21c4a 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickKeyboardPreview.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/FreeFlickKeyboardPreview.kt @@ -93,7 +93,7 @@ internal class FreeFlickKeyboardPreview(context: Context) : FrameLayout(context) val repository = SumirePopupRepository(context) val base = KeyboardDefaultLayouts.createFinalLayout(mode, emptyMap(), layoutType, SumirePopupDefaults.STYLE, DeleteKeyFlickSettings(p.delete_key_left_flick_preference, p.delete_key_up_flick_preference, p.delete_key_down_flick_preference), - p.sumire_flick_rotation_preference, p.sumire_flick_input_mode_preference, p.sumire_mode_key_highlight_preference) + p.sumire_flick_rotation_preference, p.sumire_mode_key_highlight_preference) val mapped = base.copyWithKeys(base.keys.map { key -> key.popupMapConfig?.let { key.copy(popupMapConfig = repository.load(it.keyId)) } ?: key }) 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 index f279d981b..81ea570e3 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorFragment.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/sumire_popup/PopupMapEditorFragment.kt @@ -21,11 +21,13 @@ 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.custom_keyboard.ui.CustomFreeFlickEditorDialog import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference import java.util.UUID class PopupMapEditorFragment : Fragment() { private val model: PopupMapEditorViewModel by viewModels() + private val customKey get() = arguments?.containsKey(CustomFreeFlickEditorDialog.ARG_CONFIG) == true private lateinit var repository: SumirePopupRepository private lateinit var content: LinearLayout private lateinit var properties: LinearLayout @@ -40,6 +42,10 @@ class PopupMapEditorFragment : Fragment() { private var editorReady = false private var result = "" private val config get() = requireNotNull(model.config) + private val editingKeyLabel get() = if (customKey) { + arguments?.getString(CustomFreeFlickEditorDialog.ARG_KEY_LABEL).orEmpty() + .ifEmpty { config.map(config.startMapId)?.tapText.orEmpty() }.ifEmpty { label(R.string.custom_free_flick) } + } else config.keyId 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() @@ -56,24 +62,30 @@ class PopupMapEditorFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { editorReady = false repository=SumirePopupRepository(requireContext()) - if (model.layoutId == null) model.layoutId = arguments?.getString(FreeFlickLayoutRepository.ARG_LAYOUT_ID) - ?: runCatching { FreeFlickLayoutRepository(requireContext()).selectedId() }.getOrNull() - if (model.layoutId == null || runCatching { FreeFlickLayoutRepository(requireContext()).find(model.layoutId!!) }.isFailure) { - return text(label(R.string.free_flick_layout_operation_error)) + if (customKey) { + if (model.config == null) model.load(requireNotNull(PopupKeyConfigCodec.decode( + arguments?.getString(CustomFreeFlickEditorDialog.ARG_CONFIG)))) + } else { + if (model.layoutId == null) model.layoutId = arguments?.getString(FreeFlickLayoutRepository.ARG_LAYOUT_ID) + ?: runCatching { FreeFlickLayoutRepository(requireContext()).selectedId() }.getOrNull() + if (model.layoutId == null || runCatching { FreeFlickLayoutRepository(requireContext()).find(model.layoutId!!) }.isFailure) { + return text(label(R.string.free_flick_layout_operation_error)) + } + if(model.config==null) model.load(repository.load("は", model.layoutId)) } - if(model.config==null) model.load(repository.load("は", model.layoutId)) content=column().apply {setPadding(dp(16),dp(8),dp(16),dp(24));clipToPadding=false} val scroll=NestedScrollView(requireContext()).apply {isFillViewport=true;addView(content)} + if (customKey) content.addView(button(label(android.R.string.cancel)) { leaveEditor() }) layoutHeading = text("") - content.addView(row().apply { + if (!customKey) content.addView(row().apply { item(layoutHeading,1f) item(button(label(R.string.free_flick_layout_manage_short)) { guardUnsaved { findNavController().navigate(R.id.freeFlickLayoutsFragment) } }) }) - if(AppPreference.sumire_keyboard_style!=SumirePopupDefaults.STYLE) content.addView(text(label(R.string.popup_inactive))) + if(!customKey && AppPreference.sumire_keyboard_style!=SumirePopupDefaults.STYLE) content.addView(text(label(R.string.popup_inactive))) sourceButton=button(label(R.string.popup_back_editor)) { goSource() } - content.addView(text(label(R.string.free_flick_choose_key))) + if (!customKey) content.addView(text(label(R.string.free_flick_choose_key))) keyPicker=FreeFlickKeyPicker(requireContext()) - content.addView(keyPicker,LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT).apply { + if (!customKey) content.addView(keyPicker,LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT).apply { setMargins(-dp(16),0,-dp(16),0) }) content.addView(sourceButton) @@ -94,7 +106,7 @@ class PopupMapEditorFragment : Fragment() { 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() - mapButton.text=(listOf(this@PopupMapEditorFragment.config.keyId)+session.mapPath.mapNotNull { this@PopupMapEditorFragment.config.map(it)?.name }).joinToString(" › ")+" ▾" + mapButton.text=(listOf(editingKeyLabel)+session.mapPath.mapNotNull { this@PopupMapEditorFragment.config.map(it)?.name }).joinToString(" › ")+" ▾" } } content.addView(canvas,LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,dp(200))) @@ -119,15 +131,15 @@ class PopupMapEditorFragment : Fragment() { setPadding(dp(16),dp(4),dp(16),dp(8)) item(tryButton,1f) item(MaterialButton(requireContext()).apply { - text=label(R.string.popup_save);isAllCaps=false;minWidth=0;minimumWidth=0 - setOnClickListener {save()} + text=label(if (customKey) R.string.popup_apply else R.string.popup_save);isAllCaps=false;minWidth=0;minimumWidth=0 + setOnClickListener {if (save() && customKey) closeEditor()} },1f) } - content.addView(button(label(R.string.free_flick_template)) { applyTemplate() }) - content.addView(button(label(R.string.free_flick_settings)) { + if (!customKey) content.addView(button(label(R.string.free_flick_template)) { applyTemplate() }) + if (!customKey) content.addView(button(label(R.string.free_flick_settings)) { findNavController().navigate(R.id.freeFlickSettingsFragment) }) - installSelectors() + if (!customKey) installSelectors() refresh() editorReady = true return column().apply { @@ -153,8 +165,10 @@ class PopupMapEditorFragment : Fragment() { canvas.applyFreeFlickTheme() canvas.inputOptions=FreeFlickPreferences.read(requireContext()) runCatching { - val saved = repository.load(config.keyId, model.layoutId) - if (!model.dirty && saved != config) model.load(saved) + if (!customKey) { + val saved = repository.load(config.keyId, model.layoutId) + if (!model.dirty && saved != config) model.load(saved) + } refresh() }.onFailure { status.text=label(R.string.free_flick_layout_operation_error) } } @@ -176,16 +190,16 @@ class PopupMapEditorFragment : Fragment() { } } private fun refresh() { - layoutHeading.text = getString(R.string.free_flick_layout_editing, FreeFlickLayoutRepository(requireContext()).find(model.layoutId!!).name) + if (!customKey) layoutHeading.text = getString(R.string.free_flick_layout_editing, FreeFlickLayoutRepository(requireContext()).find(model.layoutId!!).name) if(config.map(model.mapId)==null) model.mapId=config.startMapId - keyPicker.showSelection(FreeFlickLayoutRepository(requireContext()).find(model.layoutId!!).keys.map { if(it.keyId==config.keyId) config else it },config.keyId) - mapButton.text=(if(model.trying) listOf(config.keyId,config.map(config.startMapId)!!.name) - else listOf(config.keyId)+model.path.mapNotNull { config.map(it)?.name }+page.name).joinToString(" › ")+" ▾" + if (!customKey) keyPicker.showSelection(FreeFlickLayoutRepository(requireContext()).find(model.layoutId!!).keys.map { if(it.keyId==config.keyId) config else it },config.keyId) + mapButton.text=(if(model.trying) listOf(editingKeyLabel,config.map(config.startMapId)!!.name) + else listOf(editingKeyLabel)+model.path.mapNotNull { config.map(it)?.name }+page.name).joinToString(" › ")+" ▾" sourceButton.visibility=if(model.path.isEmpty() || model.trying) View.GONE else View.VISIBLE sourceButton.text=getString(R.string.free_flick_return_to_map,config.map(model.path.lastOrNull().orEmpty())?.name.orEmpty()) tryButton.text=label(if(model.trying) R.string.free_flick_return_to_edit else R.string.popup_try) status.text=when { - repository.hasInvalidSavedConfig(config.keyId, model.layoutId) -> label(R.string.popup_invalid_saved) + !customKey && repository.hasInvalidSavedConfig(config.keyId, model.layoutId) -> label(R.string.popup_invalid_saved) model.trying && canvas.inputOptions.presentation==PopupMapPresentation.GUIDE_ABOVE_KEY -> label(R.string.free_flick_try_above) model.trying -> label(if(canvas.inputOptions.nearestEnabled) R.string.free_flick_try_nearest else 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) @@ -193,7 +207,7 @@ class PopupMapEditorFragment : Fragment() { } output.text="${label(R.string.popup_result)}:$result";output.visibility=if(model.trying) View.VISIBLE else View.GONE refreshCanvas();showProperties() - keyPicker.keyboard.doOnLayout { + if (!customKey) keyPicker.keyboard.doOnLayout { val key=(0 until keyPicker.keyboard.childCount).map(keyPicker.keyboard::getChildAt) .filterIsInstance().firstOrNull {it.text.toString()==config.keyId} if(key!=null) { @@ -222,7 +236,7 @@ class PopupMapEditorFragment : Fragment() { } 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) + if(conflict.type==PopupConflictType.KEY) return getString(R.string.popup_collision_detail,label(R.string.popup_tap),editingKeyLabel) 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()) @@ -441,14 +455,27 @@ class PopupMapEditorFragment : Fragment() { 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 closeEditor() { + if (customKey) (parentFragment as? androidx.fragment.app.DialogFragment)?.dismiss() + else findNavController().popBackStack() + } private fun save(): Boolean { + if (customKey) { + val json = PopupKeyConfigCodec.encode(config) + parentFragmentManager.setFragmentResult( + CustomFreeFlickEditorDialog.RESULT, + androidx.core.os.bundleOf(CustomFreeFlickEditorDialog.ARG_CONFIG to json)) + model.markSaved() + return true + } + return runCatching {model.layoutId=repository.save(config, model.layoutId);model.markSaved();refresh();status.text=label(R.string.popup_saved);true} .getOrElse {status.text=label(R.string.free_flick_layout_operation_error);false} } fun leaveEditor() { if(model.trying) {model.trying=false;refresh();return} if(model.path.isNotEmpty()) {goSource();return} - guardUnsaved {findNavController().popBackStack()} + guardUnsaved {closeEditor()} } private fun guardUnsaved(next: ()->Unit) { if(!model.dirty) {next();return} diff --git a/app/src/main/res/layout/fragment_key_editor.xml b/app/src/main/res/layout/fragment_key_editor.xml index e20bb90e2..33bd5afc5 100644 --- a/app/src/main/res/layout/fragment_key_editor.xml +++ b/app/src/main/res/layout/fragment_key_editor.xml @@ -128,6 +128,13 @@ android:layout_marginTop="8dp" app:singleSelection="true"> + + + + 横・縦方向の距離で判定(矩形) 2段フリックの斜め判定 2段フリックの回転方向 - 3段フリックの入力機能 - 拗音・拗長音 - 濁音・半濁音 - すべて(標準) - 「きょ・きょう」などの拗音と、「が・ぱ」などの濁音の入力範囲を選びます。 標準(従来の配置) 時計回り 反時計回り @@ -1088,14 +1083,6 @@ ドーナツ入力 ドーナツ入力の設定 フリックの角度を調整します。\n変更の適応にはキーボードの再起動が必要です。 - 3段フリック入力の判定角度 - 隣り合う入力候補の境界角度を調整します - イ段 濁音/拗音 - 「きょ / ぎょ」などが意図した入力になるように調整できます。\n角度を大きくすると「きょ」を入力するときに誤って「ぎょ」と判定されにくくなります。 - 濁音化に必要な角度差 - %1$d° - リセット - %1$s 枠線の太さ 数字キーボード切り替え時の入力モード かなキーボード/スミレキーボードに切り替えるとき、数字キーボードではなく日本語入力モードに切り替えます。 @@ -1963,18 +1950,6 @@ ABC abc 0123456789 ABC 12345 特殊キーのアイコン 特殊キーの文字 - 3段フリック - かな(3段フリック) - 文字の状態 - 通常 - 濁点 - 半濁点 - %1$d段目 / 最大3段 %2$s - 前の段へ - 次の段を開く - 分岐ラベル - 次の段を作成 - 割り当てを削除 マッシュルーム対応アプリで文字を変換・入力します マッシュルーム対応アプリを選択 マッシュルーム対応アプリがインストールされていません @@ -2036,4 +2011,6 @@ ABC abc 0123456789 ABC 12345 横に並べる候補を増やす 空欄なら入力する文字を表示します。 キーボードのキーをタップして、ポップアップを編集します。 + フリーフリック + マップを編集・入力を試す diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml index 48c336a43..2f543a176 100644 --- a/app/src/main/res/values/arrays.xml +++ b/app/src/main/res/values/arrays.xml @@ -418,17 +418,7 @@ counterclockwise - - @string/sumire_flick_input_mode_contracted - @string/sumire_flick_input_mode_voiced - @string/sumire_flick_input_mode_all - - - contracted - voiced - all - legacy diff --git a/app/src/main/res/values/ids.xml b/app/src/main/res/values/ids.xml index a1edf50cc..66e6f5223 100644 --- a/app/src/main/res/values/ids.xml +++ b/app/src/main/res/values/ids.xml @@ -12,4 +12,5 @@ + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 123a33b09..8e0267c46 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -276,11 +276,6 @@ Horizontal and vertical threshold (rectangular) Two-step diagonal detection Two-step flick rotation direction - Three-step flick input features - Contracted sounds and long vowels - Voiced and semi-voiced kana - All (default) - Choose contracted sounds such as きょ and きょう, voiced kana such as が and ぱ, or both. Default (current layout) Clockwise Counterclockwise @@ -1213,14 +1208,6 @@ Donuts Input Donuts Input Adjust the flick recognition angle - Recognition angle for three-step flick input - Adjusts the boundary angle between neighboring input candidates - I-column dakuten / contracted sounds - Reset - Angle difference required for dakuten - Adjust this so inputs such as kyo / gyo are recognized as intended.\nIncreasing the angle makes gyo less likely to be recognized by mistake when entering kyo. - %1$d° - %1$s Border width Input mode when switching from the number keyboard When switching to the Kana keyboard or Sumire keyboard, switch to Japanese input mode instead of the number keyboard.。 @@ -1965,18 +1952,6 @@ ABC abc 0123456789 ABC 12345 Utility key icons Utility key text - 3-stage flick - Kana (3-stage flick) - Character state - Normal - Voiced - Semi-voiced - Stage %1$d / 3 %2$s - Previous stage - Open next stage - Branch label - Create next stage - Remove assignment Use a Mushroom app to transform or insert text Choose a Mushroom app No Mushroom apps are installed @@ -2038,4 +2013,6 @@ ABC abc 0123456789 ABC 12345 More popup columns Leave empty to show the text to enter. Tap a keyboard key to edit its popups. + Free Flick + Edit maps and try input diff --git a/app/src/main/res/xml/pref_sumire.xml b/app/src/main/res/xml/pref_sumire.xml index 9fcceb4b2..3b9a874c9 100644 --- a/app/src/main/res/xml/pref_sumire.xml +++ b/app/src/main/res/xml/pref_sumire.xml @@ -7,10 +7,6 @@ android:title="@string/category_sumire_input_keyboard_title" app:isPreferenceVisible="true"> - diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/FreeFlickKeyMigrationTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/FreeFlickKeyMigrationTest.kt new file mode 100644 index 000000000..dfda739a6 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/FreeFlickKeyMigrationTest.kt @@ -0,0 +1,69 @@ +package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.database + +import android.content.Context +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import com.kazumaproject.custom_keyboard.data.KeyType +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.data.KeyDefinition +import com.kazumaproject.markdownhelperkeyboard.database.AppDatabase +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 FreeFlickKeyMigrationTest { + @Test fun removesRetiredColumnAndPreservesEveryMappingTableAndKeyIdentity() { + val context = ApplicationProvider.getApplicationContext() + val name = "free-flick-migration-${System.nanoTime()}.db" + try { + val initial = Room.databaseBuilder(context, AppDatabase::class.java, name).allowMainThreadQueries().build() + val tables = listOf("flick_mappings", "circular_flick_mappings", "two_step_flick_mappings", + "long_press_flick_mappings", "two_step_long_press_mappings") + try { + val db = initial.openHelper.writableDatabase + db.execSQL("INSERT INTO keyboard_layouts (layoutId, name, columnCount, rowCount, isRomaji, isDirectMode, createdAt, sortOrder, stableId, isFlexiblePlacementLayout, usageMode) VALUES (1, 'Original', 2, 1, 0, 0, 0, 0, 'original', 0, 'Normal')") + runBlocking { initial.keyboardLayoutDao().insertKeys(listOf( + KeyDefinition(keyId = 10, ownerLayoutId = 1, label = "Retired", row = 0, column = 0, + keyType = KeyType.NORMAL, keyIdentifier = "old"), + KeyDefinition(keyId = 20, ownerLayoutId = 1, label = "Existing", row = 0, column = 1, + keyType = KeyType.TWO_STEP_FLICK, keyIdentifier = "existing"))) } + db.execSQL("INSERT INTO flick_mappings (ownerKeyId, stateIndex, flickDirection, actionType, actionValue) VALUES (20, 0, 'TAP', 'INPUT_TEXT', 'a')") + db.execSQL("INSERT INTO circular_flick_mappings (ownerKeyId, stateIndex, circularDirection, actionType, actionValue) VALUES (20, 0, 'TAP', 'INPUT_TEXT', 'b')") + db.execSQL("INSERT INTO two_step_flick_mappings VALUES (20, 'LEFT', 'UP', 'c')") + db.execSQL("INSERT INTO long_press_flick_mappings VALUES (20, 'UP', 'd')") + db.execSQL("INSERT INTO two_step_long_press_mappings VALUES (20, 'LEFT', 'UP', 'e')") + db.execSQL("ALTER TABLE key_definitions DROP COLUMN popupMapConfigJson") + db.execSQL("ALTER TABLE key_definitions ADD COLUMN hierarchicalFlickJson TEXT") + db.execSQL("UPDATE key_definitions SET keyType = 'HIERARCHICAL_FLICK', hierarchicalFlickJson = '{\"retired\":true}' WHERE keyId = 10") + db.execSQL("PRAGMA user_version = 50") + } finally { initial.close() } + val migrated = Room.databaseBuilder(context, AppDatabase::class.java, name) + .addMigrations(AppDatabase.MIGRATION_50_51).allowMainThreadQueries().build() + try { + val db = migrated.openHelper.writableDatabase + assertEquals(51, db.version) + db.query("SELECT keyId, keyIdentifier, keyType, popupMapConfigJson FROM key_definitions ORDER BY keyId").use { + assertTrue(it.moveToFirst()); assertEquals(10, it.getInt(0)); assertEquals("old", it.getString(1)) + assertEquals("NORMAL", it.getString(2)); assertTrue(it.isNull(3)) + assertTrue(it.moveToNext()); assertEquals(20, it.getInt(0)); assertEquals("TWO_STEP_FLICK", it.getString(2)) + } + tables.forEach { table -> db.query("SELECT ownerKeyId FROM `$table`").use { + assertTrue("$table retained", it.moveToFirst()); assertEquals(20, it.getInt(0)) + } } + db.query("PRAGMA table_info(key_definitions)").use { + while (it.moveToNext()) assertNotEquals("hierarchicalFlickJson", it.getString(1)) + } + db.query("PRAGMA foreign_key_check").use { assertFalse(it.moveToFirst()) } + // AUTOINCREMENT must still advance beyond the preserved IDs. + runBlocking { + assertTrue(migrated.keyboardLayoutDao().insertKeys(listOf(KeyDefinition(ownerLayoutId = 1, + label = "New", row = 0, column = 0, keyType = KeyType.NORMAL, keyIdentifier = "new"))).single() > 20) + } + } finally { migrated.close() } + } finally { context.deleteDatabase(name) } + } +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/HierarchicalFlickMigrationTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/LegacyKeySchemaMigrationTest.kt similarity index 88% rename from app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/HierarchicalFlickMigrationTest.kt rename to app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/LegacyKeySchemaMigrationTest.kt index 6ebdd16ef..e71867997 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/HierarchicalFlickMigrationTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/LegacyKeySchemaMigrationTest.kt @@ -15,29 +15,29 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [35]) -class HierarchicalFlickMigrationTest { +class LegacyKeySchemaMigrationTest { @Test fun migratedDatabasePassesRoomValidation() { val context = ApplicationProvider.getApplicationContext() - val name = "hierarchical-room-validation-${System.nanoTime()}.db" + val name = "legacy-key-schema-validation-${System.nanoTime()}.db" try { val initial = Room.databaseBuilder(context, AppDatabase::class.java, name) .allowMainThreadQueries().build() try { val db = initial.openHelper.writableDatabase db.execSQL("ALTER TABLE key_definitions DROP COLUMN qwertyConfigJson") - db.execSQL("ALTER TABLE key_definitions DROP COLUMN hierarchicalFlickJson") + db.execSQL("ALTER TABLE key_definitions DROP COLUMN popupMapConfigJson") db.execSQL("PRAGMA user_version = 48") } finally { initial.close() } val migrated = Room.databaseBuilder(context, AppDatabase::class.java, name) - .addMigrations(AppDatabase.MIGRATION_48_49, AppDatabase.MIGRATION_49_50).allowMainThreadQueries().build() - try { assertEquals(50, migrated.openHelper.writableDatabase.version) } + .addMigrations(AppDatabase.MIGRATION_48_49, AppDatabase.MIGRATION_49_50, AppDatabase.MIGRATION_50_51).allowMainThreadQueries().build() + try { assertEquals(51, migrated.openHelper.writableDatabase.version) } finally { migrated.close() } } finally { context.deleteDatabase(name) } } @Test fun migration48To49PreservesKeysWithNoHierarchy() { val context = ApplicationProvider.getApplicationContext() - val name = "hierarchical-migration-${System.nanoTime()}.db" + val name = "legacy-key-schema-migration-${System.nanoTime()}.db" val helper = FrameworkSQLiteOpenHelperFactory().create( SupportSQLiteOpenHelper.Configuration.builder(context).name(name) .callback(object : SupportSQLiteOpenHelper.Callback(48) { diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/QwertyKeyMigrationTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/QwertyKeyMigrationTest.kt index f69b76c53..48c7acaec 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/QwertyKeyMigrationTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/database/QwertyKeyMigrationTest.kt @@ -29,14 +29,16 @@ class QwertyKeyMigrationTest { label = "Existing", row = 0, column = 0, keyType = KeyType.NORMAL, keyIdentifier = "existing"))) } + db.execSQL("ALTER TABLE key_definitions DROP COLUMN popupMapConfigJson") + db.execSQL("ALTER TABLE key_definitions ADD COLUMN hierarchicalFlickJson TEXT") db.execSQL("ALTER TABLE key_definitions DROP COLUMN qwertyConfigJson") db.execSQL("PRAGMA user_version = 49") } finally { initial.close() } val migrated = Room.databaseBuilder(context, AppDatabase::class.java, name) - .addMigrations(AppDatabase.MIGRATION_49_50).allowMainThreadQueries().build() + .addMigrations(AppDatabase.MIGRATION_49_50, AppDatabase.MIGRATION_50_51).allowMainThreadQueries().build() try { val db = migrated.openHelper.writableDatabase - assertEquals(50, db.version) + assertEquals(51, db.version) db.query("SELECT name FROM keyboard_layouts WHERE layoutId = 1").use { assertTrue(it.moveToFirst()) assertEquals("Original", it.getString(0)) diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonImporterTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonImporterTest.kt index 255f57345..57c5bbf1c 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonImporterTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/import_export/KeyboardLayoutJsonImporterTest.kt @@ -256,7 +256,7 @@ class KeyboardLayoutJsonImporterTest { assertTrue("root must be object", root.isJsonObject) val obj = root.asJsonObject - assertEquals(6, obj["schemaVersion"].asInt) + assertEquals(7, obj["schemaVersion"].asInt) assertNotNull(obj["layouts"]) assertTrue("layouts must be array", obj["layouts"].isJsonArray) assertEquals(0, obj["layouts"].asJsonArray.size()) diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickEditorDialogTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickEditorDialogTest.kt new file mode 100644 index 000000000..dec95823c --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickEditorDialogTest.kt @@ -0,0 +1,64 @@ +package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui + +import android.os.Looper +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.fragment.app.FragmentActivity +import androidx.lifecycle.ViewModelProvider +import androidx.preference.PreferenceManager +import com.kazumaproject.custom_keyboard.data.* +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference +import com.kazumaproject.markdownhelperkeyboard.sumire_popup.PopupMapEditorFragment +import com.kazumaproject.markdownhelperkeyboard.sumire_popup.PopupMapEditorViewModel +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class CustomFreeFlickEditorDialogTest { + private fun descendants(view: View): List = listOf(view) + if (view is ViewGroup) + (0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList() + + @Test fun customMapDraftSurvivesRecreationAndReturnsWithoutChangingBuiltInPreferences() { + val controller = Robolectric.buildActivity(FragmentActivity::class.java) + controller.get().setTheme(com.google.android.material.R.style.Theme_Material3_DayNight_NoActionBar) + controller.setup() + try { + var activity = controller.get() + AppPreference.init(activity) + val preferences = PreferenceManager.getDefaultSharedPreferences(activity) + val before = preferences.all.toMap() + val original = PopupKeyConfigCodec.create("custom-key", "first") + CustomFreeFlickEditorDialog.create(PopupKeyConfigCodec.encode(original)) + .showNow(activity.supportFragmentManager, "editor") + shadowOf(Looper.getMainLooper()).idle() + fun editor(): PopupMapEditorFragment { + val dialog = activity.supportFragmentManager.findFragmentByTag("editor") as CustomFreeFlickEditorDialog + return dialog.childFragmentManager.findFragmentById(R.id.custom_free_flick_editor_host) as PopupMapEditorFragment + } + val changed = original.withMap(original.maps.single().copy(tapText = "changed😀")) + ViewModelProvider(editor())[PopupMapEditorViewModel::class.java].change(changed) + controller.recreate() + activity = controller.get() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(changed, ViewModelProvider(editor())[PopupMapEditorViewModel::class.java].config) + var returned: PopupKeyConfig? = null + activity.supportFragmentManager.setFragmentResultListener(CustomFreeFlickEditorDialog.RESULT, activity) { _, result -> + returned = PopupKeyConfigCodec.decode(result.getString(CustomFreeFlickEditorDialog.ARG_CONFIG)) + } + descendants(editor().requireView()).filterIsInstance() + .single { it.text.toString() == activity.getString(R.string.popup_apply) }.performClick() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(changed, returned) + assertEquals(before, preferences.all) + assertNull(activity.supportFragmentManager.findFragmentByTag("editor")) + } finally { controller.pause().stop().destroy() } + } +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickPersistenceTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickPersistenceTest.kt new file mode 100644 index 000000000..e36ab0192 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/CustomFreeFlickPersistenceTest.kt @@ -0,0 +1,78 @@ +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.* +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.import_export.* +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 CustomFreeFlickPersistenceTest { + private fun config() = PopupKeyConfig("custom", "base", listOf( + PopupMap("base", "Base", "😀", listOf( + PopupRegion("text", PopupBounds(-1.5f, -.5f, -.5f, .5f), PopupAction(text = "hello")), + PopupRegion("switch", PopupBounds(.5f, -.5f, 1.5f, .5f), PopupAction(PopupActionType.SWITCH, targetMapId = "next")))), + PopupMap("next", "Next", "かな", listOf( + PopupRegion("back", PopupBounds(-.5f, -1.5f, .5f, -.5f), PopupAction(PopupActionType.BACK)))))) + + @Test fun mapsRemainEditableAndSurviveSaveReloadDuplicateAndBackup() = runBlocking { + val db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java) + .allowMainThreadQueries().build() + try { + val repository = KeyboardRepository(db.keyboardLayoutDao()) + val editor = KeyboardEditorViewModel(repository) + val key = KeyData("Custom", 0, 0, true, keyType = KeyType.FREE_FLICK, keyId = "custom", popupMapConfig = config()) + editor.applyTemplate(KeyboardLayout(listOf(key), emptyMap(), 1, 1)) + val editableKey = editor.uiState.value.layout.keys.single() + val changed = config().copy(keyId = editableKey.keyId!!).let { + it.withMap(it.maps.first().copy(tapText = "edited😀")) + } + assertTrue(editor.updateKeyAndMappings(editableKey.copy(popupMapConfig = changed), emptyMap(), emptyMap(), emptyMap(), emptyMap())) + val id = repository.saveLayout(editor.uiState.value.layout, "Free Flick", null) + fun assertConfig(layout: KeyboardLayout) { + val restored = layout.keys.single() + assertEquals(KeyType.FREE_FLICK, restored.keyType) + assertEquals(changed.copy(keyId = restored.keyId!!), restored.popupMapConfig) + val session = PopupMapSession(restored.popupMapConfig!!, options = PopupMapInputOptions(nearestEnabled = false)) + session.move(1f, 0f) + assertEquals("next", session.currentMap.id) + session.move(0f, -1f) + assertEquals("base", session.currentMap.id) + session.move(-1f, 0f) + assertEquals("hello", session.release(-1f, 0f)) + } + assertConfig(repository.getFullLayout(id).first()) + repository.duplicateLayout(id) + repository.getAllCustomKeyboardLayouts().first().forEach(::assertConfig) + val json = KeyboardLayoutJsonExporter.toJson(repository.getAllFullLayoutsForExport()) + assertFalse(json.contains("hierarchicalFlick")) + val parsed = KeyboardLayoutJsonImporter.parse(json) as KeyboardLayoutImportResult.Success + assertTrue(repository.importLayouts(parsed.layouts) is KeyboardLayoutImportResult.Success) + repository.getAllCustomKeyboardLayouts().first().forEach(::assertConfig) + } finally { db.close() } + } + + @Test fun invalidMapsAreReportedOnImport() { + val json = """{"schemaVersion":7,"layouts":[{"layout":{"name":"Broken","columnCount":1,"rowCount":1},"keysWithFlicks":[{"key":{"keyType":"FREE_FLICK","row":0,"column":0,"freeFlick":{"keyId":"x","startMapId":"missing","maps":[]}}}]}]}""" + val result = KeyboardLayoutJsonImporter.parse(json) + assertTrue(result is KeyboardLayoutImportResult.Failure || result is KeyboardLayoutImportResult.PartialSuccess) + } + + @Test fun removedTypeInOldBackupLoadsAsAnOrdinaryKey() { + val json = """{"schemaVersion":5,"layouts":[{"layout":{"name":"Old","columnCount":1,"rowCount":1},"keysWithFlicks":[{"key":{"keyType":"HIERARCHICAL_FLICK","label":"old","row":0,"column":0,"hierarchicalFlick":{"obsolete":true}},"flicks":[]}]}]}""" + val result = KeyboardLayoutJsonImporter.parse(json) as KeyboardLayoutImportResult.Success + val key = result.layouts.single().keysWithFlicks.single().key + assertEquals(KeyType.NORMAL, key.keyType) + assertNull(key.popupMapConfigJson) + } +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorViewModelFlexiblePlacementTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorViewModelFlexiblePlacementTest.kt index fc5a00bda..5b5469bc0 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorViewModelFlexiblePlacementTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/KeyboardEditorViewModelFlexiblePlacementTest.kt @@ -1153,10 +1153,6 @@ class KeyboardEditorViewModelFlexiblePlacementTest { "x" to mapOf(TfbiFlickDirection.TAP to mapOf(TfbiFlickDirection.LEFT to "x")), "y" to mapOf(TfbiFlickDirection.TAP to mapOf(TfbiFlickDirection.LEFT to "y")) ), - preservedFlickDefinitions = mapOf( - "x" to """{"label":"x"}""", - "y" to """{"label":"y"}""" - ), columnCount = 2, rowCount = 1, items = listOf( @@ -1175,13 +1171,11 @@ class KeyboardEditorViewModelFlexiblePlacementTest { assertFalse(layout.twoStepFlickKeyMaps.containsKey("x")) assertFalse(layout.longPressFlickKeyMaps.containsKey("x")) assertFalse(layout.twoStepLongPressKeyMaps.containsKey("x")) - assertFalse(layout.preservedFlickDefinitions.containsKey("x")) assertTrue(layout.flickKeyMaps.containsKey("y")) assertTrue(layout.circularFlickKeyMaps.containsKey("y")) assertTrue(layout.twoStepFlickKeyMaps.containsKey("y")) assertTrue(layout.longPressFlickKeyMaps.containsKey("y")) assertTrue(layout.twoStepLongPressKeyMaps.containsKey("y")) - assertTrue(layout.preservedFlickDefinitions.containsKey("y")) assertNull(vm.uiState.value.selectedItemId) } diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/ThreeStageFlickPersistenceTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/ThreeStageFlickPersistenceTest.kt deleted file mode 100644 index fbbc9e5f7..000000000 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/ThreeStageFlickPersistenceTest.kt +++ /dev/null @@ -1,107 +0,0 @@ -package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui - -import com.kazumaproject.custom_keyboard.data.CustomFlickSuspension -import android.content.Context -import androidx.room.Room -import androidx.test.core.app.ApplicationProvider -import com.google.gson.JsonParser -import com.kazumaproject.custom_keyboard.data.GridPlacement -import com.kazumaproject.custom_keyboard.data.KeyData -import com.kazumaproject.custom_keyboard.data.KeyItem -import com.kazumaproject.custom_keyboard.data.KeyboardLayout -import com.kazumaproject.custom_keyboard.data.KeyType -import com.kazumaproject.custom_keyboard.view.TfbiFlickDirection -import com.kazumaproject.markdownhelperkeyboard.R -import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.import_export.KeyboardLayoutImportError -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 ThreeStageFlickPersistenceTest { - @Test fun oldDefinitionSurvivesOtherKeyEditsSaveReloadDuplicateAndBackup() = runBlocking { - val db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java) - .allowMainThreadQueries().build() - try { - val repository = KeyboardRepository(db.keyboardLayoutDao()) - val editor = KeyboardEditorViewModel(repository) - assertFalse(editor.availableTemplates.any { it.nameResId == R.string.template_three_stage_flick }) - val saved = KeyData("saved", 0, 0, true, keyType = KeyType.HIERARCHICAL_FLICK, keyId = "saved") - val ordinary = KeyData("other", 0, 1, false, keyId = "other") - val two = KeyData("two", 0, 2, true, keyType = KeyType.TWO_STEP_FLICK, keyId = "two") - val sticky = KeyData("sticky", 0, 3, true, keyType = KeyType.STICKY_TWO_STEP_FLICK, keyId = "sticky") - val maps = listOf("two", "sticky").associateWith { mapOf(TfbiFlickDirection.LEFT to - mapOf(TfbiFlickDirection.UP_LEFT to "きゅ", TfbiFlickDirection.DOWN_LEFT to "きょ")) } - val definition = """{"normal":{"TAP":{"type":"input","output":"preserved😀"}},"future":{"unknown":true}}""" - editor.applyTemplate(KeyboardLayout(listOf(saved, ordinary, two, sticky), emptyMap(), 4, 1, - twoStepFlickKeyMaps = maps, twoStepLongPressKeyMaps = maps, - preservedFlickDefinitions = mapOf("saved" to definition))) - val before = editor.uiState.value.layout - val oldKey = before.keys.single { it.keyType == KeyType.HIERARCHICAL_FLICK } - val other = before.keys.single { it.keyType == KeyType.NORMAL } - before.keys.filter { CustomFlickSuspension.isSuspended(it.keyType) }.forEach { key -> - assertFalse(editor.updateKeyAndMappings(key.copy(label = "changed"), emptyMap(), emptyMap(), emptyMap(), emptyMap())) - } - assertFalse(editor.updateKeyAndMappings(oldKey.copy(label = "changed"), emptyMap(), emptyMap(), emptyMap(), emptyMap())) - assertFalse(editor.updateKeyAndMappings(other.copy(keyType = KeyType.HIERARCHICAL_FLICK), emptyMap(), emptyMap(), emptyMap(), emptyMap())) - before.keys.filter { it.keyType in listOf(KeyType.TWO_STEP_FLICK, KeyType.STICKY_TWO_STEP_FLICK) } - .forEach { key -> - val keyId = requireNotNull(key.keyId) - assertTrue(editor.updateKeyAndMappings(key.copy(label = "edited-${key.label}"), - emptyMap(), before.twoStepFlickKeyMaps.getValue(keyId), emptyMap(), - before.twoStepLongPressKeyMaps.getValue(keyId))) - } - assertTrue(editor.updateKeyAndMappings(other.copy(label = "edited"), emptyMap(), emptyMap(), emptyMap(), emptyMap())) - val edited = editor.uiState.value.layout - assertEquals(before.preservedFlickDefinitions, edited.preservedFlickDefinitions) - val id = repository.saveLayout(edited, "Suspended", null) - val reloaded = repository.getFullLayout(id).first() - assertEquals(edited.preservedFlickDefinitions, reloaded.preservedFlickDefinitions) - assertEquals(edited.twoStepFlickKeyMaps, reloaded.twoStepFlickKeyMaps) - assertEquals(edited.twoStepLongPressKeyMaps, reloaded.twoStepLongPressKeyMaps) - repository.duplicateLayout(id) - val duplicateId = repository.getLayoutsNotFlow().single { it.layoutId != id }.layoutId - assertEquals(reloaded.preservedFlickDefinitions, repository.getFullLayout(duplicateId).first().preservedFlickDefinitions) - val json = KeyboardLayoutJsonExporter.toJson(repository.getAllFullLayoutsForExport()) - val parsed = KeyboardLayoutJsonImporter.parse(json) as KeyboardLayoutImportResult.Success - parsed.layouts.forEach { imported -> - assertEquals(reloaded.preservedFlickDefinitions, imported.keysWithFlicks.mapNotNull { - it.key.hierarchicalFlickJson?.let { data -> it.key.keyIdentifier to data } - }.toMap()) - } - assertTrue(repository.importLayouts(parsed.layouts) is KeyboardLayoutImportResult.Success) - repository.getAllCustomKeyboardLayouts().first().forEach { - assertEquals(reloaded.preservedFlickDefinitions, it.preservedFlickDefinitions) - assertEquals(reloaded.twoStepFlickKeyMaps, it.twoStepFlickKeyMaps) - assertEquals(reloaded.twoStepLongPressKeyMaps, it.twoStepLongPressKeyMaps) - } - } finally { db.close() } - } - - @Test fun schemaFourBackupsWithoutAHierarchyStillImport() { - val json = """{"schemaVersion":4,"layouts":[{"layout":{"name":"old","columnCount":1,"rowCount":1}, - "keysWithFlicks":[{"key":{"keyType":"NORMAL","label":"old","row":0,"column":0},"flicks":[]}]}]}""" - val parsed = KeyboardLayoutJsonImporter.parse(json) as KeyboardLayoutImportResult.Success - assertNull(parsed.layouts.single().keysWithFlicks.single().key.hierarchicalFlickJson) - } - - @Test fun suspendedDefinitionsAreOpaqueIncludingUnknownFutureFields() { - val json = """{"schemaVersion":5,"layouts":[{"layout":{"name":"saved","columnCount":1,"rowCount":1}, - "keysWithFlicks":[{"key":{"keyType":"HIERARCHICAL_FLICK","row":0,"column":0, - "hierarchicalFlick":{"normal":{"RIGHT":{"type":"future","payload":[1,2,3]}}}}}]}]}""" - val parsed = KeyboardLayoutJsonImporter.parse(json) as KeyboardLayoutImportResult.Success - val payload = JsonParser.parseString(parsed.layouts.single().keysWithFlicks.single().key.hierarchicalFlickJson) - assertEquals("future", payload.asJsonObject.getAsJsonObject("normal") - .getAsJsonObject("RIGHT").get("type").asString) - } -} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_romaji/RomajiBehaviorPersistenceTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_romaji/RomajiBehaviorPersistenceTest.kt index d68f34a8c..c2107fd4f 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_romaji/RomajiBehaviorPersistenceTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_romaji/RomajiBehaviorPersistenceTest.kt @@ -60,7 +60,7 @@ class RomajiBehaviorPersistenceTest { val context = ApplicationProvider.getApplicationContext() val name = "romaji-migration-${System.nanoTime()}.db" fun open() = Room.databaseBuilder(context, AppDatabase::class.java, name) - .addMigrations(AppDatabase.MIGRATION_47_48, AppDatabase.MIGRATION_48_49, AppDatabase.MIGRATION_49_50).allowMainThreadQueries().build() + .addMigrations(AppDatabase.MIGRATION_47_48, AppDatabase.MIGRATION_48_49, AppDatabase.MIGRATION_49_50, AppDatabase.MIGRATION_50_51).allowMainThreadQueries().build() suspend fun withDatabase(block: suspend (AppDatabase) -> Unit) { val database = open() try { block(database) } finally { database.close() } @@ -74,7 +74,7 @@ class RomajiBehaviorPersistenceTest { db.execSQL("INSERT INTO romaji_maps VALUES (1, 'custom', ?, 1, 1)", arrayOf(data)) db.execSQL("INSERT INTO romaji_maps VALUES (2, 'default', ?, 0, 0)", arrayOf(data)) db.execSQL("ALTER TABLE key_definitions DROP COLUMN qwertyConfigJson") - db.execSQL("ALTER TABLE key_definitions DROP COLUMN hierarchicalFlickJson") + db.execSQL("ALTER TABLE key_definitions DROP COLUMN popupMapConfigJson") db.execSQL("PRAGMA user_version = 47") } withDatabase { database -> diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEServiceSumireFlickRotationTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEServiceSumireFlickRotationTest.kt index 6d051dd2a..3e6538e6d 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEServiceSumireFlickRotationTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEServiceSumireFlickRotationTest.kt @@ -11,7 +11,6 @@ import com.kazumaproject.core.domain.state.InputMode import com.kazumaproject.core.domain.state.TenKeyQWERTYMode import com.kazumaproject.custom_keyboard.data.KeyboardInputMode import com.kazumaproject.custom_keyboard.data.KeyboardLayout -import com.kazumaproject.custom_keyboard.data.SumireFlickInputMode import com.kazumaproject.custom_keyboard.data.TfbiFlickRotation import com.kazumaproject.custom_keyboard.layout.KeyboardDefaultLayouts import com.kazumaproject.custom_keyboard.view.TfbiFlickDirection diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ng_word/database/NgWordMigrationTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ng_word/database/NgWordMigrationTest.kt index 22a93075c..77ca49288 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ng_word/database/NgWordMigrationTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ng_word/database/NgWordMigrationTest.kt @@ -40,17 +40,17 @@ class NgWordMigrationTest { db.execSQL("DROP TABLE romaji_maps") db.execSQL("CREATE TABLE romaji_maps (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL, mapData TEXT NOT NULL, isActive INTEGER NOT NULL, isDeletable INTEGER NOT NULL)") db.execSQL("ALTER TABLE key_definitions DROP COLUMN qwertyConfigJson") - db.execSQL("ALTER TABLE key_definitions DROP COLUMN hierarchicalFlickJson") + db.execSQL("ALTER TABLE key_definitions DROP COLUMN popupMapConfigJson") db.execSQL("PRAGMA user_version = 46") } finally { initial.close() } val migrated = Room.databaseBuilder(context, AppDatabase::class.java, name) - .addMigrations(AppDatabase.MIGRATION_46_47, AppDatabase.MIGRATION_47_48, AppDatabase.MIGRATION_48_49, AppDatabase.MIGRATION_49_50) + .addMigrations(AppDatabase.MIGRATION_46_47, AppDatabase.MIGRATION_47_48, AppDatabase.MIGRATION_48_49, AppDatabase.MIGRATION_49_50, AppDatabase.MIGRATION_50_51) .allowMainThreadQueries().build() try { val db = migrated.openHelper.writableDatabase - assertEquals(50, db.version) + assertEquals(51, db.version) db.query("SELECT matchMode FROM ng_word").use { cursor -> assertTrue(cursor.moveToFirst()) assertEquals("PARTIAL", cursor.getString(0)) diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreferenceSumireFlickInputModeTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreferenceSumireFlickInputModeTest.kt deleted file mode 100644 index 065a05573..000000000 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreferenceSumireFlickInputModeTest.kt +++ /dev/null @@ -1,89 +0,0 @@ -package com.kazumaproject.markdownhelperkeyboard.setting_activity - -import android.content.Context -import android.content.res.Configuration -import androidx.preference.PreferenceManager -import androidx.test.core.app.ApplicationProvider -import com.kazumaproject.custom_keyboard.data.SumireFlickInputMode -import com.kazumaproject.markdownhelperkeyboard.R -import com.kazumaproject.markdownhelperkeyboard.ime_service.ImePreferencesSnapshot -import com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.SettingDestinationType -import com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.SettingSearchIndex -import org.junit.After -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.annotation.Config -import java.util.Locale - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [35]) -class AppPreferenceSumireFlickInputModeTest { - private val context = ApplicationProvider.getApplicationContext() - private val preferences get() = PreferenceManager.getDefaultSharedPreferences(context) - - @Before - fun setUp() { - clearPreferences() - AppPreference.init(context) - } - - @After - fun clearPreferences() { - preferences.edit().clear().commit() - } - - @Test - fun missingAndUnknownPreferencesKeepAllExistingCharacters() { - assertEquals(SumireFlickInputMode.ALL, AppPreference.sumire_flick_input_mode_preference) - preferences.edit().putString(AppPreference.SUMIRE_FLICK_INPUT_MODE_KEY, "unknown").commit() - assertEquals(SumireFlickInputMode.ALL, AppPreference.sumire_flick_input_mode_preference) - assertEquals("all", ImePreferencesSnapshot.from(AppPreference).sumireFlickInputModePreferenceValue) - } - - @Test - fun everyInputModePersistsAndReachesTheImeSnapshot() { - for (mode in SumireFlickInputMode.entries) { - AppPreference.sumire_flick_input_mode_preference = mode - AppPreference.init(context) - assertEquals(mode, AppPreference.sumire_flick_input_mode_preference) - assertEquals(mode.preferenceValue, - preferences.getString(AppPreference.SUMIRE_FLICK_INPUT_MODE_KEY, null)) - assertEquals(mode.preferenceValue, - ImePreferencesSnapshot.from(AppPreference).sumireFlickInputModePreferenceValue) - } - } - - @Test - fun backupRestoresInputModeAndOlderBackupsKeepAllExistingCharacters() { - val olderBackup = AppPreference.exportAllToJson() - AppPreference.sumire_flick_input_mode_preference = SumireFlickInputMode.CONTRACTED - val contractedBackup = AppPreference.exportAllToJson() - AppPreference.importAllFromJson(olderBackup) - assertEquals(SumireFlickInputMode.ALL, AppPreference.sumire_flick_input_mode_preference) - AppPreference.importAllFromJson(contractedBackup) - assertEquals(SumireFlickInputMode.CONTRACTED, AppPreference.sumire_flick_input_mode_preference) - } - - @Test - fun restoredThreeStageSelectionUsesNormalFlickWithoutOverwritingTheBackup() { - preferences.edit().putString("sumire_keyboard_style_preference", "third-flick") - .putString("sumire_input_method_preference", "toggle").commit() - val backup = AppPreference.exportAllToJson() - repeat(2) { - AppPreference.init(context) - val snapshot = ImePreferencesSnapshot.from(AppPreference) - assertEquals("default", snapshot.sumireInputStyle) - assertEquals("flick", snapshot.sumireInputKeyLayoutType) - assertEquals("third-flick", AppPreference.sumire_keyboard_style) - assertEquals("toggle", AppPreference.sumire_input_method) - } - AppPreference.importAllFromJson(backup) - assertEquals("default", ImePreferencesSnapshot.from(AppPreference).sumireInputStyle) - assertFalse(SettingSearchIndex.searchable(context).any { it.key == AppPreference.SUMIRE_FLICK_INPUT_MODE_KEY }) - } -} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/RemovedFlickPreferencesMigrationTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/RemovedFlickPreferencesMigrationTest.kt new file mode 100644 index 000000000..6f50d51cc --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/RemovedFlickPreferencesMigrationTest.kt @@ -0,0 +1,31 @@ +package com.kazumaproject.markdownhelperkeyboard.setting_activity + +import android.content.Context +import androidx.preference.PreferenceManager +import androidx.test.core.app.ApplicationProvider +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 RemovedFlickPreferencesMigrationTest { + @Test fun oldPreferencesUseNormalFlickAndRemoveUnusedSettings() { + val context = ApplicationProvider.getApplicationContext() + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + prefs.edit().putString("sumire_keyboard_style_preference", "third-flick") + .putString("sumire_input_method_preference", "toggle") + .putString("sumire_flick_input_mode_preference", "voiced") + .putInt("hierarchical_flick_mode_switch_angle_margin_preference", 23).commit() + AppPreference.init(context) + assertEquals("default", AppPreference.sumire_keyboard_style) + assertEquals("flick", AppPreference.sumire_input_method) + assertFalse(prefs.contains("sumire_flick_input_mode_preference")) + assertFalse(prefs.contains("hierarchical_flick_mode_switch_angle_margin_preference")) + AppPreference.sumire_keyboard_style = "free-popup" + AppPreference.init(context) + assertEquals("free-popup", AppPreference.sumire_keyboard_style) + } +} diff --git a/core/src/main/java/com/kazumaproject/core/data/popup/TfbiPopupPresentationMode.kt b/core/src/main/java/com/kazumaproject/core/data/popup/TfbiPopupPresentationMode.kt index c8ad3fec0..1835f8f7b 100644 --- a/core/src/main/java/com/kazumaproject/core/data/popup/TfbiPopupPresentationMode.kt +++ b/core/src/main/java/com/kazumaproject/core/data/popup/TfbiPopupPresentationMode.kt @@ -1,7 +1,7 @@ package com.kazumaproject.core.data.popup /** - * Presentation modes for the two-step/three-step flick popup. + * Presentation modes for the two-step flick popup. * * The legacy mode is intentionally the default so existing installations keep their * current popup behavior when the preference is not present yet. diff --git a/core/src/main/res/values-ja/strings.xml b/core/src/main/res/values-ja/strings.xml index 0aeb637aa..43b6b2f5f 100644 --- a/core/src/main/res/values-ja/strings.xml +++ b/core/src/main/res/values-ja/strings.xml @@ -284,6 +284,5 @@ 直接入力モード カーソルを左に移動 カーソルを右に移動 - 3段フリックは一時停止中です。標準キーボードは通常フリックで入力できます。カスタムのキー定義は保持されますが、3段フリックのキーは入力・編集できません。 - カスタム二段・三段フリックのキーは一時停止中です。 + このキーの形式には対応していません。 diff --git a/core/src/main/res/values/strings.xml b/core/src/main/res/values/strings.xml index e630c3dc9..a0e268e63 100644 --- a/core/src/main/res/values/strings.xml +++ b/core/src/main/res/values/strings.xml @@ -284,6 +284,5 @@ Direct input mode Move cursor left Move cursor right - 3-stage flick is temporarily unavailable. The built-in keyboard uses normal flick input. Existing custom key definitions are preserved, but their 3-stage keys cannot be used or edited. - Custom two-step and three-stage flick keys are temporarily suspended. + This key type is unsupported. diff --git a/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/controller/FreeFlickPopupPositionInstrumentedTest.kt b/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/controller/FreeFlickPopupPositionInstrumentedTest.kt index 6f1aa7f5f..389fde228 100644 --- a/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/controller/FreeFlickPopupPositionInstrumentedTest.kt +++ b/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/controller/FreeFlickPopupPositionInstrumentedTest.kt @@ -23,6 +23,52 @@ import org.junit.runner.RunWith class FreeFlickPopupPositionInstrumentedTest { private val instrumentation = InstrumentationRegistry.getInstrumentation() + @Test fun customFreeFlickTypeCommitsTextSwitchesMapsAndCancelsInBothPresentations() { + val intent = Intent(instrumentation.context, SumireFlickRotationTestActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ActivityScenario.launch(intent).use { scenario -> + scenario.onActivity { activity -> + activity.configure("default", TfbiFlickRotation.DEFAULT, TfbiPopupPresentationMode.LEGACY_GRID) + val config = PopupKeyConfig("custom-key", "base", listOf( + PopupMap("base", "Base", "tap😀", listOf( + PopupRegion("text", PopupBounds(-1.5f, -.5f, -.5f, .5f), PopupAction(text = "left")), + PopupRegion("switch", PopupBounds(.5f, -.5f, 1.5f, .5f), PopupAction(PopupActionType.SWITCH, targetMapId = "next")))), + PopupMap("next", "Next", "nextかな", listOf( + PopupRegion("back", PopupBounds(-.5f, -1.5f, .5f, -.5f), PopupAction(PopupActionType.BACK)))))) + val base = KeyboardDefaultLayouts.createFinalLayout(KeyboardInputMode.HIRAGANA, emptyMap(), "flick", "default") + activity.keyboard.setKeyboard(base.copyWithKeys(base.keys.map { + if (it.label == "か") it.copy(keyId = "custom-key", keyType = KeyType.FREE_FLICK, popupMapConfig = config) else it + }), origin = KeyboardLayoutOrigin.CUSTOM) + } + instrumentation.waitForIdleSync() + for (presentation in PopupMapPresentation.entries) { + scenario.onActivity { it.keyboard.setPopupMapOptions(PopupMapInputOptions(nearestEnabled = false, presentation = presentation)) } + event(scenario, MotionEvent.ACTION_DOWN, 0f, 0f) + event(scenario, MotionEvent.ACTION_UP, 0f, 0f) + scenario.onActivity { assertEquals(listOf(KeyAction.Text("tap😀")), it.actions) } + event(scenario, MotionEvent.ACTION_DOWN, 0f, 0f) + event(scenario, MotionEvent.ACTION_MOVE, -1f, 0f) + event(scenario, MotionEvent.ACTION_UP, -1f, 0f) + scenario.onActivity { assertEquals(listOf(KeyAction.Text("left")), it.actions) } + event(scenario, MotionEvent.ACTION_DOWN, 0f, 0f) + event(scenario, MotionEvent.ACTION_MOVE, 1f, 0f) + event(scenario, MotionEvent.ACTION_MOVE, 0f, 0f) + event(scenario, MotionEvent.ACTION_UP, 0f, 0f) + scenario.onActivity { assertEquals(listOf(KeyAction.Text("nextかな")), it.actions) } + event(scenario, MotionEvent.ACTION_DOWN, 0f, 0f) + event(scenario, MotionEvent.ACTION_MOVE, 1f, 0f) + event(scenario, MotionEvent.ACTION_MOVE, 0f, -1f) + event(scenario, MotionEvent.ACTION_MOVE, 0f, 0f) + event(scenario, MotionEvent.ACTION_UP, 0f, 0f) + scenario.onActivity { assertEquals(listOf(KeyAction.Text("tap😀")), it.actions) } + event(scenario, MotionEvent.ACTION_DOWN, 0f, 0f) + event(scenario, MotionEvent.ACTION_MOVE, -1f, 0f) + event(scenario, MotionEvent.ACTION_CANCEL, -1f, 0f) + scenario.onActivity { assertTrue(it.actions.isEmpty()) } + } + } + } + @Test fun sensitivityKeepsPopupPlacementAndDirectHitsKeyRelative() { val intent = Intent(instrumentation.context, SumireFlickRotationTestActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) @@ -67,7 +113,9 @@ class FreeFlickPopupPositionInstrumentedTest { private fun event(scenario: ActivityScenario, action: Int, x: Float, y: Float) { scenario.onActivity { activity -> if (action == MotionEvent.ACTION_DOWN) activity.actions.clear() - val key = activity.kaKey() + // Free Flick temporarily replaces the displayed text with the active map tap output. + val key = (0 until activity.keyboard.childCount).map(activity.keyboard::getChildAt) + .single { it.contentDescription?.toString() == "か" } val keyLocation = IntArray(2).also(key::getLocationOnScreen) val keyboardLocation = IntArray(2).also(activity.keyboard::getLocationOnScreen) val event = MotionEvent.obtain(0L, SystemClock.uptimeMillis(), action, diff --git a/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/view/SumireFlickRotationInstrumentedTest.kt b/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/view/SumireFlickRotationInstrumentedTest.kt index 4f66d4060..e440f7540 100644 --- a/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/view/SumireFlickRotationInstrumentedTest.kt +++ b/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/view/SumireFlickRotationInstrumentedTest.kt @@ -19,7 +19,6 @@ import com.kazumaproject.custom_keyboard.data.FlickDirection import com.kazumaproject.custom_keyboard.data.KeyAction import com.kazumaproject.custom_keyboard.data.KeyboardLayoutOrigin import com.kazumaproject.custom_keyboard.data.KeyboardInputMode -import com.kazumaproject.custom_keyboard.data.SumireFlickInputMode import com.kazumaproject.custom_keyboard.data.TfbiFlickRotation import com.kazumaproject.custom_keyboard.data.TfbiGuidePopupState import com.kazumaproject.custom_keyboard.layout.KeyboardDefaultLayouts @@ -48,8 +47,7 @@ class SumireFlickRotationTestActivity : Activity() { fun configure( style: String, rotation: TfbiFlickRotation, - popup: TfbiPopupPresentationMode, - mode: SumireFlickInputMode = SumireFlickInputMode.ALL + popup: TfbiPopupPresentationMode ) { root.removeAllViews() actions.clear() @@ -62,8 +60,7 @@ class SumireFlickRotationTestActivity : Activity() { dynamicKeyStates = emptyMap(), inputLayoutType = "flick", inputStyle = style, - tfbiFlickRotation = rotation, - sumireFlickInputMode = mode + tfbiFlickRotation = rotation ), origin = KeyboardLayoutOrigin.BUILT_IN) setOnKeyboardActionListener(object : FlickKeyboardView.OnKeyboardActionListener { override fun onPress(action: KeyAction) = Unit @@ -160,10 +157,9 @@ class SumireFlickRotationInstrumentedTest { scenario: ActivityScenario, style: String, rotation: TfbiFlickRotation, - popup: TfbiPopupPresentationMode, - mode: SumireFlickInputMode = SumireFlickInputMode.ALL + popup: TfbiPopupPresentationMode ) { - scenario.onActivity { it.configure(style, rotation, popup, mode) } + scenario.onActivity { it.configure(style, rotation, popup) } InstrumentationRegistry.getInstrumentation().waitForIdleSync() scenario.onActivity { assertTrue("Keyboard must be attached and laid out", it.keyboard.isAttachedToWindow) diff --git a/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/view/ThreeStageFlickSuspensionInstrumentedTest.kt b/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/view/ThreeStageFlickSuspensionInstrumentedTest.kt deleted file mode 100644 index 4699a2808..000000000 --- a/custom_keyboard/src/androidTest/java/com/kazumaproject/custom_keyboard/view/ThreeStageFlickSuspensionInstrumentedTest.kt +++ /dev/null @@ -1,75 +0,0 @@ -package com.kazumaproject.custom_keyboard.view - -import android.os.SystemClock -import android.view.InputDevice -import android.view.MotionEvent -import android.view.View -import androidx.core.view.doOnLayout -import androidx.test.core.app.ActivityScenario -import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.platform.app.InstrumentationRegistry -import com.kazumaproject.core.data.popup.TfbiPopupPresentationMode -import com.kazumaproject.custom_keyboard.data.* -import org.junit.Assert.* -import org.junit.Test -import org.junit.runner.RunWith -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit - -@RunWith(AndroidJUnit4::class) -class ThreeStageFlickSuspensionInstrumentedTest { - @Test fun savedKeysStayBlockedInBothPopupModesAndEveryHitTestMode() { - val instrumentation = InstrumentationRegistry.getInstrumentation() - ActivityScenario.launch(SumireFlickRotationTestActivity::class.java).use { scenario -> - for (type in listOf(KeyType.HIERARCHICAL_FLICK)) - for (popup in TfbiPopupPresentationMode.entries) for (hitMode in KeyHitTestMode.entries) { - val laidOut = CountDownLatch(1) - scenario.onActivity { activity -> - activity.configure("third-flick", TfbiFlickRotation.DEFAULT, popup) - val blocked = KeyData("saved", 0, 0, true, action = KeyAction.Text("blocked"), - keyId = "saved", keyType = type) - val ordinary = KeyData("ok", 0, 1, false, action = KeyAction.Text("ok"), keyId = "ordinary") - val saved = """{"normal":{"TAP":{"type":"input","output":"preserved"}}}""" - activity.keyboard.setLongPressTimeout(100) - activity.keyboard.setKeyboard(KeyboardLayout(listOf(blocked, ordinary), emptyMap(), 2, 1, - preservedFlickDefinitions = mapOf("saved" to saved)), hitMode) - activity.keyboard.doOnLayout { laidOut.countDown() } - } - assertTrue("Keyboard layout did not finish", laidOut.await(5, TimeUnit.SECONDS)) - instrumentation.waitForIdleSync() - fun tap(index: Int, hold: Boolean = false) { - var x = 0f; var y = 0f - scenario.onActivity { activity -> - val key = activity.keyboard.getChildAt(index) - assertEquals(index != 0, key.isEnabled) - assertTrue("Unmeasured key: $index ${key.width}x${key.height}", key.width > 0 && key.height > 0) - val position = IntArray(2).also(key::getLocationOnScreen) - x = position[0] + key.width / 2f; y = position[1] + key.height / 2f - } - val down = SystemClock.uptimeMillis() - fun send(action: Int) { - val event = MotionEvent.obtain(down, SystemClock.uptimeMillis(), action, x, y, 0) - event.source = InputDevice.SOURCE_TOUCHSCREEN - try { assertTrue(instrumentation.uiAutomation.injectInputEvent(event, true)) } - finally { event.recycle() } - } - send(MotionEvent.ACTION_DOWN) - SystemClock.sleep(if (hold) 200 else 40) - send(MotionEvent.ACTION_UP) - instrumentation.waitForIdleSync() - } - tap(0); tap(0); tap(0, hold = true) - scenario.onActivity { activity -> - assertTrue("$popup/$hitMode: ${activity.actions}", activity.actions.isEmpty()) - activity.keyboard.setVisibleKeyLabels(null) - assertFalse(activity.keyboard.getChildAt(0).isEnabled) - activity.keyboard.getChildAt(0).performClick() - activity.keyboard.getChildAt(0).performLongClick() - assertTrue(activity.actions.isEmpty()) - } - tap(1) - scenario.onActivity { assertEquals("$popup/$hitMode", listOf(KeyAction.Text("ok")), it.actions) } - } - } - } -} diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/CustomFlickSuspension.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/CustomFlickSuspension.kt deleted file mode 100644 index 2c3a45f8f..000000000 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/CustomFlickSuspension.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.kazumaproject.custom_keyboard.data - -/** Selected by the caller, never restored from a layout backup. */ -enum class KeyboardLayoutOrigin { CUSTOM, BUILT_IN } - -/** Storage identifiers remain readable while their custom input implementations are suspended. */ -object CustomFlickSuspension { - fun isSuspended(type: KeyType?, origin: KeyboardLayoutOrigin = KeyboardLayoutOrigin.CUSTOM): Boolean = - type == null || type == KeyType.HIERARCHICAL_FLICK -} 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 73df89d35..a4203a515 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 @@ -603,7 +603,6 @@ data class KeyboardLayout( val twoStepFlickKeyMaps: Map>> = emptyMap(), val longPressFlickKeyMaps: Map> = emptyMap(), val twoStepLongPressKeyMaps: Map>> = emptyMap(), - val preservedFlickDefinitions: Map = emptyMap(), val items: List = keys.map { it.toKeyItem() }, val columnUnitCount: Int = columnCount * 2, val rowUnitCount: Int = rowCount * 2, @@ -635,7 +634,8 @@ enum class KeyType { STICKY_TWO_STEP_FLICK, - HIERARCHICAL_FLICK, + /** User-defined popup maps with arbitrary text and map transitions. */ + FREE_FLICK, FLICK_LONG_PRESS, diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyboardLayoutOrigin.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyboardLayoutOrigin.kt new file mode 100644 index 000000000..727b1675c --- /dev/null +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyboardLayoutOrigin.kt @@ -0,0 +1,4 @@ +package com.kazumaproject.custom_keyboard.data + +/** Selected by the caller, never restored from a layout backup. */ +enum class KeyboardLayoutOrigin { CUSTOM, BUILT_IN } diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/PopupKeyConfigCodec.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/PopupKeyConfigCodec.kt new file mode 100644 index 000000000..5eb03d184 --- /dev/null +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/PopupKeyConfigCodec.kt @@ -0,0 +1,32 @@ +package com.kazumaproject.custom_keyboard.data + +import com.google.gson.Gson + +/** Validate saved and imported maps before they reach the gesture controller. */ +object PopupKeyConfigCodec { + private val gson = Gson() + + fun encode(config: PopupKeyConfig): String { + require(PopupMapValidator.conflicts(config).isEmpty()) + return gson.toJson(config) + } + + fun decode(json: String?): PopupKeyConfig? = runCatching { + val config = gson.fromJson(json, PopupKeyConfig::class.java) ?: return null + config.maps.forEach { map -> + requireStrings(map.id, map.name, map.tapText) + map.regions.forEach { region -> + requireStrings(region.id, region.label, region.action.text) + requireNotNull(region.action.type) + } + } + require(config.keyId.isNotBlank() && PopupMapValidator.conflicts(config).isEmpty()) + config + }.getOrNull() + + private fun requireStrings(vararg values: String?) { require(values.all { it != null }) } + + fun create(keyId: String, tapText: String): PopupKeyConfig = PopupKeyConfig( + keyId, "normal", listOf(PopupMap("normal", tapText, tapText)) + ) +} diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/SumireFlickInputMode.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/SumireFlickInputMode.kt deleted file mode 100644 index e5da6ae18..000000000 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/SumireFlickInputMode.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.kazumaproject.custom_keyboard.data - -/** Additional character groups offered by the built-in Sumire three-step kana layouts. */ -enum class SumireFlickInputMode(val preferenceValue: String) { - CONTRACTED("contracted"), - VOICED("voiced"), - ALL("all"); - - companion object { - fun fromPreferenceValue(value: String?): SumireFlickInputMode = - entries.firstOrNull { it.preferenceValue == value } ?: ALL - } -} 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 2b92e208b..330b29872 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 @@ -20,7 +20,6 @@ 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 import com.kazumaproject.custom_keyboard.data.copyWithItems import com.kazumaproject.custom_keyboard.data.copyWithKeys import com.kazumaproject.custom_keyboard.view.TfbiFlickDirection @@ -174,26 +173,19 @@ object KeyboardDefaultLayouts { inputStyle: String, deleteKeyFlickSettings: DeleteKeyFlickSettings = DeleteKeyFlickSettings(), tfbiFlickRotation: TfbiFlickRotation = TfbiFlickRotation.DEFAULT, - 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) + val base = createFinalLayout(mode, dynamicKeyStates, inputLayoutType, "default", deleteKeyFlickSettings, tfbiFlickRotation, 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, + key.copy(keyId = "popup-kana-${key.label}", keyType = KeyType.FREE_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, - tfbiFlickRotation, sumireFlickInputMode, highlightSelectedMode - ) - } val baseLayout = when (inputLayoutType) { "toggle" -> { when (mode) { 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 0180a9f87..466308780 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 @@ -1,6 +1,5 @@ package com.kazumaproject.custom_keyboard.view -import com.kazumaproject.custom_keyboard.data.CustomFlickSuspension import com.kazumaproject.custom_keyboard.data.KeyboardLayoutOrigin import android.annotation.SuppressLint import android.content.Context @@ -259,8 +258,8 @@ class FlickKeyboardView @JvmOverloads constructor( private var currentLayout: KeyboardLayout? = null private var layoutOrigin = KeyboardLayoutOrigin.CUSTOM - private fun isSuspended(key: KeyData): Boolean = - CustomFlickSuspension.isSuspended(key.keyType, layoutOrigin) + private fun isUnsupported(key: KeyData): Boolean = + key.keyType == null // Used only for the built-in Sumire layout. User-defined layouts keep the legacy path. private var geometry = KeyboardGeometry() @@ -868,11 +867,11 @@ class FlickKeyboardView @JvmOverloads constructor( keyView.alpha=if(keyView.isEnabled) 1f else .4f return } - if (isSuspended(keyData)) { + if (isUnsupported(keyData)) { keyView.visibility = if (visibleKeyLabels?.contains(keyData.label) != false) View.VISIBLE else View.INVISIBLE keyView.isEnabled = false keyView.alpha = 0.4f - keyView.contentDescription = "${keyData.label}: ${context.getString(com.kazumaproject.core.R.string.custom_flick_suspended)}" + keyView.contentDescription = "${keyData.label}: ${context.getString(com.kazumaproject.core.R.string.custom_key_unsupported)}" return } keyView.alpha = 1f @@ -1541,7 +1540,7 @@ class FlickKeyboardView @JvmOverloads constructor( val commonCornerRadius = dpToPx(8).toFloat() val visualPalette = resolveKeyVisualPalette(keyData) - val keyView: View = if (shouldRenderKeyAsImage(keyData) && !isSuspended(keyData)) { + val keyView: View = if (shouldRenderKeyAsImage(keyData) && !isUnsupported(keyData)) { AppCompatImageButton(context).apply { isFocusable = false elevation = 0f @@ -1765,7 +1764,7 @@ class FlickKeyboardView @JvmOverloads constructor( keyView.isPressed=keyView.isSelected return null } - if (isSuspended(keyData)) return null + if (isUnsupported(keyData)) return null val layout = currentLayout ?: return null keyData.popupMapConfig?.let { config -> @@ -2898,7 +2897,7 @@ class FlickKeyboardView @JvmOverloads constructor( } } - KeyType.HIERARCHICAL_FLICK -> return null + KeyType.FREE_FLICK -> return null } return null @@ -2927,7 +2926,7 @@ class FlickKeyboardView @JvmOverloads constructor( isFlick: Boolean, isLongPress: Boolean = false, ) { - if (isSuspended(keyData)) return + if (isUnsupported(keyData)) return val dispatch = dispatch@{ val toggleValues = if ( !isFlick && @@ -3286,7 +3285,7 @@ class FlickKeyboardView @JvmOverloads constructor( if (x < 0f || x >= width || y < 0f || y >= height) return null val views = keyInfos.filter { it.view.visibility == View.VISIBLE && it.view.width > 0 && it.view.height > 0 && - (it.view.isEnabled || isSuspended(it.keyData)) + (it.view.isEnabled || isUnsupported(it.keyData)) }.map { it.view } val hit = views.firstOrNull { KeyboardViewGeometry.containsParentPoint(it, x, y) } val selected = hit ?: if (keyHitTestMode == KeyHitTestMode.NEAREST_KEY) views.minByOrNull { key -> @@ -3333,7 +3332,7 @@ class FlickKeyboardView @JvmOverloads constructor( for (info in keyInfos) { val key = info.view if (key.visibility != View.VISIBLE || key.width <= 0 || key.height <= 0 || - (!key.isEnabled && !isSuspended(info.keyData)) + (!key.isEnabled && !isUnsupported(info.keyData)) ) { continue } diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayoutsFlickInputModeTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayoutsFlickInputModeTest.kt deleted file mode 100644 index e9d7f306d..000000000 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/layout/KeyboardDefaultLayoutsFlickInputModeTest.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.kazumaproject.custom_keyboard.layout - -import com.kazumaproject.custom_keyboard.data.KeyboardInputMode -import com.kazumaproject.custom_keyboard.data.KeyboardLayout -import com.kazumaproject.custom_keyboard.data.SumireFlickInputMode -import com.kazumaproject.custom_keyboard.data.TfbiFlickRotation -import com.kazumaproject.custom_keyboard.view.TfbiFlickDirection -import com.kazumaproject.custom_keyboard.view.TfbiFlickDirection.* -import java.text.Normalizer -import org.junit.Assert.* -import org.junit.Test - -class KeyboardDefaultLayoutsFlickInputModeTest { - @Test - fun preferenceValuesRoundTripAndUnknownValuesPreserveAll() { - SumireFlickInputMode.entries.forEach { mode -> - assertEquals(mode, SumireFlickInputMode.fromPreferenceValue(mode.preferenceValue)) - } - assertEquals(SumireFlickInputMode.ALL, SumireFlickInputMode.fromPreferenceValue(null)) - assertEquals(SumireFlickInputMode.ALL, SumireFlickInputMode.fromPreferenceValue("unknown")) - } - - - - - - - - - - - - - - - -} diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/CustomThreeStageFlickTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/CustomThreeStageFlickTest.kt deleted file mode 100644 index 3ceb4ad8c..000000000 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/CustomThreeStageFlickTest.kt +++ /dev/null @@ -1,89 +0,0 @@ -package com.kazumaproject.custom_keyboard.view - -import android.app.Activity -import android.os.Looper -import android.view.ContextThemeWrapper -import android.view.MotionEvent -import android.view.View -import com.kazumaproject.custom_keyboard.data.* -import com.kazumaproject.custom_keyboard.layout.KeyboardDefaultLayouts -import org.junit.Assert.* -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.Robolectric -import org.robolectric.RobolectricTestRunner -import org.robolectric.Shadows.shadowOf -import org.robolectric.annotation.Config -import java.time.Duration - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [35]) -class CustomThreeStageFlickTest { - @Test fun restoredBuiltInStylesUseNormalFlickForEveryLanguageAndOldInputMethod() { - for (mode in KeyboardInputMode.entries) for (method in listOf("flick", "toggle", "romaji")) { - val expected = KeyboardDefaultLayouts.createFinalLayout(mode, emptyMap(), "flick", "default") - val restored = KeyboardDefaultLayouts.createFinalLayout(mode, emptyMap(), method, "third-flick") - assertEquals(expected, restored) - assertTrue(restored.preservedFlickDefinitions.isEmpty()) - assertFalse(restored.keys.any { it.keyType == KeyType.HIERARCHICAL_FLICK }) - } - } - - @Test fun suspendedKeysCannotDispatchTapHoldDoubleTapOrNearestKeyInputAfterRebuild() { - val activity = Robolectric.buildActivity(Activity::class.java).setup().get() - val keyboard = FlickKeyboardView(ContextThemeWrapper(activity, - com.google.android.material.R.style.Theme_Material3_DayNight_NoActionBar)) - val actions = mutableListOf() - keyboard.setOnKeyboardActionListener(object : FlickKeyboardView.OnKeyboardActionListener { - override fun onPress(action: KeyAction) = Unit - override fun onAction(action: KeyAction, isFlick: Boolean) { actions += action } - override fun onActionLongPress(action: KeyAction) { actions += action } - override fun onActionUpAfterLongPress(action: KeyAction) { actions += action } - override fun onFlickDirectionChanged(direction: FlickDirection) = Unit - override fun onFlickActionLongPress(action: KeyAction) { actions += action } - override fun onFlickActionUpAfterLongPress(action: KeyAction, isFlick: Boolean) { actions += action } - }) - val blocked = KeyData("saved", 0, 0, true, action = KeyAction.Text("blocked"), - keyType = KeyType.HIERARCHICAL_FLICK, keyId = "saved") - val ordinary = KeyData("ok", 0, 1, false, action = KeyAction.Text("ok"), keyId = "ordinary") - val saved = """{"normal":{"TAP":{"type":"input","output":"saved"}}}""" - val layout = KeyboardLayout(listOf(blocked, ordinary), emptyMap(), 2, 1, - preservedFlickDefinitions = mapOf("saved" to saved)) - activity.setContentView(keyboard) - fun tap(index: Int, hold: Boolean = false) { - val key = keyboard.getChildAt(index) - assertTrue("Key $index has no bounds", key.width > 0 && key.height > 0) - val position = IntArray(2).also(key::getLocationOnScreen) - val owner = IntArray(2).also(keyboard::getLocationOnScreen) - val x = position[0] + key.width / 2f - val y = position[1] + key.height / 2f - for (action in listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP)) { - val now = android.os.SystemClock.uptimeMillis() - val event = MotionEvent.obtain(now, now, action, x, y, 0) - event.offsetLocation(-owner[0].toFloat(), -owner[1].toFloat()) - keyboard.dispatchTouchEvent(event) - event.recycle() - if (action == MotionEvent.ACTION_DOWN && hold) shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(2)) - } - } - for (hitMode in KeyHitTestMode.entries) { - keyboard.setKeyboard(layout, hitMode) - keyboard.measure(View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY), - View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.EXACTLY)) - keyboard.layout(0, 0, 800, 400) - assertFalse(keyboard.getChildAt(0).isEnabled) - tap(0); tap(0); tap(0, hold = true) - assertTrue("$hitMode: $actions", actions.isEmpty()) - keyboard.setVisibleKeyLabels(null) - keyboard.setKeyboard(layout, hitMode) - assertFalse(keyboard.getChildAt(0).isEnabled) - tap(0) - assertTrue(actions.isEmpty()) - tap(1) - assertEquals(listOf(KeyAction.Text("ok")), actions) - actions.clear() - assertEquals(saved, layout.preservedFlickDefinitions["saved"]) - } - activity.finish() - } -} diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardViewLifecycleTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardViewLifecycleTest.kt index 091ce2b84..c5f43de6a 100644 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardViewLifecycleTest.kt +++ b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardViewLifecycleTest.kt @@ -46,7 +46,7 @@ class FlickKeyboardViewLifecycleTest { @Test fun all54SumireLayoutsKeepEveryKeysTapAfterHideAndReuse() { for (mode in KeyboardInputMode.entries) { for (method in listOf("toggle", "flick", "switch-mode-effective")) { - for (style in listOf("default", "circle", "second-flick", "third-flick", "center-guide-flick", "sumire")) { + for (style in listOf("default", "circle", "second-flick", "center-guide-flick", "sumire")) { val scenario = "$mode/$method/$style" val layout = KeyboardDefaultLayouts.createFinalLayout(mode, emptyMap(), method, style) install(layout) @@ -88,7 +88,7 @@ class FlickKeyboardViewLifecycleTest { @Test fun all54SumireLayoutsKeepEveryKeysLongPressAfterHide() { for (mode in KeyboardInputMode.entries) { for (method in listOf("toggle", "flick", "switch-mode-effective")) { - for (style in listOf("default", "circle", "second-flick", "third-flick", "center-guide-flick", "sumire")) { + for (style in listOf("default", "circle", "second-flick", "center-guide-flick", "sumire")) { val scenario = "$mode/$method/$style" install(KeyboardDefaultLayouts.createFinalLayout(mode, emptyMap(), method, style)) holdAllKeys() diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/SumireModeKeyHighlightTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/SumireModeKeyHighlightTest.kt index 0a04fe244..cd4260909 100644 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/SumireModeKeyHighlightTest.kt +++ b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/SumireModeKeyHighlightTest.kt @@ -100,5 +100,5 @@ class SumireModeKeyHighlightTest { KeyboardInputMode.SYMBOLS -> KeyAction.SwitchToNumberLayout } - private val styles = listOf("default", "circle", "sumire", "second-flick", "third-flick") + private val styles = listOf("default", "circle", "sumire", "second-flick") }