Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

feat(terminal): wire cursor blinker; paint coalesce; layout-settle; parser fixes

ExTv59226d17bf19
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt
index 2c39cde..4b8444b 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt
@@ -76,7 +76,6 @@ import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
-import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -87,6 +86,7 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -121,11 +121,11 @@ fun TerminalScreen(
viewModel: TerminalViewModel = hiltViewModel(),
) {
val context = LocalContext.current
- val vmState by viewModel.vmState.collectAsState()
- val fontSize by viewModel.terminalFontSize.collectAsState()
- val showQuickSettings by viewModel.showQuickSettings.collectAsState()
- val showExtraKeys by viewModel.showExtraKeysFlow.collectAsState()
- val hapticsEnabled by viewModel.hapticsEnabledFlow.collectAsState()
+ val vmState by viewModel.vmState.collectAsStateWithLifecycle()
+ val fontSize by viewModel.terminalFontSize.collectAsStateWithLifecycle()
+ val showQuickSettings by viewModel.showQuickSettings.collectAsStateWithLifecycle()
+ val showExtraKeys by viewModel.showExtraKeysFlow.collectAsStateWithLifecycle()
+ val hapticsEnabled by viewModel.hapticsEnabledFlow.collectAsStateWithLifecycle()
DisposableEffect(Unit) {
val activity = context as? Activity
@@ -154,14 +154,8 @@ fun TerminalScreen(
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
- val colorTheme by viewModel.terminalColorTheme.collectAsState()
- val terminalFont by viewModel.terminalFont.collectAsState()
-
- // Resolve the typeface and background palette from settings. Both run on
- // recomposition because they're cheap (asset reads, font cache lookup) and
- // the result drives the View setters in LaunchedEffect below.
- val typeface = remember(terminalFont) { viewModel.loadFont(terminalFont) }
- val themeBg = remember(colorTheme) { viewModel.loadColorTheme(colorTheme) }
+ val colorTheme by viewModel.terminalColorTheme.collectAsStateWithLifecycle()
+ val terminalFont by viewModel.terminalFont.collectAsStateWithLifecycle()
if (showQuickSettings) {
QuickSettingsDialog(
@@ -260,98 +254,17 @@ fun TerminalScreen(
}
is VmState.Running -> {
- Box(modifier = Modifier.weight(1f).fillMaxSize()) {
- // The View is created per-Composition-context (i.e. per Activity).
- // Caching it across config changes used to leak the destroyed Activity.
- val view = remember(context) {
- TerminalView(context, null).apply {
- setTextSize(fontSize)
- keepScreenOn = true
- isFocusable = true
- isFocusableInTouchMode = true
- }
- }
-
- LaunchedEffect(view, themeBg) {
- view.setBackgroundColor(themeBg ?: android.graphics.Color.BLACK)
- }
- LaunchedEffect(view, typeface) {
- view.setTypeface(typeface)
- view.post {
- viewModel.forceUpdateSizeFromView(view, typeface)
- view.updateSize()
- }
- }
-
- DisposableEffect(view, vmState) {
- viewModel.resetOnRestart()
- viewModel.bindView(view)
- viewModel.createSession()
- view.setTerminalViewClient(viewModel.viewClient)
- val sess = viewModel.session
- if (sess != null) {
- view.mTermSession = sess
- view.mEmulator = sess.emulator
- }
- view.requestFocus()
- view.onScreenUpdated()
-
- view.post {
- viewModel.forceUpdateSizeFromView(view, typeface)
- view.updateSize()
- view.onScreenUpdated()
- }
- onDispose { viewModel.bindView(null) }
- }
-
- // Layout-change debounce: keyboard slide animation fires ~25 layout
- // events. Coroutine debounce collapses them to one SIGWINCH.
- val scope = rememberCoroutineScope()
- DisposableEffect(view) {
- var pending: kotlinx.coroutines.Job? = null
- val listener = android.view.View.OnLayoutChangeListener {
- v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
- val w = right - left
- val h = bottom - top
- if (w <= 0 || h <= 0) return@OnLayoutChangeListener
- if (w == oldRight - oldLeft && h == oldBottom - oldTop) return@OnLayoutChangeListener
- pending?.cancel()
- pending = scope.launch {
- kotlinx.coroutines.delay(150)
- val tv = v as TerminalView
- // Just tv.updateSize() — it has the correct row math
- // (subtracts mFontLineSpacingAndAscent). Calling
- // forceUpdateSizeFromView too caused a row-count race:
- // the two computations disagree by 1 in some sizes,
- // triggering two back-to-back resizes per keyboard
- // slide and a visible cursor flicker.
- tv.updateSize()
- }
- }
- view.addOnLayoutChangeListener(listener)
- onDispose {
- pending?.cancel()
- view.removeOnLayoutChangeListener(listener)
- }
- }
-
- // Last fontSize actually pushed to the View. Termux's TerminalView has no
- // getTextSize(), so we track it ourselves to skip redundant setTextSize +
- // updateSize calls on each recomposition (which were the visible flicker
- // source whenever extraCtrl/extraAlt flipped).
- var lastAppliedFontSize by remember { mutableStateOf(-1) }
- AndroidView(
- factory = { view },
- update = { v ->
- if (lastAppliedFontSize != fontSize) {
- lastAppliedFontSize = fontSize
- v.setTextSize(fontSize)
- v.post { v.updateSize() }
- }
- },
- modifier = Modifier.fillMaxSize(),
- )
- }
+ // Hoisted into its own composable so toggling chrome state in the
+ // parent (showQuickSettings, showExtraKeys, hapticsEnabled, modifier
+ // keys, etc.) doesn't invalidate the AndroidView slot. TerminalSurface
+ // takes only the ViewModel (stable @HiltViewModel) so Compose's
+ // restart-scope skipping kicks in: chrome toggles → parent recomposes,
+ // surface skips. The terminal pixels never re-route through Compose
+ // unless something the surface actually reads has changed.
+ TerminalSurface(
+ viewModel = viewModel,
+ modifier = Modifier.weight(1f).fillMaxSize(),
+ )
}
}
@@ -370,6 +283,172 @@ fun TerminalScreen(
}
}
+/**
+ * Owns the TerminalView. Isolated as its own composable so chrome state
+ * (quick-settings sheet, extra-keys toggle, haptics, etc.) lives in the
+ * parent's restart scope and never invalidates this slot. The only reads
+ * here drive things the View genuinely needs: typeface, palette, font size.
+ *
+ * `update = { }` — the View manages its own state. All View setters are
+ * driven by narrow-keyed LaunchedEffects so Compose only touches the View
+ * when the actual driving input changes, never on incidental recomposition.
+ */
+@Composable
+private fun TerminalSurface(
+ viewModel: TerminalViewModel,
+ modifier: Modifier = Modifier,
+) {
+ val context = LocalContext.current
+ val fontSize by viewModel.terminalFontSize.collectAsStateWithLifecycle()
+ val colorTheme by viewModel.terminalColorTheme.collectAsStateWithLifecycle()
+ val terminalFont by viewModel.terminalFont.collectAsStateWithLifecycle()
+
+ // Resolve typeface + palette here (cheap: asset reads, font cache lookup).
+ // Each is keyed on its specific upstream string so a theme change does not
+ // re-resolve the font and vice versa.
+ val typeface = remember(terminalFont) { viewModel.loadFont(terminalFont) }
+ val themeBg = remember(colorTheme) { viewModel.loadColorTheme(colorTheme) }
+
+ Box(modifier = modifier) {
+ // The View is created per-Composition-context (i.e. per Activity).
+ // Caching it across config changes used to leak the destroyed Activity.
+ val view = remember(context) {
+ TerminalView(context, null).apply {
+ setTextSize(fontSize)
+ keepScreenOn = true
+ isFocusable = true
+ isFocusableInTouchMode = true
+ }
+ }
+
+ // Theme background — keyed only on themeBg so font/size changes don't
+ // re-fire it. We also force a repaint here because loadColorTheme()
+ // pushes the new palette into the live session's mCurrentColors, but
+ // doesn't itself trigger an invalidate — without this the screen
+ // keeps painting with the old colors until the next PTY byte.
+ LaunchedEffect(view, themeBg) {
+ view.setBackgroundColor(themeBg ?: android.graphics.Color.BLACK)
+ view.onScreenUpdated()
+ }
+
+ // Typeface — keyed only on the resolved Typeface. Re-pushes size to the
+ // session because cell metrics (charWidth/lineHeight) change with the
+ // font, not just with text size. Use only view.updateSize() (its row
+ // math subtracts mFontLineSpacingAndAscent); calling
+ // forceUpdateSizeFromView in addition disagrees by ±1 row and causes
+ // cursor flicker.
+ LaunchedEffect(view, typeface) {
+ view.setTypeface(typeface)
+ view.post { view.updateSize() }
+ }
+
+ // Font size — keyed only on the int. Replaces the old guard-in-update
+ // pattern: now `update = { }` is a true no-op and Compose touches the
+ // View only when fontSize actually changes.
+ LaunchedEffect(view, fontSize) {
+ view.setTextSize(fontSize)
+ view.post { view.updateSize() }
+ }
+
+ // Session/client binding. Keyed on `view` only — we are inside the
+ // VmState.Running branch so vmState identity is stable while we live.
+ // (Previous `DisposableEffect(view, vmState)` was wider than necessary;
+ // narrowing means transient VM state churn can't re-bind the session.)
+ DisposableEffect(view) {
+ viewModel.resetOnRestart()
+ viewModel.bindView(view)
+ viewModel.createSession()
+ view.setTerminalViewClient(viewModel.viewClient)
+ val sess = viewModel.session
+ if (sess != null) {
+ view.mTermSession = sess
+ view.mEmulator = sess.emulator
+ }
+ view.requestFocus()
+ view.onScreenUpdated()
+
+ // view.updateSize() only — its row math subtracts
+ // mFontLineSpacingAndAscent. forceUpdateSizeFromView disagrees by
+ // ±1 row in some sizes and causes a visible cursor flicker on
+ // first paint.
+ view.post {
+ view.updateSize()
+ view.onScreenUpdated()
+ }
+
+ // Cursor blinker: the host app must opt in — TerminalView ships the
+ // mechanism but never starts itself. 500ms is the conventional rate.
+ // startOnlyIfCursorEnabled=false because the renderer already gates
+ // paint via shouldCursorBeVisible() (which honors ?25l), so it's
+ // safe to leave the FrameCallback driving and let the emulator say
+ // when the cursor is hidden.
+ view.setTerminalCursorBlinkerRate(500)
+ view.setTerminalCursorBlinkerState(true, false)
+
+ onDispose { viewModel.bindView(null) }
+ }
+
+ // Pause the blinker when the activity is backgrounded. Without this
+ // the Choreographer FrameCallback keeps firing every VSYNC in
+ // paused-without-detach states (split-screen, dialog occlusion, PiP).
+ // onDetachedFromWindow already handles the full-detach case.
+ val lifecycleOwner = LocalLifecycleOwner.current
+ DisposableEffect(view, lifecycleOwner) {
+ val observer = LifecycleEventObserver { _, event ->
+ when (event) {
+ Lifecycle.Event.ON_RESUME -> view.setTerminalCursorBlinkerState(true, false)
+ Lifecycle.Event.ON_PAUSE -> view.setTerminalCursorBlinkerState(false, false)
+ else -> {}
+ }
+ }
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
+ }
+
+ // Layout-change debounce: keyboard slide animation fires ~25 layout
+ // events. Coroutine debounce collapses them to one SIGWINCH. We also
+ // tell the View to suppress its blink toggle during the settle window
+ // so the cursor doesn't visibly flicker on/off mid-animation.
+ val scope = rememberCoroutineScope()
+ DisposableEffect(view) {
+ var pending: kotlinx.coroutines.Job? = null
+ val listener = android.view.View.OnLayoutChangeListener {
+ v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
+ val w = right - left
+ val h = bottom - top
+ if (w <= 0 || h <= 0) return@OnLayoutChangeListener
+ if (w == oldRight - oldLeft && h == oldBottom - oldTop) return@OnLayoutChangeListener
+ pending?.cancel()
+ val tv = v as TerminalView
+ tv.setLayoutSettling(true)
+ pending = scope.launch {
+ kotlinx.coroutines.delay(150)
+ // Just tv.updateSize() — it has the correct row math
+ // (subtracts mFontLineSpacingAndAscent). Calling
+ // forceUpdateSizeFromView too caused a row-count race:
+ // the two computations disagree by 1 in some sizes,
+ // triggering two back-to-back resizes per keyboard
+ // slide and a visible cursor flicker.
+ tv.updateSize()
+ tv.setLayoutSettling(false)
+ }
+ }
+ view.addOnLayoutChangeListener(listener)
+ onDispose {
+ pending?.cancel()
+ view.setLayoutSettling(false)
+ view.removeOnLayoutChangeListener(listener)
+ }
+ }
+
+ AndroidView(
+ factory = { view },
+ update = { },
+ modifier = Modifier.fillMaxSize(),
+ )
+ }
+}
+
@Composable
private fun ExtraKeysRow(
onKey: (String) -> Unit,
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt
index 44ba5e1..e442ba1 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt
@@ -149,9 +149,22 @@ class TerminalViewModel @Inject constructor(
* Returns null background for the built-in default.
*/
fun loadColorTheme(theme: String): Int? {
- if (theme == "default") return null
- val props = readThemeProperties(theme) ?: return null
+ // "default" path passes empty props through updateWith → resets
+ // COLOR_SCHEME to the built-in defaults and yields a null bg
+ // (renderer falls back to BLACK). Previously the "default" branch
+ // returned early without resetting, so switching from a custom
+ // theme to "default" left the previous palette in place.
+ val props = if (theme == "default") {
+ java.util.Properties()
+ } else {
+ readThemeProperties(theme) ?: return null
+ }
TerminalColors.COLOR_SCHEME.updateWith(props)
+ // updateWith refreshes the static defaults, but the live session's
+ // mCurrentColors is a per-session cache populated at session start
+ // and on `\ec` (RIS). Without this push, theme changes only took
+ // effect after the user typed `reset` in the shell.
+ session?.emulator?.mColors?.reset()
return (props["background"] as? String)?.let { parseColor(it) }
}
diff --git a/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java b/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java
index 5ff1899..615c9fd 100644
--- a/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java
+++ b/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java
@@ -2178,7 +2178,12 @@ public final class TerminalEmulator {
mEffect = state.mSavedEffect;
mForeColor = state.mSavedForeColor;
mBackColor = state.mSavedBackColor;
- int mask = (DECSET_BIT_AUTOWRAP | DECSET_BIT_ORIGIN_MODE);
+ // Restore the cursor-visible bit too (xterm does). A TUI that hides the
+ // cursor inside alt-screen via ?25l and exits via ?1049l without
+ // re-issuing ?25h would otherwise leave the cursor permanently hidden
+ // for the rest of the session — shouldCursorBeVisible() would return
+ // false forever.
+ int mask = (DECSET_BIT_AUTOWRAP | DECSET_BIT_ORIGIN_MODE | DECSET_BIT_CURSOR_ENABLED);
mCurrentDecSetFlags = (mCurrentDecSetFlags & ~mask) | (state.mSavedDecFlags & mask);
mUseLineDrawingG0 = state.mUseLineDrawingG0;
mUseLineDrawingG1 = state.mUseLineDrawingG1;
@@ -3039,6 +3044,7 @@ public final class TerminalEmulator {
case 1337: // iTerm image
// - https://iterm2.com/documentation-images.html
// - https://iterm2.com/documentation-escape-codes.html
+ if (argsLength < 5) break;
String controlCommandPrefix = mTerminalControlArgs.substring(5, Math.min(19, argsLength));
if (controlCommandPrefix.startsWith("File=") ||
@@ -3138,7 +3144,11 @@ public final class TerminalEmulator {
}
break;
} else if (controlCommandPrefix.startsWith("ReportCellSize")) {
- mSession.write(String.format(Locale.ENGLISH, "\0331337;ReportCellSize=%d;%d\007", mCellHeightPixels, mCellWidthPixels));
+ // Proper OSC framing: ESC ] 1337 ; ... BEL. The previous
+ // string was missing the ']' so the response was malformed.
+ mSession.write(String.format(Locale.ENGLISH, "\033]1337;ReportCellSize=%d;%d\007", mCellHeightPixels, mCellWidthPixels));
+ mITermImage = null;
+ break;
}
// Free image from memory for any non `MultipartFile=` related commands.
@@ -3641,6 +3651,10 @@ public final class TerminalEmulator {
// Initial wrap-around is not accurate but makes terminal more useful, especially on a small screen:
setDecsetinternalBit(DECSET_BIT_AUTOWRAP, true);
setDecsetinternalBit(DECSET_BIT_CURSOR_ENABLED, true);
+ // Re-arm the blink state. RIS / DECSTR clear the DEC flags but leave
+ // mCursorBlinkState whatever it was last toggled to — if the host
+ // blinker is paused that can leave the cursor stuck invisible.
+ setCursorBlinkState(true);
mSavedDecSetFlags = mSavedStateMain.mSavedDecFlags = mSavedStateAlt.mSavedDecFlags = mCurrentDecSetFlags;
// XXX: Should we set terminal driver back to IUTF8 with termios?
diff --git a/terminal-emulator/src/main/jni/termux.c b/terminal-emulator/src/main/jni/termux.c
index 8cd5e78..8752b05 100644
--- a/terminal-emulator/src/main/jni/termux.c
+++ b/terminal-emulator/src/main/jni/termux.c
@@ -162,7 +162,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
char const* cmd_utf8 = (*env)->GetStringUTFChars(env, cmd, NULL);
int ptm = create_subprocess(env, cmd_utf8, cmd_cwd, argv, envp, &procId, rows, columns, cell_width, cell_height);
(*env)->ReleaseStringUTFChars(env, cmd, cmd_utf8);
- (*env)->ReleaseStringUTFChars(env, cmd, cmd_cwd);
+ (*env)->ReleaseStringUTFChars(env, cwd, cmd_cwd);
if (argv) {
for (char** tmp = argv; *tmp; ++tmp) free(*tmp);
diff --git a/terminal-view/src/main/java/com/termux/view/TerminalView.java b/terminal-view/src/main/java/com/termux/view/TerminalView.java
index 49e03ca..5c4a418 100644
--- a/terminal-view/src/main/java/com/termux/view/TerminalView.java
+++ b/terminal-view/src/main/java/com/termux/view/TerminalView.java
@@ -9,14 +9,13 @@ import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.os.Build;
-import android.os.Handler;
-import android.os.Looper;
import android.os.SystemClock;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ActionMode;
+import android.view.Choreographer;
import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
@@ -59,13 +58,99 @@ public final class TerminalView extends View {
private TextSelectionCursorController mTextSelectionCursorController;
- private Handler mTerminalCursorBlinkerHandler;
- private TerminalCursorBlinkerRunnable mTerminalCursorBlinkerRunnable;
private int mTerminalCursorBlinkerRate;
private boolean mCursorInvisibleIgnoreOnce;
public static final int TERMINAL_CURSOR_BLINK_RATE_MIN = 100;
public static final int TERMINAL_CURSOR_BLINK_RATE_MAX = 2000;
+ /**
+ * VSYNC-aligned invalidate + cursor-blink driver.
+ *
+ * A single {@link Choreographer.FrameCallback} coalesces:
+ * - screen invalidates triggered by {@link #onScreenUpdated()} (Goal A: collapses
+ * a burst of N PTY-input batches into one paint per VSYNC), and
+ * - cursor-blink toggles (Goal B: blink edges land on a frame boundary instead of
+ * drifting off-VSYNC under a Handler.postDelayed schedule).
+ *
+ * The callback is re-posted while either an invalidate is pending or blink is enabled.
+ * It is unposted on detach / session end to avoid leaking the callback.
+ */
+ /** Wait this long after the most recent PTY-input chunk before painting,
+ * so multi-chunk bursts (less row-by-row redraws, bash readline reprints,
+ * long lines split by the kernel) collapse into one paint instead of a
+ * visible cursor walk. Tuned to ≈ one VSYNC. */
+ private static final long INPUT_COALESCE_QUIET_MS = 16;
+
+ /** Hard cap on how long a single burst can defer paints. Without it, a
+ * continuous output stream (yes, while-true, sixel video) would never
+ * paint. 64 ms ≈ 4 VSYNCs at 60 Hz — fast enough that the user perceives
+ * the screen as live. */
+ private static final long INPUT_COALESCE_MAX_MS = 64;
+
+ private final Choreographer mChoreographer = Choreographer.getInstance();
+ private final Choreographer.FrameCallback mFrameCallback = new Choreographer.FrameCallback() {
+ @Override
+ public void doFrame(long frameTimeNanos) {
+ mFramePosted = false;
+ long nowMs = frameTimeNanos / 1_000_000L;
+
+ // Goal B: blink-tick-if-due. Toggle only when the user-configured rate has
+ // elapsed since the last toggle; the FrameCallback fires every VSYNC but
+ // the visual blink rate is preserved by the elapsed-time gate.
+ // Suppressed while a layout change is settling (keyboard slide, rotation,
+ // sheet open) so the cursor doesn't blink off mid-animation while the
+ // View bounds are still changing.
+ if (!mLayoutSettling
+ && mBlinkEnabled && mEmulator != null && mTerminalCursorBlinkerRate > 0) {
+ if (nowMs - mLastBlinkMs >= mTerminalCursorBlinkerRate) {
+ mBlinkCursorVisible = !mBlinkCursorVisible;
+ mEmulator.setCursorBlinkState(mBlinkCursorVisible);
+ mLastBlinkMs = nowMs;
+ mInvalidatePending = true;
+ }
+ }
+
+ // Goal A: invalidate-if-pending, with input-coalesce. We paint only
+ // when (a) input has been quiet for INPUT_COALESCE_QUIET_MS or (b)
+ // the burst has been deferring for at least INPUT_COALESCE_MAX_MS.
+ // Otherwise we keep mInvalidatePending=true and re-post for the
+ // next VSYNC. This collapses a 20-chunk less-page-down redraw into
+ // a single paint instead of a cursor walking down the column.
+ if (mInvalidatePending) {
+ boolean quiet = nowMs - mLastInputMs >= INPUT_COALESCE_QUIET_MS;
+ boolean capped = mFirstDeferredInputMs != 0
+ && nowMs - mFirstDeferredInputMs >= INPUT_COALESCE_MAX_MS;
+ if (quiet || capped) {
+ mInvalidatePending = false;
+ mFirstDeferredInputMs = 0;
+ invalidate();
+ }
+ // else: defer; the re-post below keeps the callback alive.
+ }
+
+ // Re-post if either blink is running or we still owe a deferred
+ // paint. (Blink alone wakes us once per VSYNC; deferred paints
+ // need the same cadence so they can re-check the quiet condition.)
+ if (mBlinkEnabled || mInvalidatePending) {
+ mFramePosted = true;
+ mChoreographer.postFrameCallback(this);
+ }
+ }
+ };
+ private boolean mInvalidatePending;
+ private boolean mFramePosted;
+ private boolean mBlinkEnabled;
+ private boolean mBlinkCursorVisible;
+ private long mLastBlinkMs;
+ /** Wall-clock of the most recent input chunk (for INPUT_COALESCE_QUIET_MS). */
+ private long mLastInputMs;
+ /** Wall-clock of the first input chunk in the current deferred burst. Reset
+ * to 0 every time a paint actually lands. (For INPUT_COALESCE_MAX_MS cap.) */
+ private long mFirstDeferredInputMs;
+ /** While true, the FrameCallback skips blink toggles. Set during keyboard
+ * slides and other layout settles (host calls setLayoutSettling). */
+ private boolean mLayoutSettling;
+
/** The top row of text to display. Ranges from -activeTranscriptRows to 0. */
int mTopRow;
int[] mDefaultSelectors = new int[]{-1,-1,-1,-1};
@@ -494,10 +579,42 @@ public final class TerminalView extends View {
mEmulator.clearScrollCounter();
- invalidate();
+ scheduleFrameInvalidate();
if (mAccessibilityEnabled) setContentDescription(getText());
}
+ /**
+ * Mark a frame invalidate as pending and post the shared {@link Choreographer.FrameCallback}
+ * if it isn't already posted. Always called on the main thread (PTY-input drains arrive
+ * via {@code TerminalSession.MainThreadHandler} → {@code TerminalSessionClient.onTextChanged}
+ * → {@link #onScreenUpdated()}), so no synchronization is required.
+ */
+ private void scheduleFrameInvalidate() {
+ long now = SystemClock.uptimeMillis();
+ mInvalidatePending = true;
+ // Track input timing for the burst-coalesce in doFrame. mFirstDeferredInputMs
+ // is set on the first chunk of a burst and cleared whenever a paint lands.
+ if (mFirstDeferredInputMs == 0) mFirstDeferredInputMs = now;
+ mLastInputMs = now;
+ // Suppress cursor blink during active screen updates: when typing (or any
+ // PTY-driven screen change) the cursor must stay solidly visible. Otherwise
+ // the block cursor inverts characters under it and the blink toggle makes
+ // each character appear to flicker between two colors as the cursor moves.
+ // Resetting mLastBlinkMs here delays the next toggle by a full blink
+ // interval after activity stops, so the cursor only blinks when idle.
+ if (mBlinkEnabled && mEmulator != null) {
+ if (!mBlinkCursorVisible) {
+ mBlinkCursorVisible = true;
+ mEmulator.setCursorBlinkState(true);
+ }
+ mLastBlinkMs = now;
+ }
+ if (!mFramePosted) {
+ mFramePosted = true;
+ mChoreographer.postFrameCallback(mFrameCallback);
+ }
+ }
+
/** This must be called by the hosting activity in {@link Activity#onContextMenuClosed(Menu)}
* when context menu for the {@link TerminalView} is started by
* {@link TextSelectionCursorController#ACTION_MORE} is closed. */
@@ -995,9 +1112,8 @@ public final class TerminalView extends View {
mEmulator = mTermSession.getEmulator();
mClient.onEmulatorSet();
- // Update mTerminalCursorBlinkerRunnable inner class mEmulator on session change
- if (mTerminalCursorBlinkerRunnable != null)
- mTerminalCursorBlinkerRunnable.setEmulator(mEmulator);
+ // The shared FrameCallback reads mEmulator directly, so no per-session
+ // re-binding is needed (was previously mTerminalCursorBlinkerRunnable.setEmulator).
mTopRow = 0;
scrollTo(0, 0);
@@ -1294,14 +1410,55 @@ public final class TerminalView extends View {
return;
}
- // Start cursor blinker runnable
+ // Start the VSYNC-aligned cursor blinker. The shared FrameCallback gates
+ // the toggle behind mTerminalCursorBlinkerRate, so the user-configurable
+ // blink rate is preserved while the actual paint lands on a frame boundary.
if (TERMINAL_VIEW_KEY_LOGGING_ENABLED)
mClient.logVerbose(LOG_TAG, "Starting cursor blinker with the blink rate " + mTerminalCursorBlinkerRate);
- if (mTerminalCursorBlinkerHandler == null)
- mTerminalCursorBlinkerHandler = new Handler(Looper.getMainLooper());
- mTerminalCursorBlinkerRunnable = new TerminalCursorBlinkerRunnable(mEmulator, mTerminalCursorBlinkerRate);
mEmulator.setCursorBlinkingEnabled(true);
- mTerminalCursorBlinkerRunnable.run();
+ // Show the cursor immediately on enable, then let the FrameCallback gate
+ // subsequent toggles by mTerminalCursorBlinkerRate.
+ mBlinkCursorVisible = true;
+ mEmulator.setCursorBlinkState(mBlinkCursorVisible);
+ mLastBlinkMs = SystemClock.uptimeMillis();
+ mBlinkEnabled = true;
+ mInvalidatePending = true;
+ if (!mFramePosted) {
+ mFramePosted = true;
+ mChoreographer.postFrameCallback(mFrameCallback);
+ }
+ }
+ }
+
+ /**
+ * Mark the View as in the middle of a layout-settle window (e.g., the soft
+ * keyboard is sliding in/out). While true, the FrameCallback skips blink
+ * toggles so the cursor doesn't blink off mid-animation. Entering settle
+ * forces the cursor visible immediately so a paint that lands during the
+ * settle shows the cursor solidly. Leaving settle resets the blink timer
+ * so the post-settle frame doesn't immediately toggle.
+ */
+ public synchronized void setLayoutSettling(boolean settling) {
+ if (mLayoutSettling == settling) return;
+ mLayoutSettling = settling;
+ if (settling) {
+ if (mBlinkEnabled && mEmulator != null && !mBlinkCursorVisible) {
+ mBlinkCursorVisible = true;
+ mEmulator.setCursorBlinkState(true);
+ mInvalidatePending = true;
+ if (!mFramePosted) {
+ mFramePosted = true;
+ mChoreographer.postFrameCallback(mFrameCallback);
+ }
+ }
+ } else {
+ // Resetting on settle-end starts the next blink interval from zero,
+ // matching scheduleFrameInvalidate's "fresh interval after activity
+ // stops" rule. Without this the FrameCallback could toggle the
+ // cursor on its very first post-settle frame.
+ if (mBlinkEnabled) {
+ mLastBlinkMs = SystemClock.uptimeMillis();
+ }
}
}
@@ -1309,45 +1466,16 @@ public final class TerminalView extends View {
* Cancel the terminal cursor blinker callbacks
*/
private void stopTerminalCursorBlinker() {
- if (mTerminalCursorBlinkerHandler != null && mTerminalCursorBlinkerRunnable != null) {
+ if (mBlinkEnabled) {
if (TERMINAL_VIEW_KEY_LOGGING_ENABLED)
mClient.logVerbose(LOG_TAG, "Stopping cursor blinker");
- mTerminalCursorBlinkerHandler.removeCallbacks(mTerminalCursorBlinkerRunnable);
- }
- }
-
- private class TerminalCursorBlinkerRunnable implements Runnable {
-
- private TerminalEmulator mEmulator;
- private final int mBlinkRate;
-
- // Initialize with false so that initial blink state is visible after toggling
- boolean mCursorVisible = false;
-
- public TerminalCursorBlinkerRunnable(TerminalEmulator emulator, int blinkRate) {
- mEmulator = emulator;
- mBlinkRate = blinkRate;
- }
-
- public void setEmulator(TerminalEmulator emulator) {
- mEmulator = emulator;
- }
-
- public void run() {
- try {
- if (mEmulator != null) {
- // Toggle the blink state and then invalidate() the view so
- // that onDraw() is called, which then calls TerminalRenderer.render()
- // which checks with TerminalEmulator.shouldCursorBeVisible() to decide whether
- // to draw the cursor or not
- mCursorVisible = !mCursorVisible;
- //mClient.logVerbose(LOG_TAG, "Toggling cursor blink state to " + mCursorVisible);
- mEmulator.setCursorBlinkState(mCursorVisible);
- invalidate();
- }
- } finally {
- // Recall the Runnable after mBlinkRate milliseconds to toggle the blink state
- mTerminalCursorBlinkerHandler.postDelayed(this, mBlinkRate);
+ mBlinkEnabled = false;
+ // The FrameCallback re-posts itself only while mBlinkEnabled is true; it will
+ // drain naturally on the next firing. If no invalidate is pending either, also
+ // remove it so we don't keep waking the Choreographer for a no-op.
+ if (mFramePosted && !mInvalidatePending) {
+ mChoreographer.removeFrameCallback(mFrameCallback);
+ mFramePosted = false;
}
}
}
@@ -1455,6 +1583,15 @@ public final class TerminalView extends View {
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
+ // Stop the VSYNC-aligned blink/invalidate driver and unpost the shared
+ // FrameCallback so it doesn't leak this View past detach.
+ mBlinkEnabled = false;
+ mInvalidatePending = false;
+ if (mFramePosted) {
+ mChoreographer.removeFrameCallback(mFrameCallback);
+ mFramePosted = false;
+ }
+
if (mTextSelectionCursorController != null) {
// Might solve the following exception
// android.view.WindowLeaked: Activity com.termux.app.TermuxActivity has leaked window android.widget.PopupWindow