diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/data/DataConverterExtensions.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/data/DataConverterExtensions.kt index c6f49d88f..6fe75cfb7 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/data/DataConverterExtensions.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/data/DataConverterExtensions.kt @@ -76,6 +76,7 @@ fun FlickMapping.toFlickAction(): FlickAction { "ForceHalfWidthSpace" -> KeyAction.ForceHalfWidthSpace "ForceFullWidthSpace" -> KeyAction.ForceFullWidthSpace "ShowEmojiKeyboard" -> KeyAction.ShowEmojiKeyboard + "SwitchToKana" -> KeyAction.SwitchToKanaLayout "SwitchToEnglish" -> KeyAction.SwitchToEnglishLayout "SwitchToNumber" -> KeyAction.SwitchToNumberLayout "DeleteUntilSymbol" -> KeyAction.DeleteUntilSymbol @@ -223,6 +224,7 @@ fun FlickAction.toDbStrings(): Pair { KeyAction.ForceHalfWidthSpace -> "ForceHalfWidthSpace" to null KeyAction.ForceFullWidthSpace -> "ForceFullWidthSpace" to null KeyAction.ShowEmojiKeyboard -> "ShowEmojiKeyboard" to CircularFlickSlotActionMapper.EMOJI_KEYBOARD_LABEL + KeyAction.SwitchToKanaLayout -> "SwitchToKana" to null KeyAction.SwitchToEnglishLayout -> "SwitchToEnglish" to null KeyAction.SwitchToNumberLayout -> "SwitchToNumber" to null KeyAction.DeleteUntilSymbol -> "DeleteUntilSymbol" to null diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/EditableFlickKeyboardView.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/EditableFlickKeyboardView.kt index 42cba1965..b97c048da 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/EditableFlickKeyboardView.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/EditableFlickKeyboardView.kt @@ -608,7 +608,7 @@ class EditableFlickKeyboardView @JvmOverloads constructor( } } else { AutoSizeButton(context).apply { - val label = KeyIconResolver.resolvedLabelForRendering(keyData) + val label = KeyIconResolver.resolvedLabelForRendering(keyData, context) isFocusable = false; isClickable = true isAllCaps = false minimumHeight = 0 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 ba59316e1..f22a7b0ed 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 @@ -101,6 +101,8 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { private companion object { const val STATE_EDITING_KEY = "editingKeyIdentifier" const val STATE_LONG_PRESS_ACTION = "longPressAction" + const val STATE_KEY_TYPE = "editingKeyType" + const val STATE_MIXED_FLICK = "mixedFlickDraft" } @Inject @@ -130,6 +132,8 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { private var currentFlickLongPressItems = mutableListOf() private var currentFlickLongPressHoldItems = mutableListOf() private var currentSpecialFlickItems = mutableListOf() + private var mixedFlickDraft: MixedFlickEditorState? = null + private var updatingMixedFlickSlotType = false private var currentCircularFlickMaps = mutableListOf>() private var currentCircularMapIndex = 0 private var outputEditMode: OutputEditMode = OutputEditMode.NORMAL @@ -142,6 +146,7 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { private lateinit var keyActionOptions: List private lateinit var specialFlickActionOptions: List private lateinit var customKeyboardTargetAdapter: ArrayAdapter + private lateinit var mixedFlickTargetAdapter: ArrayAdapter private lateinit var doubleTapTargetAdapter: ArrayAdapter private lateinit var longPressTargetAdapter: ArrayAdapter private lateinit var circularFlickAdapter: CircularFlickMappingAdapter @@ -174,15 +179,6 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { private var maxColumnSpanUnits: Int = 2 private var maxRowSpanUnits: Int = 2 - // NEW: allowed directions for special-flick category (5 directions) - private val allowedSpecialFlickDirections: List = listOf( - FlickDirection.TAP, - FlickDirection.UP, - FlickDirection.DOWN, - FlickDirection.UP_LEFT, - FlickDirection.UP_RIGHT - ) - private val flickLongPressDirections: List = listOf( TfbiFlickDirection.TAP, TfbiFlickDirection.UP_LEFT, @@ -273,6 +269,12 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { mutableListOf() ) binding.customKeyboardTargetSpinner.setAdapter(customKeyboardTargetAdapter) + mixedFlickTargetAdapter = ArrayAdapter( + requireContext(), + android.R.layout.simple_spinner_dropdown_item, + mutableListOf() + ) + binding.mixedFlickTargetSpinner.setAdapter(mixedFlickTargetAdapter) doubleTapTargetAdapter = ArrayAdapter( requireContext(), android.R.layout.simple_spinner_dropdown_item, @@ -348,15 +350,32 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { binding.flickGridEditorView.updateCellLabel(mode, text) updateDoneButtonState() } - else -> Unit + is CellMode.SpecialFlick -> { + if (isEditingMixedFlick() && mixedFlickDraft?.slots?.get(mode.direction) is MixedFlickSlot.Text) { + setMixedFlickSlot(mode, MixedFlickSlot.Text(text)) + } + } } } // 特殊フリック用アクション選択コールバック binding.specialFlickMappingsRecyclerView.setOnItemClickListener { _, _, idx, _ -> val mode = currentCellMode as? CellMode.SpecialFlick ?: return@setOnItemClickListener + val option = specialFlickActionOptions.getOrNull(idx) ?: return@setOnItemClickListener + if (isEditingMixedFlick()) { + val currentAction = (mixedFlickDraft?.slots?.get(mode.direction) as? MixedFlickSlot.Action)?.action + val action = resolveSpecialFlickSelectedAction( + selectedAction = option.action?.action, + currentAction = currentAction, + selectedTargetStableId = null, + validTargetStableIds = validTargetStableIds() + ) + setMixedFlickSlot(mode, MixedFlickSlot.Action(action)) + showMixedFlickSlot(mode) + return@setOnItemClickListener + } val item = currentSpecialFlickItems.firstOrNull { it.direction == mode.direction } - val selectedAction = specialFlickActionOptions.getOrNull(idx)?.action?.let { + val selectedAction = option.action?.let { resolveSpecialFlickSelectedAction( selectedAction = it.action, currentAction = item?.action, @@ -388,63 +407,53 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { binding.keyTypeChipGroup.setOnCheckedStateChangeListener { _, checkedIds -> updateLongPressControlsVisibility() - if (checkedIds.isEmpty()) { + val selectedChipId = checkedIds.firstOrNull() + if (selectedChipId == null) { updateDoneButtonState() - return@setOnCheckedStateChangeListener - } - val selectedChipId = checkedIds.first() - val isSpecialKey = selectedChipId == R.id.chip_special - - // Special key: show category selector (single/flick) - binding.textSpecialCategoryTitle.isVisible = isSpecialKey - binding.specialCategoryChipGroup.isVisible = isSpecialKey - updateSpecialKeyColorStyleVisibility(isSpecialKey) - - // Normal UI blocks - binding.textInputStyleTitle.isVisible = !isSpecialKey - binding.inputStyleChipGroup.isVisible = !isSpecialKey - binding.textOutputModeTitle.isVisible = !isSpecialKey - 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) - } - - // hide normal editors - binding.keyLabelLayout.isVisible = false - binding.flickGridEditorView.isVisible = false - binding.textSelectedDirection.isVisible = false - binding.textCharInputLayout.isVisible = false - - // show the right special editor - handleSpecialCategoryUi() } else { - // hide special editors - binding.keyActionLayout.isVisible = false - binding.customKeyboardTargetLayout.isVisible = false - binding.specialFlickEditorGroup.isVisible = false - updateSpecialKeyColorStyleVisibility(false) + showKeyTypeEditor(selectedChipId) + } + } - // normal key: input style controls which editor is visible - handleInputStyleUi() + binding.mixedFlickSlotTypeGroup.setOnCheckedStateChangeListener { _, checkedIds -> + if (updatingMixedFlickSlotType || !isEditingMixedFlick()) return@setOnCheckedStateChangeListener + val mode = currentCellMode as? CellMode.SpecialFlick ?: return@setOnCheckedStateChangeListener + val slot = when (checkedIds.firstOrNull()) { + R.id.chip_mixed_text -> MixedFlickSlot.Text() + R.id.chip_mixed_action -> MixedFlickSlot.Action() + R.id.chip_mixed_unassigned -> MixedFlickSlot.Unassigned + else -> return@setOnCheckedStateChangeListener } + setMixedFlickSlot(mode, slot) + showMixedFlickSlot(mode) + } - updateDoubleTapControlsVisibility() - updateDoneButtonState() + binding.mixedKeyLabelEdittext.doAfterTextChanged { text -> + mixedFlickDraft?.label = text?.toString().orEmpty() + } + + binding.mixedFlickTargetSpinner.setOnItemClickListener { _, _, position, _ -> + if (!isEditingMixedFlick()) return@setOnItemClickListener + val mode = currentCellMode as? CellMode.SpecialFlick ?: return@setOnItemClickListener + val target = customKeyboardTargetOptions.getOrNull(position) + ?.takeIf { it.isValid } ?: return@setOnItemClickListener + setMixedFlickSlot(mode, MixedFlickSlot.Action(KeyAction.MoveToCustomKeyboard(target.stableId))) + showMixedFlickSlot(mode) } // NEW: category change for special key binding.specialCategoryChipGroup.setOnCheckedStateChangeListener { _, checkedIds -> - if (checkedIds.isEmpty()) return@setOnCheckedStateChangeListener + if (checkedIds.isEmpty() || binding.keyTypeChipGroup.checkedChipId != R.id.chip_special) { + return@setOnCheckedStateChangeListener + } handleSpecialCategoryUi() updateDoneButtonState() } binding.inputStyleChipGroup.setOnCheckedStateChangeListener { _, checkedIds -> - if (checkedIds.isEmpty()) return@setOnCheckedStateChangeListener + if (checkedIds.isEmpty() || binding.keyTypeChipGroup.checkedChipId != R.id.chip_normal) { + return@setOnCheckedStateChangeListener + } val isPetal = checkedIds.first() == R.id.chip_petal_flick binding.chipToggleOutput.isEnabled = isPetal if (!isPetal && outputEditMode == OutputEditMode.TOGGLE) { @@ -492,7 +501,9 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { } binding.outputModeChipGroup.setOnCheckedStateChangeListener { _, checkedIds -> - if (checkedIds.isEmpty()) return@setOnCheckedStateChangeListener + if (checkedIds.isEmpty() || binding.keyTypeChipGroup.checkedChipId != R.id.chip_normal) { + return@setOnCheckedStateChangeListener + } outputEditMode = when (checkedIds.first()) { R.id.chip_toggle_output -> OutputEditMode.TOGGLE R.id.chip_long_press_output -> OutputEditMode.LONG_PRESS @@ -631,6 +642,111 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { } } + private fun showKeyTypeEditor(chipId: Int) { + val isNormal = chipId == R.id.chip_normal + val isSpecial = chipId == R.id.chip_special + val isMixed = chipId == R.id.chip_mixed + binding.textSpecialCategoryTitle.isVisible = isSpecial + binding.specialCategoryChipGroup.isVisible = isSpecial + updateSpecialKeyColorStyleVisibility(isSpecial) + + binding.textInputStyleTitle.isVisible = isNormal + binding.inputStyleChipGroup.isVisible = isNormal + binding.textOutputModeTitle.isVisible = isNormal + binding.outputModeChipGroup.isVisible = isNormal + + binding.mixedKeyLabelLayout.isVisible = isMixed + binding.mixedFlickSlotTypeGroup.isVisible = isMixed + binding.mixedFlickTargetLayout.isVisible = false + binding.textCharEdittext.isSaveEnabled = !isMixed + binding.specialFlickMappingsRecyclerView.isSaveEnabled = !isMixed + + binding.keyActionLayout.isVisible = false + binding.customKeyboardTargetLayout.isVisible = false + binding.specialFlickEditorGroup.isVisible = false + binding.circularFlickEditorGroup.isVisible = false + binding.editFreeFlickMap.isVisible = false + + when (chipId) { + R.id.chip_normal -> handleInputStyleUi() + R.id.chip_special -> { + if (binding.specialCategoryChipGroup.checkedChipId == View.NO_ID) { + binding.specialCategoryChipGroup.check(R.id.chip_special_single) + } + handleSpecialCategoryUi() + } + R.id.chip_mixed -> showMixedFlickEditor() + } + + updateDoubleTapControlsVisibility() + updateDoneButtonState() + } + + private fun isEditingMixedFlick(): Boolean = + binding.keyTypeChipGroup.checkedChipId == R.id.chip_mixed + + private fun showMixedFlickEditor() { + val draft = mixedFlickDraft ?: return + binding.qwertyKeyEditor.isVisible = false + binding.keyLabelLayout.isVisible = false + binding.flickGridEditorView.isVisible = true + updateIconOverrideVisibility() + + binding.mixedKeyLabelEdittext.setText(draft.label) + binding.flickGridEditorView.setSpecialFlickContent(emptyList(), specialFlickDisplayActions) + draft.slots.forEach { (direction, slot) -> + updateMixedFlickCell(CellMode.SpecialFlick(direction), slot) + } + val mode = CellMode.SpecialFlick(draft.selectedDirection) + binding.flickGridEditorView.setSelectedMode(mode) + currentCellMode = mode + showEditorForMode(mode) + } + + private fun showMixedFlickSlot(mode: CellMode.SpecialFlick) { + val draft = mixedFlickDraft ?: return + draft.selectedDirection = mode.direction + val slot = draft.slots[mode.direction] ?: MixedFlickSlot.Unassigned + updatingMixedFlickSlotType = true + binding.mixedFlickSlotTypeGroup.check( + when (slot) { + MixedFlickSlot.Unassigned -> R.id.chip_mixed_unassigned + is MixedFlickSlot.Text -> R.id.chip_mixed_text + is MixedFlickSlot.Action -> R.id.chip_mixed_action + } + ) + updatingMixedFlickSlotType = false + + binding.textCharInputLayout.isVisible = slot is MixedFlickSlot.Text + binding.textCharInputLayout.hint = getString(R.string.two_step_output_label) + binding.specialFlickEditorGroup.isVisible = slot is MixedFlickSlot.Action + if (slot is MixedFlickSlot.Text) setCharEditorValue(slot.output) + + val action = (slot as? MixedFlickSlot.Action)?.action + val actionLabel = action?.let(::displayActionForAction)?.displayName.orEmpty() + binding.specialFlickMappingsRecyclerView.setText(actionLabel, false) + + val targetId = (action as? KeyAction.MoveToCustomKeyboard)?.stableId + binding.mixedFlickTargetLayout.isVisible = targetId != null + val targetLabel = targetId?.takeIf(String::isNotEmpty)?.let { id -> + customKeyboardTargetOptions.firstOrNull { it.stableId == id }?.label + ?: getString(R.string.deleted_custom_keyboard_target) + } + binding.mixedFlickTargetSpinner.setText(targetLabel.orEmpty(), false) + } + + private fun setMixedFlickSlot(mode: CellMode.SpecialFlick, slot: MixedFlickSlot) { + mixedFlickDraft?.slots?.set(mode.direction, slot) + updateMixedFlickCell(mode, slot) + updateDoneButtonState() + } + + private fun updateMixedFlickCell(mode: CellMode.SpecialFlick, slot: MixedFlickSlot) { + val displayAction = (slot as? MixedFlickSlot.Action)?.action?.let(::displayActionForAction) + val label = (slot as? MixedFlickSlot.Text)?.output ?: displayAction?.displayName.orEmpty() + binding.flickGridEditorView.updateCellIcon(mode, displayAction?.iconResId, label) + } + private fun handleSpecialCategoryUi() { binding.qwertyKeyEditor.isVisible = false val isFlick = binding.specialCategoryChipGroup.checkedChipId == R.id.chip_special_flick @@ -647,7 +763,7 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { if (isFlick) { if (currentSpecialFlickItems.isEmpty()) { - currentSpecialFlickItems = allowedSpecialFlickDirections + currentSpecialFlickItems = specialFlickDirections .map { dir -> SpecialFlickMappingItem(direction = dir, action = null) } .toMutableList() } @@ -917,6 +1033,10 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { setCharEditorValue(value) } is CellMode.SpecialFlick -> { + if (isEditingMixedFlick()) { + showMixedFlickSlot(mode) + return + } val currentAction = currentSpecialFlickItems .firstOrNull { it.direction == mode.direction }?.action val currentName = currentAction?.let { act -> @@ -1107,7 +1227,7 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { private fun refreshCustomKeyboardTargetOptions(deletedStableId: String? = null) { customKeyboardTargetOptions = buildTargetOptions(customKeyboardTargets, deletedStableId) val labels = customKeyboardTargetOptions.map { it.label } - for (adapter in listOf(customKeyboardTargetAdapter, doubleTapTargetAdapter)) { + for (adapter in listOf(customKeyboardTargetAdapter, doubleTapTargetAdapter, mixedFlickTargetAdapter)) { adapter.clear() adapter.addAll(labels) adapter.notifyDataSetChanged() @@ -1249,7 +1369,7 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { } private fun updateDoneButtonState() { - if (outputEditMode != OutputEditMode.TOGGLE) { + if (outputEditMode != OutputEditMode.TOGGLE || isEditingMixedFlick()) { binding.textCharInputLayout.error = null } if (!selectedLongPressAction.isValidMoveToCustomKeyboardTarget(validTargetStableIds())) { @@ -1270,6 +1390,8 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { return } val isEnabled = when (binding.keyTypeChipGroup.checkedChipId) { + R.id.chip_mixed -> mixedFlickDraft?.canSave(validTargetStableIds()) == true + R.id.chip_special -> { val isFlick = binding.specialCategoryChipGroup.checkedChipId == R.id.chip_special_flick @@ -1382,10 +1504,14 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { } val key = currentKeyData!! - val savedLongPress = savedInstanceState?.takeIf { - key.isSpecialKey && selectedId == restoredEditingKeyIdentifier && - it.containsKey(STATE_LONG_PRESS_ACTION) - } + val savedKeyState = savedInstanceState?.takeIf { selectedId == restoredEditingKeyIdentifier } + val savedLongPress = savedKeyState?.takeIf { + key.isSpecialKey && it.containsKey(STATE_LONG_PRESS_ACTION) + } + val flickMapForMixed = state.layout.flickKeyMaps[key.keyId]?.firstOrNull() + ?: state.layout.flickKeyMaps[key.label]?.firstOrNull().orEmpty() + mixedFlickDraft = savedKeyState?.getBundle(STATE_MIXED_FLICK)?.let(MixedFlickEditorState::fromBundle) + ?: MixedFlickEditorState.fromKey(key, flickMapForMixed) val savedAction = savedLongPress?.getString(STATE_LONG_PRESS_ACTION) updateLongPressAction( when { @@ -1450,7 +1576,7 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { if (isSpecialFlick) { binding.specialCategoryChipGroup.check(R.id.chip_special_flick) - currentSpecialFlickItems = allowedSpecialFlickDirections.map { dir -> + currentSpecialFlickItems = specialFlickDirections.map { dir -> val saved = flickMap[dir] as? FlickAction.Action SpecialFlickMappingItem(direction = dir, action = saved?.action) }.toMutableList() @@ -1589,6 +1715,17 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { handleInputStyleUi() } + val restoredType = savedKeyState?.getInt(STATE_KEY_TYPE, View.NO_ID) ?: View.NO_ID + val desiredType = when { + restoredType == R.id.chip_mixed -> restoredType + key.keyType == KeyType.MIXED_FLICK && restoredType in listOf(R.id.chip_normal, R.id.chip_special) -> + restoredType + key.keyType == KeyType.MIXED_FLICK -> R.id.chip_mixed + else -> binding.keyTypeChipGroup.checkedChipId + } + if (desiredType != binding.keyTypeChipGroup.checkedChipId) { + binding.keyTypeChipGroup.check(desiredType) + } updateDoneButtonState() } } @@ -1993,6 +2130,24 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { val newDrawableResId: Int? when (binding.keyTypeChipGroup.checkedChipId) { + R.id.chip_mixed -> { + val draft = mixedFlickDraft ?: return + if (!draft.canSave(validTargetStableIds())) return + newKeyType = KeyType.MIXED_FLICK + isSpecial = false + newLabel = draft.label.trim() + newFlickMap = draft.slots.mapNotNull { (direction, slot) -> + slot.toFlickAction()?.let { direction to it } + }.toMap() + newAction = when (val tap = newFlickMap.getValue(FlickDirection.TAP)) { + is FlickAction.Input -> KeyAction.Text(tap.char) + is FlickAction.Action -> tap.action + } + newDrawableResId = null + newLongPressFlickMap = emptyMap() + newTwoStepLongPressMap = emptyMap() + } + R.id.chip_special -> { val isFlick = binding.specialCategoryChipGroup.checkedChipId == R.id.chip_special_flick @@ -2234,7 +2389,10 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { ) } if (newAction == KeyAction.VoiceInput || newDoubleTapBinding?.action == KeyAction.VoiceInput || - newLongPressAction == KeyAction.VoiceInput + newLongPressAction == KeyAction.VoiceInput || + (newKeyType == KeyType.MIXED_FLICK && newFlickMap.values.any { + (it as? FlickAction.Action)?.action == KeyAction.VoiceInput + }) ) { val hasPermission = ContextCompat.checkSelfPermission( requireContext(), @@ -2326,6 +2484,10 @@ class KeyEditorFragment : Fragment(R.layout.fragment_key_editor) { } } freeFlickDraft?.let { outState.putString("freeFlickDraft", PopupKeyConfigCodec.encode(it)) } + if (_binding != null) { + outState.putInt(STATE_KEY_TYPE, binding.keyTypeChipGroup.checkedChipId) + mixedFlickDraft?.let { outState.putBundle(STATE_MIXED_FLICK, it.toBundle()) } + } if (_binding != null && freeFlickDraft != null) { outState.putInt("freeFlickInputStyle", binding.inputStyleChipGroup.checkedChipId) } diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickEditorState.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickEditorState.kt new file mode 100644 index 000000000..f19430b8b --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickEditorState.kt @@ -0,0 +1,107 @@ +package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui + +import android.os.Bundle +import androidx.core.os.bundleOf +import com.kazumaproject.custom_keyboard.data.FlickAction +import com.kazumaproject.custom_keyboard.data.FlickDirection +import com.kazumaproject.custom_keyboard.data.KeyAction +import com.kazumaproject.custom_keyboard.data.KeyActionMapper +import com.kazumaproject.custom_keyboard.data.KeyData + +internal val specialFlickDirections = listOf( + FlickDirection.TAP, + FlickDirection.UP, + FlickDirection.DOWN, + FlickDirection.UP_LEFT, + FlickDirection.UP_RIGHT +) + +internal sealed interface MixedFlickSlot { + data object Unassigned : MixedFlickSlot + data class Text(val output: String = "") : MixedFlickSlot + data class Action(val action: KeyAction? = null) : MixedFlickSlot + + fun toFlickAction(): FlickAction? = when (this) { + Unassigned -> null + is Text -> output.takeIf(String::isNotEmpty)?.let { FlickAction.Input(it) } + is Action -> action?.let { FlickAction.Action(it) } + } + + companion object { + fun fromFlickAction(action: FlickAction?): MixedFlickSlot = when (action) { + is FlickAction.Input -> if (action.char.isEmpty()) Unassigned else Text(action.char) + is FlickAction.Action -> when (val keyAction = action.action) { + is KeyAction.Text -> Text(keyAction.text) + is KeyAction.InputText -> Text(keyAction.text) + else -> Action(keyAction) + } + null -> Unassigned + } + } +} + +internal class MixedFlickEditorState( + val slots: MutableMap, + var label: String, + var selectedDirection: FlickDirection = FlickDirection.TAP +) { + fun canSave(validTargetIds: Set): Boolean = + slots[FlickDirection.TAP]?.toFlickAction() != null && + slots.values.all { (it as? MixedFlickSlot.Action)?.action.isValidMoveToCustomKeyboardTarget(validTargetIds) } + + fun toBundle(): Bundle = bundleOf( + "label" to label, + "selectedDirection" to selectedDirection.name, + "slots" to Bundle().apply { + slots.forEach { (direction, slot) -> + val value = when (slot) { + MixedFlickSlot.Unassigned -> null + is MixedFlickSlot.Text -> bundleOf("text" to slot.output) + is MixedFlickSlot.Action -> bundleOf( + "action" to KeyActionMapper.fromKeyAction(slot.action), + "pendingTarget" to (slot.action == KeyAction.MoveToCustomKeyboard("")) + ) + } + putBundle(direction.name, value) + } + } + ) + + companion object { + fun fromKey(key: KeyData, flickMap: Map): MixedFlickEditorState { + val slots = specialFlickDirections.associateWith { direction -> + val alternate = when (direction) { + FlickDirection.UP_LEFT -> flickMap[FlickDirection.UP_LEFT_FAR] + FlickDirection.UP_RIGHT -> flickMap[FlickDirection.UP_RIGHT_FAR] + else -> null + } + val fallback = key.action?.takeIf { direction == FlickDirection.TAP } + ?.let { FlickAction.Action(it) } + val saved = flickMap[direction] ?: alternate + MixedFlickSlot.fromFlickAction( + saved?.takeUnless { it is FlickAction.Input && it.char.isEmpty() } ?: fallback + ) + }.toMutableMap() + return MixedFlickEditorState(slots, key.label.takeUnless { key.isSpecialKey }.orEmpty()) + } + + fun fromBundle(bundle: Bundle): MixedFlickEditorState { + val savedSlots = bundle.getBundle("slots") + return MixedFlickEditorState( + slots = specialFlickDirections.associateWith { direction -> + val slot = savedSlots?.getBundle(direction.name) + when { + slot == null -> MixedFlickSlot.Unassigned + slot.containsKey("text") -> MixedFlickSlot.Text(slot.getString("text").orEmpty()) + slot.getBoolean("pendingTarget") -> MixedFlickSlot.Action(KeyAction.MoveToCustomKeyboard("")) + else -> MixedFlickSlot.Action(KeyActionMapper.toKeyAction(slot.getString("action"))) + } + }.toMutableMap(), + label = bundle.getString("label").orEmpty(), + selectedDirection = specialFlickDirections.firstOrNull { + it.name == bundle.getString("selectedDirection") + } ?: FlickDirection.TAP + ) + } + } +} diff --git a/app/src/main/res/layout/fragment_key_editor.xml b/app/src/main/res/layout/fragment_key_editor.xml index f7bd01979..30b9e7019 100644 --- a/app/src/main/res/layout/fragment_key_editor.xml +++ b/app/src/main/res/layout/fragment_key_editor.xml @@ -27,6 +27,7 @@ android:id="@+id/key_type_chip_group" android:layout_width="wrap_content" android:layout_height="wrap_content" + app:selectionRequired="true" app:singleSelection="true"> + + @@ -326,6 +335,23 @@ android:maxLines="1" /> + + + + + + + + + + + + + + + + + + + 挿入方向切替 通常キー 特別なキー + 混在キー + 未設定 + 文字入力 + 特殊アクション キーの表示ラベル キーのアクション ダブルタップのアクション diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e5aa8efe7..0fc50afa6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -823,6 +823,10 @@ Cycle target Normal Key Special Key + Mixed Key + Unassigned + Text Input + Special Action Label for Key Display Action for Key Double-tap action diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickKeyEditorTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickKeyEditorTest.kt new file mode 100644 index 000000000..458e8d82f --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickKeyEditorTest.kt @@ -0,0 +1,143 @@ +package com.kazumaproject.markdownhelperkeyboard.custom_keyboard.ui + +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.view.ContextThemeWrapper +import android.view.LayoutInflater +import android.widget.AutoCompleteTextView +import androidx.core.view.isVisible +import androidx.fragment.app.FragmentHostCallback +import androidx.test.core.app.ApplicationProvider +import com.kazumaproject.custom_keyboard.data.FlickAction +import com.kazumaproject.custom_keyboard.data.FlickDirection +import com.kazumaproject.custom_keyboard.data.KeyAction +import com.kazumaproject.custom_keyboard.data.KeyActionMapper +import com.kazumaproject.custom_keyboard.data.KeyData +import com.kazumaproject.custom_keyboard.data.KeyType +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.data.CustomKeyboardLayout +import com.kazumaproject.markdownhelperkeyboard.databinding.FragmentKeyEditorBinding +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers +import org.robolectric.util.ReflectionHelpers.ClassParameter + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class MixedFlickKeyEditorTest { + @Test + fun eachCellCanSwitchBetweenTextActionAndUnassigned() { + val draft = MixedFlickEditorState.fromKey(blankKey, emptyMap()) + val (_, binding) = editor(draft) + assertFalse(binding.buttonDone.isEnabled) + assertFalse(binding.textCharInputLayout.isVisible) + + binding.chipMixedText.performClick() + assertTrue(binding.textCharInputLayout.isVisible) + binding.textCharEdittext.setText("かな") + assertTrue(binding.buttonDone.isEnabled) + + binding.flickGridEditorView.onCellSelected?.invoke(CellMode.SpecialFlick(FlickDirection.UP)) + binding.chipMixedAction.performClick() + assertFalse(binding.textCharInputLayout.isVisible) + assertTrue(binding.specialFlickEditorGroup.isVisible) + val deleteLabel = KeyActionMapper.getDisplayActions(binding.root.context) + .first { it.action == KeyAction.Delete }.displayName + binding.specialFlickMappingsRecyclerView.select(deleteLabel) + assertEquals(MixedFlickSlot.Action(KeyAction.Delete), draft.slots[FlickDirection.UP]) + assertEquals(MixedFlickSlot.Text("かな"), draft.slots[FlickDirection.TAP]) + + binding.chipMixedUnassigned.performClick() + assertEquals(MixedFlickSlot.Unassigned, draft.slots[FlickDirection.UP]) + assertTrue(binding.buttonDone.isEnabled) + binding.flickGridEditorView.onCellSelected?.invoke(CellMode.SpecialFlick(FlickDirection.TAP)) + binding.chipMixedUnassigned.performClick() + assertFalse(binding.buttonDone.isEnabled) + } + + @Test + fun switchTargetsAndSelectionSurviveSavingTheDraft() { + val move = KeyAction.MoveToCustomKeyboard("first") + val draft = MixedFlickEditorState.fromKey( + blankKey.copy(keyType = KeyType.MIXED_FLICK, action = move), + mapOf( + FlickDirection.TAP to FlickAction.Action(move), + FlickDirection.UP_RIGHT to FlickAction.Action(move) + ) + ) + val (fragment, binding) = editor(draft) + binding.flickGridEditorView.onCellSelected?.invoke(CellMode.SpecialFlick(FlickDirection.UP_RIGHT)) + binding.mixedFlickTargetSpinner.select("Second") + binding.mixedKeyLabelEdittext.setText("Switch") + + val saved = Bundle() + fragment.onSaveInstanceState(saved) + val restored = MixedFlickEditorState.fromBundle(requireNotNull(saved.getBundle("mixedFlickDraft"))) + val (_, restoredBinding) = editor(restored) + assertEquals("Switch", restoredBinding.mixedKeyLabelEdittext.text.toString()) + assertEquals(CellMode.SpecialFlick(FlickDirection.UP_RIGHT), restoredBinding.flickGridEditorView.getCurrentMode()) + assertEquals("Second", restoredBinding.mixedFlickTargetSpinner.text.toString()) + assertEquals(MixedFlickSlot.Action(move), restored.slots[FlickDirection.TAP]) + + restoredBinding.flickGridEditorView.onCellSelected?.invoke(CellMode.SpecialFlick(FlickDirection.TAP)) + assertEquals("First", restoredBinding.mixedFlickTargetSpinner.text.toString()) + assertTrue(restoredBinding.buttonDone.isEnabled) + } + + @Test + fun convertingAPetalKeyRetainsItsTapAndNormalizesLeftAndRight() { + val draft = MixedFlickEditorState.fromKey( + blankKey.copy(label = "Label", keyType = KeyType.PETAL_FLICK, action = KeyAction.Text("center")), + mapOf( + FlickDirection.UP_LEFT_FAR to FlickAction.Input("left"), + FlickDirection.UP_RIGHT_FAR to FlickAction.Input("right") + ) + ) + assertEquals("Label", draft.label) + assertEquals(MixedFlickSlot.Text("center"), draft.slots[FlickDirection.TAP]) + assertEquals(MixedFlickSlot.Text("left"), draft.slots[FlickDirection.UP_LEFT]) + assertEquals(MixedFlickSlot.Text("right"), draft.slots[FlickDirection.UP_RIGHT]) + } + + private fun editor(draft: MixedFlickEditorState): Pair { + val context = ContextThemeWrapper(ApplicationProvider.getApplicationContext(), R.style.Theme_MarkdownKeyboard) + val binding = FragmentKeyEditorBinding.inflate(LayoutInflater.from(context)) + val fragment = KeyEditorFragment() + val host = object : FragmentHostCallback(context, Handler(Looper.getMainLooper()), 0) { + override fun onGetHost(): Any = this + } + ReflectionHelpers.setField(fragment, "mHost", host) + ReflectionHelpers.setField(fragment, "_binding", binding) + ReflectionHelpers.setField(fragment, "mixedFlickDraft", draft) + ReflectionHelpers.setField( + fragment, + "customKeyboardTargets", + listOf( + CustomKeyboardLayout(name = "First", columnCount = 1, rowCount = 1, stableId = "first"), + CustomKeyboardLayout(name = "Second", columnCount = 1, rowCount = 1, stableId = "second") + ) + ) + ReflectionHelpers.callInstanceMethod(fragment, "setupGridEditor") + ReflectionHelpers.callInstanceMethod(fragment, "setupUIListeners") + ReflectionHelpers.callInstanceMethod( + fragment, + "refreshCustomKeyboardTargetOptions", + ClassParameter.from(String::class.java, null) + ) + binding.keyTypeChipGroup.check(R.id.chip_mixed) + return fragment to binding + } + + private fun AutoCompleteTextView.select(label: String) { + val position = (0 until adapter.count).first { adapter.getItem(it) == label } + onItemClickListener.onItemClick(null, null, position, position.toLong()) + } + + private val blankKey = KeyData(label = "", row = 0, column = 0, isFlickable = false) +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickPersistenceTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickPersistenceTest.kt new file mode 100644 index 000000000..a0bb2abdb --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/custom_keyboard/ui/MixedFlickPersistenceTest.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.FlickAction +import com.kazumaproject.custom_keyboard.data.FlickDirection +import com.kazumaproject.custom_keyboard.data.KeyAction +import com.kazumaproject.custom_keyboard.data.KeyData +import com.kazumaproject.custom_keyboard.data.KeyType +import com.kazumaproject.custom_keyboard.data.KeyboardLayout +import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.data.toFlickAction +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.assertEquals +import org.junit.Assert.assertTrue +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 MixedFlickPersistenceTest { + @Test + fun mixedAssignmentsSurviveTheEditorRoomAndJsonBackup() = runBlocking { + val database = Room.inMemoryDatabaseBuilder( + ApplicationProvider.getApplicationContext(), + AppDatabase::class.java + ).allowMainThreadQueries().build() + try { + val repository = KeyboardRepository(database.keyboardLayoutDao()) + val key = KeyData(label = "", row = 0, column = 0, isFlickable = false, keyId = "key") + val layout = KeyboardLayout(listOf(key), emptyMap(), columnCount = 1, rowCount = 1) + val targetId = repository.saveLayout(layout, "Target", null) + val target = repository.getLayoutsNotFlowEnsuringStableIds().single { it.layoutId == targetId } + val editor = KeyboardEditorViewModel(repository) + editor.applyTemplate(layout) + val editorKey = editor.uiState.value.layout.keys.single() + val assignments = mapOf( + FlickDirection.TAP to FlickAction.Input("かな"), + FlickDirection.UP to FlickAction.Action(KeyAction.Delete), + FlickDirection.DOWN to FlickAction.Action(KeyAction.SwitchToKanaLayout), + FlickDirection.UP_RIGHT to FlickAction.Action(KeyAction.MoveToCustomKeyboard(target.stableId)) + ) + assertTrue( + editor.updateKeyAndMappings( + editorKey.copy(keyType = KeyType.MIXED_FLICK, action = KeyAction.Text("かな")), + assignments, emptyMap(), emptyMap(), emptyMap() + ) + ) + val layoutId = repository.saveLayout(editor.uiState.value.layout, "Mixed", null) + val reloaded = repository.getFullLayout(layoutId).first() + val reloadedKey = reloaded.keys.single() + assertEquals(KeyType.MIXED_FLICK, reloadedKey.keyType) + assertEquals(KeyAction.Text("かな"), reloadedKey.action) + val map = reloaded.flickKeyMaps.getValue(reloadedKey.keyId!!).single() + val expectedSlots = assignments.mapValues { MixedFlickSlot.fromFlickAction(it.value) } + assertEquals(expectedSlots, map.mapValues { MixedFlickSlot.fromFlickAction(it.value) }) + + val json = KeyboardLayoutJsonExporter.toJson(repository.getAllFullLayoutsForExport()) + val imported = (KeyboardLayoutJsonImporter.parse(json) as KeyboardLayoutImportResult.Success) + .layouts.single { it.layout.name == "Mixed" }.keysWithFlicks.single() + assertEquals(KeyType.MIXED_FLICK, imported.key.keyType) + val importedSlots = imported.flicks.associate { + it.flickDirection to MixedFlickSlot.fromFlickAction(it.toFlickAction()) + } + assertEquals(expectedSlots, importedSlots) + } finally { + database.close() + } + } +} diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/CrossFlickInputController.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/CrossFlickInputController.kt index 7080c92d1..6a75311cc 100644 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/CrossFlickInputController.kt +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/controller/CrossFlickInputController.kt @@ -115,6 +115,7 @@ class CrossFlickInputController( private var activeGestureConfig: GestureSessionConfig? = null private var flickActionMap: Map = emptyMap() + private var previewsActionText = false private var actionDisplayTransform: (FlickAction) -> FlickAction = { it } private var textMap: Map = emptyMap() private var longPressTextMap: Map = emptyMap() @@ -207,10 +208,10 @@ class CrossFlickInputController( dismissAllPopups(clearDirectionalCache = true) } - // ACTION モードでビューにアタッチする。CROSS_FLICK キー(アイコン付き特殊キー)向け。 @SuppressLint("ClickableViewAccessibility") - fun attach(view: View, map: Map) { + fun attach(view: View, map: Map, previewText: Boolean = false) { inputMode = InputMode.ACTION + previewsActionText = previewText flickActionMap = map.mapValues { (_, action) -> action.withDisplayMetadata() } textMap = emptyMap() longPressTextMap = emptyMap() @@ -302,6 +303,9 @@ class CrossFlickInputController( resolveText(currentDirection, preferLongPress = isLongPressMode), currentDirection != FlickDirection.TAP ) + } else if (previewsActionText) { + val text = (resolveAction(currentDirection) as? FlickAction.Input)?.char + listener?.onTextSelectionChanged(text, currentDirection != FlickDirection.TAP) } } updatePopupFingerFeedback(event.rawX, event.rawY) diff --git a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyIconResolver.kt b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyIconResolver.kt index 301ec4965..5a9cbaf6d 100644 --- a/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyIconResolver.kt +++ b/custom_keyboard/src/main/java/com/kazumaproject/custom_keyboard/data/KeyIconResolver.kt @@ -22,8 +22,21 @@ object KeyIconResolver { fun hasIconOverride(keyData: KeyData): Boolean = keyData.icon?.isOverride() == true - fun resolvedLabelForRendering(keyData: KeyData): String = - if (suppressesDoNothingDefaultContent(keyData)) "" else keyData.label + fun resolvedLabelForRendering(keyData: KeyData, context: Context? = null): String { + if (suppressesDoNothingDefaultContent(keyData)) return "" + if (keyData.keyType != KeyType.MIXED_FLICK || keyData.label.isNotEmpty()) return keyData.label + + return when (val action = keyData.action) { + is KeyAction.Text -> action.text + is KeyAction.InputText -> action.text + null -> "" + else -> context?.let { + KeyActionMapper.getDisplayActions(it).firstOrNull { option -> + option.action::class == action::class + }?.displayName + } ?: KeyActionMapper.fromKeyAction(action).orEmpty() + } + } fun shouldTintIcon(icon: KeyIconRef?, fallbackResId: Int?): Boolean { return when (icon?.type) { 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 1166b9f5c..a84d3db0b 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 @@ -641,7 +641,10 @@ enum class KeyType { FLICK_LONG_PRESS, /** Configurable key preview and a grid of long-press alternatives. */ - QWERTY + QWERTY, + + /** A tap and four flick directions that can each input text or run an action. */ + MIXED_FLICK } enum class ShapeType { 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 75b9b73f0..f61726493 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 @@ -1072,7 +1072,9 @@ class FlickKeyboardView @JvmOverloads constructor( private fun shouldTransformMainLabel(keyData: KeyData): Boolean { if (keyData.action is KeyAction.Text) return true - return !keyData.isSpecialKey && keyData.keyType != KeyType.NORMAL + return !keyData.isSpecialKey && + keyData.keyType != KeyType.NORMAL && + keyData.keyType != KeyType.MIXED_FLICK } /** Standard mode labels use the same text sizing as other special keys. */ @@ -1096,7 +1098,7 @@ class FlickKeyboardView @JvmOverloads constructor( return keyData.qwertyConfig?.layer(keyCharacterCase)?.displayLabel ?: keyData.label } modeSwitchLabelForDisplay(keyData)?.let { return it } - val canonicalLabel = KeyIconResolver.resolvedLabelForRendering(keyData) + val canonicalLabel = KeyIconResolver.resolvedLabelForRendering(keyData, context) return if (shouldTransformMainLabel(keyData)) { transformInputTextForDisplay(canonicalLabel) } else { @@ -2011,7 +2013,8 @@ class FlickKeyboardView @JvmOverloads constructor( } } - KeyType.CROSS_FLICK -> { + KeyType.CROSS_FLICK, KeyType.MIXED_FLICK -> { + val isMixedFlick = keyData.keyType == KeyType.MIXED_FLICK val rawFlickActionMap = keyData.keyId?.let { layout.flickKeyMaps[it] }?.firstOrNull() ?: layout.flickKeyMaps[keyData.label]?.firstOrNull() @@ -2043,6 +2046,11 @@ class FlickKeyboardView @JvmOverloads constructor( } override fun onPress(action: KeyAction, direction: FlickDirection) { + if (isMixedFlick) { + if (action is KeyAction.Text) notifyTextPress(keyData, action.text) + else this@FlickKeyboardView.listener?.onPress(action) + return + } when ( val resolved = resolveSumireSpecialKeyOverride( keyData, @@ -2085,6 +2093,11 @@ class FlickKeyboardView @JvmOverloads constructor( isFlick: Boolean, direction: FlickDirection ) { + if (isMixedFlick) { + if (fallbackAction != null) dispatchCommittedKeyAction(keyData, fallbackAction, isFlick) + else cancelTextPreview(keyData) + return + } dispatchSumireSpecialKeyRuntimeAction( keyData = keyData, flickDirection = direction, @@ -2100,8 +2113,28 @@ class FlickKeyboardView @JvmOverloads constructor( } } + override fun onTextSelectionChanged(text: String?, isFlick: Boolean) { + if (!isMixedFlick) return + val action = text?.takeIf(String::isNotEmpty)?.let { KeyAction.Text(it) } + if (action != null && canPreviewText(keyData, action) && + previewKeyData != keyData && !independentTextPreviews.containsKey(keyData) + ) { + beginTextPreview(keyData, FlickTextSelection(action.text, isFlick)) + } else { + updateTextPreview(keyData, text, isFlick) + } + } + + override fun onCanceled() { + if (isMixedFlick) cancelTextPreview(keyData) + } + override fun onFlickLongPress(action: KeyAction) { if (action is KeyAction.Text) return + if (isMixedFlick) { + if (action == KeyAction.DoNothing) return + cancelTextPreview(keyData) + } doubleTapActionDispatcher.interrupt() if (usesDefaultActionAfterLongPress(action)) return longPressOwnerKeyData = keyData @@ -2112,6 +2145,19 @@ class FlickKeyboardView @JvmOverloads constructor( action: KeyAction, isFlick: Boolean ) { + if (isMixedFlick) { + when (action) { + is KeyAction.Text -> { + dispatchCommittedKeyAction(keyData, action, isFlick, isLongPress = true) + return + } + KeyAction.Cancel, KeyAction.DoNothing -> { + cancelTextPreview(keyData) + return + } + else -> Unit + } + } if (action is KeyAction.Text) return if (usesDefaultActionAfterLongPress(action)) { dispatchNonTapAction(action, isFlick) @@ -2127,7 +2173,10 @@ class FlickKeyboardView @JvmOverloads constructor( action: KeyAction, direction: FlickDirection ) { - if (action !is KeyAction.Text && !usesDefaultActionAfterLongPress(action)) { + if (action !is KeyAction.Text && + (!isMixedFlick || action != KeyAction.DoNothing) && + !usesDefaultActionAfterLongPress(action) + ) { this@FlickKeyboardView.listener?.onLongPressActionCanceled( action ) @@ -2135,7 +2184,7 @@ class FlickKeyboardView @JvmOverloads constructor( } } - attach(keyView, displayFlickActionMap) + attach(keyView, displayFlickActionMap, previewText = isMixedFlick) } when (themeMode) { @@ -3039,15 +3088,18 @@ class FlickKeyboardView @JvmOverloads constructor( val action = KeyAction.Text(character) if (character.isNotEmpty()) listener?.onPress(action) if (character.isNotEmpty() && canPreviewText(keyData, action)) { - previewKeyData = keyData - val selection = FlickTextSelection(character, false) - if (independentMultiTouchForCurrentGesture) independentTextPreviews[keyData] = selection - flickTextPreviewEmitter.begin(selection) + beginTextPreview(keyData, FlickTextSelection(character, false)) } else { cancelTextPreview() } } + private fun beginTextPreview(keyData: KeyData, selection: FlickTextSelection) { + previewKeyData = keyData + if (independentMultiTouchForCurrentGesture) independentTextPreviews[keyData] = selection + flickTextPreviewEmitter.begin(selection) + } + private fun updateTextPreview(keyData: KeyData, character: String?, isFlick: Boolean) { val selection = FlickTextSelection(character, isFlick) if (independentMultiTouchForCurrentGesture) { diff --git a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardViewTouchDispatchTest.kt b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardViewTouchDispatchTest.kt index a03d6f00e..58307c862 100644 --- a/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardViewTouchDispatchTest.kt +++ b/custom_keyboard/src/test/java/com/kazumaproject/custom_keyboard/view/FlickKeyboardViewTouchDispatchTest.kt @@ -178,6 +178,85 @@ class FlickKeyboardViewTouchDispatchTest { assertTrue(listener.actions == listOf(KeyAction.Paste)) } + @Test + fun mixedFlickCommitsTextAndActionsFromTheSameKey() { + val listener = RecordingKeyboardActionListener() + val keyboard = keyboardView(listener) + keyboard.setKeyboard(mixedFlickLayout()) + layoutKeyboard(keyboard) + + val key = keyboard.getChildAt(0) as AutoSizeButton + assertEquals("a", key.text.toString()) + keyboard.setKeyCharacterCase(KeyCharacterCase.UPPERCASE) + assertEquals("A", key.text.toString()) + val x = key.centerX() + val y = key.centerY() + + fun touch(deltaX: Float, deltaY: Float, time: Long, release: Int = MotionEvent.ACTION_UP) { + keyboard.dispatchTouch(MotionEvent.ACTION_DOWN, x, y, time, time) + keyboard.dispatchTouch(MotionEvent.ACTION_MOVE, x + deltaX, y + deltaY, time, time + 10L) + keyboard.dispatchTouch(release, x + deltaX, y + deltaY, time, time + 20L) + } + + touch(0f, 0f, 100L) + touch(-80f, 0f, 200L) + touch(80f, 0f, 300L) + touch(0f, -100f, 400L) + touch(0f, 100f, 500L) // Unassigned + touch(0f, -100f, 600L, MotionEvent.ACTION_CANCEL) + + assertEquals( + listOf(KeyAction.Text("a"), KeyAction.Text("left"), KeyAction.MoveCursorRight, KeyAction.Delete), + listener.actions + ) + } + + @Test + fun holdingMixedTextCommitsItOnRelease() { + val listener = RecordingKeyboardActionListener() + val keyboard = keyboardView(listener) + keyboard.setLongPressTimeout(200L) + keyboard.setKeyboard(mixedFlickLayout()) + layoutKeyboard(keyboard) + val key = keyboard.getChildAt(0) + val time = SystemClock.uptimeMillis() + + keyboard.dispatchTouch(MotionEvent.ACTION_DOWN, key.centerX(), key.centerY(), time, time) + shadowOf(Looper.getMainLooper()).idleFor(210, TimeUnit.MILLISECONDS) + assertTrue(listener.actions.isEmpty()) + assertTrue(listener.flickLongPresses.isEmpty()) + keyboard.dispatchTouch(MotionEvent.ACTION_UP, key.centerX(), key.centerY(), time, time + 220L) + + assertEquals(listOf(KeyAction.Text("a")), listener.actions) + } + + private fun mixedFlickLayout(): KeyboardLayout { + val key = KeyData( + label = "", + row = 0, + column = 0, + isFlickable = true, + action = KeyAction.Text("a"), + keyId = "mixed", + keyType = KeyType.MIXED_FLICK + ) + return KeyboardLayout( + keys = listOf(key), + flickKeyMaps = mapOf( + "mixed" to listOf( + mapOf( + FlickDirection.TAP to FlickAction.Input("a"), + FlickDirection.UP_LEFT to FlickAction.Input("left"), + FlickDirection.UP_RIGHT to FlickAction.Action(KeyAction.MoveCursorRight), + FlickDirection.UP to FlickAction.Action(KeyAction.Delete) + ) + ) + ), + columnCount = 1, + rowCount = 1 + ) + } + private fun keyboardView( listener: FlickKeyboardView.OnKeyboardActionListener, context: Context = ApplicationProvider.getApplicationContext()