diff --git a/app/src/main/java/helium314/keyboard/keyboard/KeyboardSwitcher.kt b/app/src/main/java/helium314/keyboard/keyboard/KeyboardSwitcher.kt index 87f99b70e..f894e8993 100644 --- a/app/src/main/java/helium314/keyboard/keyboard/KeyboardSwitcher.kt +++ b/app/src/main/java/helium314/keyboard/keyboard/KeyboardSwitcher.kt @@ -556,6 +556,8 @@ class KeyboardSwitcher private constructor() : KeyboardState.SwitchActions { } else { mTouchpadView?.visibility = View.GONE } + // Any return to the main keyboard ends the touchpad, so bring back the one-handed controls it hid + mKeyboardViewWrapper?.oneHandedControlsHidden = PointerTracker.sPersistentTouchpadModeActive && visibility == View.VISIBLE } override fun setEmojiKeyboard() { @@ -1013,8 +1015,14 @@ class KeyboardSwitcher private constructor() : KeyboardState.SwitchActions { fun setOneHandedModeEnabled(enabled: Boolean, force: Boolean) { val wrapper = mKeyboardViewWrapper ?: return - if (!force && wrapper.oneHandedModeEnabled == enabled) return val settings = Settings.getInstance() + if (!force && wrapper.oneHandedModeEnabled == enabled) { + // The side is stored per orientation and split state, so keep it in sync on every keyboard load, + // otherwise the wrapper keeps a stale side and the switch button flips from the wrong one. + val gravity = settings.current.mOneHandedModeGravity + if (enabled && wrapper.oneHandedGravity != gravity) wrapper.oneHandedGravity = gravity + return + } wrapper.oneHandedModeEnabled = enabled wrapper.oneHandedGravity = settings.current.mOneHandedModeGravity settings.writeOneHandedModeEnabled(enabled) @@ -1043,11 +1051,7 @@ class KeyboardSwitcher private constructor() : KeyboardState.SwitchActions { kbView.visibility = View.INVISIBLE mEmojiPalettesView?.visibility = View.GONE mClipboardHistoryView?.visibility = View.GONE - mKeyboardViewWrapper?.let { wrapper -> - wrapper.findViewById(R.id.btn_stop_one_handed_mode)?.visibility = View.GONE - wrapper.findViewById(R.id.btn_switch_one_handed_mode)?.visibility = View.GONE - wrapper.findViewById(R.id.btn_resize_one_handed_mode)?.visibility = View.GONE - } + mKeyboardViewWrapper?.oneHandedControlsHidden = true if (Settings.getValues().mTouchpadFullscreen) { mStripContainer?.visibility = View.GONE requestInputViewLayoutAndInsets() @@ -1107,11 +1111,7 @@ class KeyboardSwitcher private constructor() : KeyboardState.SwitchActions { mSuggestionStripView?.updateSplitToolbarState() requestInputViewLayoutAndInsets() mKeyboardViewWrapper?.let { wrapper -> - if (wrapper.oneHandedModeEnabled) { - wrapper.findViewById(R.id.btn_stop_one_handed_mode)?.visibility = View.VISIBLE - wrapper.findViewById(R.id.btn_switch_one_handed_mode)?.visibility = View.VISIBLE - wrapper.findViewById(R.id.btn_resize_one_handed_mode)?.visibility = View.VISIBLE - } + wrapper.oneHandedControlsHidden = false wrapper.requestLayout() } } diff --git a/app/src/main/java/helium314/keyboard/keyboard/KeyboardView.kt b/app/src/main/java/helium314/keyboard/keyboard/KeyboardView.kt index 11455412d..78e3db2cb 100644 --- a/app/src/main/java/helium314/keyboard/keyboard/KeyboardView.kt +++ b/app/src/main/java/helium314/keyboard/keyboard/KeyboardView.kt @@ -560,6 +560,19 @@ open class KeyboardView @JvmOverloads constructor( } } + // Emoji glyphs are taller than the reference char and fitting above is by width only, so a glyph could + // reach into the next row and get cut when that row's keys are redrawn. Fit and center by real bounds. + if (isEmojiKey && this is EmojiPageKeyboardView && !isEmoticonInEmojiKeyboard) { + val bounds = android.graphics.Rect() + paint.getTextBounds(label, 0, label.length, bounds) + val maxHeight = keyHeight * 0.9f + if (bounds.height() > maxHeight) { + paint.textSize = paint.textSize * (maxHeight / bounds.height()) + paint.getTextBounds(label, 0, label.length, bounds) + } + if (bounds.height() > 0) labelBaseline = centerY - bounds.exactCenterY() + } + if (key.isEnabled) { val isTextEditMode = KeyboardActionListenerImpl.sPersistentTextEditModeActive || (keyboard?.mId?.mElementId == KeyboardId.ELEMENT_TEXT_EDIT) val customBgColor = mKeyCustomBgColors[key] diff --git a/app/src/main/java/helium314/keyboard/latin/KeyboardWrapperView.kt b/app/src/main/java/helium314/keyboard/latin/KeyboardWrapperView.kt index 8927d3689..2cea6860b 100644 --- a/app/src/main/java/helium314/keyboard/latin/KeyboardWrapperView.kt +++ b/app/src/main/java/helium314/keyboard/latin/KeyboardWrapperView.kt @@ -20,7 +20,7 @@ import helium314.keyboard.latin.common.Constants import helium314.keyboard.latin.settings.Settings import helium314.keyboard.latin.utils.ResourceUtils import helium314.keyboard.latin.utils.prefs -import kotlin.math.abs +import kotlin.math.roundToInt class KeyboardWrapperView @JvmOverloads constructor( context: Context, @@ -41,6 +41,55 @@ class KeyboardWrapperView @JvmOverloads constructor( if (isInLayout) post { requestLayout() } else requestLayout() } + /** Hides the one-handed controls while another view (touchpad) covers the keyboard, without leaving the mode. */ + var oneHandedControlsHidden = false + set(hidden) { + if (field == hidden) return + field = hidden + updateViewsVisibility() + } + + // Resize drag: rebuilding the keyboard takes ~100 ms, so the drag only previews the new width by scaling the + // keyboard view, and the keyboard is rebuilt once when the finger is lifted. + private var resizeStartX = 0f + private var resizeStartScale = 0f + private var resizePendingScale = 0f + private var resizePreviewView: View? = null + + // Side switch: keyboard position before the switch, to slide it to the new side on the next layout + private var slideFromLeft: Int? = null + + private fun oneHandedWidthFraction(extraScale: Float): Float { + val baseScale = resources.getFraction(R.fraction.config_one_handed_mode_width, 1, 1) + return 1f - (1f - baseScale) * extraScale + } + + private fun previewResize(scale: Float) { + val view = resizePreviewView ?: return + val scaleX = oneHandedWidthFraction(scale) / oneHandedWidthFraction(resizeStartScale) + val isLeftGravity = oneHandedGravity == Gravity.LEFT + view.pivotX = if (isLeftGravity) 0f else view.width.toFloat() + view.scaleX = scaleX + // the buttons stay centered in the space beside the keyboard + val shift = (scaleX - 1f) * view.width / 2f + val buttonShift = if (isLeftGravity) shift else -shift + stopOneHandedModeBtn.translationX = buttonShift + switchOneHandedModeBtn.translationX = buttonShift + resizeOneHandedModeBtn.translationX = buttonShift + } + + private fun endResize(apply: Boolean) { + resizePreviewView?.scaleX = 1f + resizePreviewView = null + stopOneHandedModeBtn.translationX = 0f + switchOneHandedModeBtn.translationX = 0f + resizeOneHandedModeBtn.translationX = 0f + if (!apply || resizePendingScale == resizeStartScale || !oneHandedModeEnabled) return + // the pref listener reloads settings synchronously, so the rebuilt keyboard uses the new scale + Settings.getInstance().writeOneHandedModeScale(resizePendingScale) + KeyboardSwitcher.getInstance().setOneHandedModeEnabled(true, true) + } + var oneHandedGravity = Gravity.NO_GRAVITY set(value) { field = value @@ -67,53 +116,52 @@ class KeyboardWrapperView @JvmOverloads constructor( stopOneHandedModeBtn.setOnClickListener(this) switchOneHandedModeBtn.setOnClickListener(this) - var x = 0f resizeOneHandedModeBtn.setOnTouchListener { _, motionEvent -> - when (motionEvent.action) { - MotionEvent.ACTION_DOWN -> x = motionEvent.rawX + when (motionEvent.actionMasked) { + MotionEvent.ACTION_DOWN -> { + resizeStartX = motionEvent.rawX + val landscape = Settings.getValues().mDisplayOrientation == Configuration.ORIENTATION_LANDSCAPE + val split = Settings.getValues().mIsSplitKeyboardEnabled + resizeStartScale = Settings.readOneHandedModeScale(context.prefs(), landscape, split) + resizePendingScale = resizeStartScale + resizePreviewView = KeyboardSwitcher.getInstance().visibleKeyboardView + } MotionEvent.ACTION_MOVE -> { - // performance is not great because settings are reloaded and keyboard is redrawn - // on every move, but it's good enough val sign = -switchOneHandedModeBtn.scaleX // factor 2 to make it more sensitive (maybe could be tuned a little) - val changePercent = 2 * sign * (x - motionEvent.rawX) / context.resources.displayMetrics.density - if (abs(changePercent) < 1) return@setOnTouchListener true - x = motionEvent.rawX - val landscape = Settings.getValues().mDisplayOrientation == Configuration.ORIENTATION_LANDSCAPE - val split = Settings.getValues().mIsSplitKeyboardEnabled - val oldScale = Settings.readOneHandedModeScale(context.prefs(), landscape, split) - val newScale = (oldScale + changePercent / 100f).coerceAtMost(2.5f).coerceAtLeast(0.5f) - if (newScale == oldScale) return@setOnTouchListener true - Settings.getInstance().writeOneHandedModeScale(newScale) - // Force reload settings synchronously to ensure the new scale is used immediately - val settings = Settings.getInstance() - val values = Settings.getValues() - settings.loadSettings(context, values.mLocale, values.mInputAttributes, values.mCurrentKeyboardScript) - KeyboardSwitcher.getInstance().setOneHandedModeEnabled(true, true) + val changePercent = 2 * sign * (resizeStartX - motionEvent.rawX) / context.resources.displayMetrics.density + val newScale = ((resizeStartScale * 100f + changePercent).roundToInt() / 100f).coerceIn(0.5f, 2.5f) + if (newScale != resizePendingScale) { + resizePendingScale = newScale + previewResize(newScale) + } } - else -> x = 0f + MotionEvent.ACTION_UP -> endResize(true) + MotionEvent.ACTION_CANCEL -> endResize(false) } true } val colors = Settings.getValues().mColors - colors.setColor(stopOneHandedModeBtn, ColorType.ONE_HANDED_MODE_BUTTON) - colors.setColor(switchOneHandedModeBtn, ColorType.ONE_HANDED_MODE_BUTTON) - colors.setColor(resizeOneHandedModeBtn, ColorType.ONE_HANDED_MODE_BUTTON) - colors.setBackground(stopOneHandedModeBtn, ColorType.ONE_HANDED_MODE_BUTTON) - colors.setBackground(switchOneHandedModeBtn, ColorType.ONE_HANDED_MODE_BUTTON) - colors.setBackground(resizeOneHandedModeBtn, ColorType.ONE_HANDED_MODE_BUTTON) + // styled like the toolbar keys (rounded key background, toolbar icon color) + for (button in listOf(stopOneHandedModeBtn, switchOneHandedModeBtn, resizeOneHandedModeBtn)) { + button.setBackgroundResource(R.drawable.toolbar_key_background) + colors.setColor(button.background, ColorType.TOOL_BAR_EXPAND_KEY_BACKGROUND) + colors.setColor(button, ColorType.TOOL_BAR_KEY) + } } @SuppressLint("RtlHardcoded") fun switchOneHandedModeSide() { + slideFromLeft = KeyboardSwitcher.getInstance().visibleKeyboardView?.left oneHandedGravity = if (oneHandedGravity == Gravity.LEFT) Gravity.RIGHT else Gravity.LEFT } private fun updateViewsVisibility() { - stopOneHandedModeBtn.visibility = if (oneHandedModeEnabled) VISIBLE else GONE - switchOneHandedModeBtn.visibility = if (oneHandedModeEnabled) VISIBLE else GONE - resizeOneHandedModeBtn.visibility = if (oneHandedModeEnabled) VISIBLE else GONE + val visibility = if (oneHandedModeEnabled && !oneHandedControlsHidden) VISIBLE else GONE + stopOneHandedModeBtn.visibility = visibility + switchOneHandedModeBtn.visibility = visibility + resizeOneHandedModeBtn.visibility = visibility } @SuppressLint("RtlHardcoded") @@ -210,19 +258,30 @@ class KeyboardWrapperView @JvmOverloads constructor( keyboardLeft + keyboardView.measuredWidth, keyboardView.measuredHeight ) + slideFromLeft?.let { fromLeft -> + slideFromLeft = null + val duration = Settings.getAnimationDuration(200) + if (duration > 0L && fromLeft != keyboardLeft) { + keyboardView.translationX = (fromLeft - keyboardLeft).toFloat() + keyboardView.animate().translationX(0f).setDuration(duration) + .setInterpolator(android.view.animation.DecelerateInterpolator()).start() + } + } val scale = Settings.getValues().mKeyboardHeightScale // scale one-handed mode button height if keyboard height scale is < 80% val heightScale = if (scale < 0.8f) scale + 0.2f else 1f val buttonsLeft = if (isLeftGravity) keyboardView.measuredWidth else 0 - val buttonXLeft = buttonsLeft + (spareWidth - stopOneHandedModeBtn.measuredWidth) / 2 - val buttonXRight = buttonsLeft + (spareWidth + stopOneHandedModeBtn.measuredWidth) / 2 - val buttonHeight = (heightScale * stopOneHandedModeBtn.measuredHeight).toInt() + // square buttons like the toolbar keys, smaller if the space beside the keyboard is narrow + val buttonSize = (heightScale * 40 * resources.displayMetrics.density).toInt().coerceAtMost(spareWidth) + val buttonXLeft = buttonsLeft + (spareWidth - buttonSize) / 2 fun View.setLayout(yPosition: Int) { - layout(buttonXLeft, yPosition - buttonHeight / 2, buttonXRight, yPosition + buttonHeight / 2) + layout(buttonXLeft, yPosition - buttonSize / 2, buttonXLeft + buttonSize, yPosition + buttonSize / 2) } - stopOneHandedModeBtn.setLayout((keyboardView.measuredHeight * 0.2f).toInt()) - switchOneHandedModeBtn.setLayout((keyboardView.measuredHeight * 0.5f).toInt()) - resizeOneHandedModeBtn.setLayout((keyboardView.measuredHeight * 0.8f).toInt()) + // Bottom padding holds the navigation bar inset, keep the buttons above it + val contentHeight = keyboardView.measuredHeight - keyboardView.paddingBottom + stopOneHandedModeBtn.setLayout((contentHeight * 0.2f).toInt()) + switchOneHandedModeBtn.setLayout((contentHeight * 0.5f).toInt()) + resizeOneHandedModeBtn.setLayout((contentHeight * 0.8f).toInt()) } } diff --git a/app/src/main/java/helium314/keyboard/latin/LatinIME.kt b/app/src/main/java/helium314/keyboard/latin/LatinIME.kt index c1e87271f..0f6cb1006 100644 --- a/app/src/main/java/helium314/keyboard/latin/LatinIME.kt +++ b/app/src/main/java/helium314/keyboard/latin/LatinIME.kt @@ -2261,7 +2261,10 @@ class LatinIME : InputMethodService(), CustomSoundManager.getInstance(this).onTrimMemory() helium314.keyboard.latin.utils.TextExpanderImageUtils.clearCache() helium314.keyboard.latin.handwriting.HandwritingLoader.release() - helium314.keyboard.latin.cjk.CjkPluginLoader.release() + // UI_HIDDEN comes on every app switch: re-initializing the CJK engine there reloads its dictionaries and + // dropped Japanese state, so only release it on real memory pressure. With a physical keyboard the input + // view can be hidden while the user is typing, so also keep it while an input session is active. + if (forceUnbindVoice && !currentInputStarted) helium314.keyboard.latin.cjk.CjkPluginLoader.release() helium314.keyboard.latin.ocr.OcrPluginLoader.release() helium314.keyboard.latin.translation.TranslationLoader.unloadPlugin() helium314.keyboard.latin.gif.GifImageLoader.clearMemory() diff --git a/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt b/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt index 357e40085..d2be2b549 100644 --- a/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt @@ -29,8 +29,9 @@ object CjkPluginLoader { // A native library (jni_pinyin) can only be loaded by one ClassLoader. The loader must outlive the engine // (release() drops it on every keyboard close), otherwise Pinyin stays unavailable after a re-open. + // Keyed by the native lib directory: the conflict is per .so path, and a new plugin APK gets a new directory. private var cachedClassLoader: ClassLoader? = null - private var cachedLoaderApkModified: Long = 0L + private var cachedLoaderLibDir: String? = null fun getTargetAbi(): String { for (abi in Build.SUPPORTED_ABIS) { @@ -149,6 +150,7 @@ object CjkPluginLoader { context.prefs().edit().putBoolean(PREF_ENABLE_MOCK, enabled).apply() } + @Synchronized fun getEngine(context: Context): ICjkEngine? { val internalApk = File(context.filesDir, PLUGIN_FILENAME) val apkModified = if (internalApk.exists()) internalApk.lastModified() else 0L @@ -207,8 +209,8 @@ object CjkPluginLoader { extractPluginAssetsAndLibs(apkFile, nativeLibDir, sharedDir) - val apkModified = apkFile.lastModified() - val classLoader = cachedClassLoader?.takeIf { cachedLoaderApkModified == apkModified } + val libDirPath = nativeLibDir.absolutePath + val classLoader = cachedClassLoader?.takeIf { cachedLoaderLibDir == libDirPath } ?: PluginClassLoader( apkFile.absolutePath, context.codeCacheDir.absolutePath, @@ -216,7 +218,7 @@ object CjkPluginLoader { context.classLoader ).also { cachedClassLoader = it - cachedLoaderApkModified = apkModified + cachedLoaderLibDir = libDirPath } val clazz = classLoader.loadClass(PLUGIN_CLASS_NAME) @@ -304,6 +306,7 @@ object CjkPluginLoader { fun importPlugin(context: Context, sourceUri: Uri): Boolean = loadPluginFromUri(context, sourceUri) + @Synchronized fun loadPluginFromUri(context: Context, sourceUri: Uri): Boolean { return try { try { @@ -327,6 +330,7 @@ object CjkPluginLoader { val success = engine != null && isUsable(engine) if (success) { activeEngine = engine + lastApkModified = targetFile.lastModified() context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, true).apply() Log.i(TAG, "CJK plugin imported and verified successfully") } else { @@ -341,6 +345,7 @@ object CjkPluginLoader { } } + @Synchronized fun importPluginFromTempFile(context: Context, tempFile: File): Boolean { return try { try { @@ -361,6 +366,7 @@ object CjkPluginLoader { val success = engine != null && isUsable(engine) if (success) { activeEngine = engine + lastApkModified = targetFile.lastModified() context.prefs().edit().putBoolean(PREF_HAS_PLUGIN, true).apply() Log.i(TAG, "CJK plugin imported from temp file and verified successfully") } else { @@ -389,11 +395,13 @@ object CjkPluginLoader { } } + @Synchronized fun removePlugin(context: Context) { try { activeEngine?.cleanup() activeEngine = null cachedClassLoader = null + cachedLoaderLibDir = null val apkFile = File(context.filesDir, PLUGIN_FILENAME) if (apkFile.exists()) apkFile.delete() val nativeLibBase = File(context.filesDir, "plugin_libs") @@ -409,6 +417,7 @@ object CjkPluginLoader { } } + @Synchronized fun release() { try { activeEngine?.cleanup() diff --git a/app/src/main/java/helium314/keyboard/latin/utils/ResourceUtils.kt b/app/src/main/java/helium314/keyboard/latin/utils/ResourceUtils.kt index 4d268cdad..6895be50e 100644 --- a/app/src/main/java/helium314/keyboard/latin/utils/ResourceUtils.kt +++ b/app/src/main/java/helium314/keyboard/latin/utils/ResourceUtils.kt @@ -77,19 +77,11 @@ object ResourceUtils { fun getSuggestionsStripHeight(res: Resources): Int { val defaultHeight = res.getDimensionPixelSize(R.dimen.config_suggestions_strip_height) if (sFloatingKeyboardScaleOverride > 0.0f) { - // Derive strip height from the actual keyboard key row height rather than - // arbitrary dp bounds, using the configured ratio of strip to key row. - val defaultKbHeight = getDefaultKeyboardHeight(res, false) - val defaultRowHeight = defaultKbHeight / helium314.keyboard.keyboard.internal.KeyboardParams.DEFAULT_KEYBOARD_ROWS - val defaultRatio = if (defaultRowHeight > 0f) defaultHeight.toFloat() / defaultRowHeight else 0.78f - val keyboard = helium314.keyboard.keyboard.KeyboardSwitcher.getInstance().keyboard - if (keyboard != null && keyboard.mMostCommonKeyHeight > 0) { - return (keyboard.mMostCommonKeyHeight * defaultRatio).toInt() - .coerceAtLeast((24 * res.displayMetrics.density).toInt()) // absolute floor: 24dp - } - // Fallback: scale the default height directly + // Scale the docked strip height with the floating keyboard. Not derived from the key height: layouts with + // more rows (number row, PC layouts) have shorter keys, which made the strip and toolbar keys too small. + // Capped at the docked height: toolbar icons don't grow, so a taller strip only adds empty space. val scaledHeight = (defaultHeight * sFloatingKeyboardScaleOverride).toInt() - return scaledHeight.coerceAtLeast((24 * res.displayMetrics.density).toInt()) + return scaledHeight.coerceIn((24 * res.displayMetrics.density).toInt(), defaultHeight) } return defaultHeight }