Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions app/src/main/java/helium314/keyboard/keyboard/KeyboardSwitcher.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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<View>(R.id.btn_stop_one_handed_mode)?.visibility = View.GONE
wrapper.findViewById<View>(R.id.btn_switch_one_handed_mode)?.visibility = View.GONE
wrapper.findViewById<View>(R.id.btn_resize_one_handed_mode)?.visibility = View.GONE
}
mKeyboardViewWrapper?.oneHandedControlsHidden = true
if (Settings.getValues().mTouchpadFullscreen) {
mStripContainer?.visibility = View.GONE
requestInputViewLayoutAndInsets()
Expand Down Expand Up @@ -1107,11 +1111,7 @@ class KeyboardSwitcher private constructor() : KeyboardState.SwitchActions {
mSuggestionStripView?.updateSplitToolbarState()
requestInputViewLayoutAndInsets()
mKeyboardViewWrapper?.let { wrapper ->
if (wrapper.oneHandedModeEnabled) {
wrapper.findViewById<View>(R.id.btn_stop_one_handed_mode)?.visibility = View.VISIBLE
wrapper.findViewById<View>(R.id.btn_switch_one_handed_mode)?.visibility = View.VISIBLE
wrapper.findViewById<View>(R.id.btn_resize_one_handed_mode)?.visibility = View.VISIBLE
}
wrapper.oneHandedControlsHidden = false
wrapper.requestLayout()
}
}
Expand Down
13 changes: 13 additions & 0 deletions app/src/main/java/helium314/keyboard/keyboard/KeyboardView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
133 changes: 96 additions & 37 deletions app/src/main/java/helium314/keyboard/latin/KeyboardWrapperView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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")
Expand Down Expand Up @@ -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())
}
}
5 changes: 4 additions & 1 deletion app/src/main/java/helium314/keyboard/latin/LatinIME.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
17 changes: 13 additions & 4 deletions app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -207,16 +209,16 @@ 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,
nativeLibDir.absolutePath,
context.classLoader
).also {
cachedClassLoader = it
cachedLoaderApkModified = apkModified
cachedLoaderLibDir = libDirPath
}

val clazz = classLoader.loadClass(PLUGIN_CLASS_NAME)
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -341,6 +345,7 @@ object CjkPluginLoader {
}
}

@Synchronized
fun importPluginFromTempFile(context: Context, tempFile: File): Boolean {
return try {
try {
Expand All @@ -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 {
Expand Down Expand Up @@ -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")
Expand All @@ -409,6 +417,7 @@ object CjkPluginLoader {
}
}

@Synchronized
fun release() {
try {
activeEngine?.cleanup()
Expand Down
Loading
Loading