diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/terminal/AnsiTerminalEmulator.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/terminal/AnsiTerminalEmulator.kt index 78efcf11d..1b15eba64 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/terminal/AnsiTerminalEmulator.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/terminal/AnsiTerminalEmulator.kt @@ -20,10 +20,13 @@ import kotlin.math.min * @param maxLines how many lines of scrollback to keep; the oldest are dropped first */ class AnsiTerminalEmulator( - private val columns: Int = DEFAULT_COLUMNS, - private val rows: Int = DEFAULT_ROWS, + columns: Int = DEFAULT_COLUMNS, + rows: Int = DEFAULT_ROWS, private val maxLines: Int = DEFAULT_MAX_LINES, ) { + private var columns = columns + private var rows = rows + init { require(columns > 0) { "columns must be positive" } require(rows > 0) { "rows must be positive" } @@ -59,6 +62,25 @@ class AnsiTerminalEmulator( revision++ } + /** + * Follows a change of screen size. Text already on screen stays as it was wrapped; new output + * wraps at the new width, and absolute cursor addressing uses the new height. + */ + fun resize( + columns: Int, + rows: Int, + ) { + require(columns > 0) { "columns must be positive" } + require(rows > 0) { "rows must be positive" } + if (columns == this.columns && rows == this.rows) return + this.columns = columns + this.rows = rows + cursorColumn = cursorColumn.coerceAtMost(columns - 1) + savedColumn = savedColumn.coerceAtMost(columns - 1) + wrapPending = false + revision++ + } + /** Empties the scrollback and homes the cursor; the current text style is kept. */ fun clear() { lines.clear() diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/workspace/TerminalViewModel.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/workspace/TerminalViewModel.kt index 73e5e0618..9973786a5 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/workspace/TerminalViewModel.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/workspace/TerminalViewModel.kt @@ -106,12 +106,18 @@ class TerminalViewModel( private var columns = 0 private var rows = 0 - /** The screen measured itself; start the shell at that size. Later calls are ignored. */ + /** + * The screen measured itself: the first call starts the shell at that size, and later calls + * resize it, for example when the keyboard opens or the device rotates. + */ fun open( columns: Int, rows: Int, ) { - if (_state.value.status != TerminalStatus.IDLE) return + if (_state.value.status != TerminalStatus.IDLE) { + resize(columns, rows) + return + } // The same bounds the pty is sized with, so what the shell wraps to is what is drawn. this.columns = columns.coerceIn(LocalTerminalLauncher.MIN_COLUMNS, LocalTerminalLauncher.MAX_COLUMNS) this.rows = rows.coerceIn(LocalTerminalLauncher.MIN_ROWS, LocalTerminalLauncher.MAX_ROWS) @@ -119,6 +125,27 @@ class TerminalViewModel( start() } + private var resizeJob: Job? = null + + private fun resize( + columns: Int, + rows: Int, + ) { + val newColumns = columns.coerceIn(LocalTerminalLauncher.MIN_COLUMNS, LocalTerminalLauncher.MAX_COLUMNS) + val newRows = rows.coerceIn(LocalTerminalLauncher.MIN_ROWS, LocalTerminalLauncher.MAX_ROWS) + if (newColumns == this.columns && newRows == this.rows) return + this.columns = newColumns + this.rows = newRows + publish { resize(newColumns, newRows) } + // The keyboard animates the screen through many sizes; the shell only needs the last one. + resizeJob?.cancel() + resizeJob = + viewModelScope.launch { + delay(RESIZE_SETTLE_MILLIS) + synchronized(lock) { session }?.resize(newColumns, newRows) + } + } + /** Starts a fresh shell after the previous one ended or failed to start. History stays on screen. */ fun restart() { val status = _state.value.status @@ -149,10 +176,12 @@ class TerminalViewModel( } private suspend fun run() { + val startColumns = columns + val startRows = rows val opened = try { withContext(ioDispatcher) { - sessions.open(TerminalOpenRequest(startDirectory, columns, rows)).also(::adopt) + sessions.open(TerminalOpenRequest(startDirectory, startColumns, startRows)).also(::adopt) } } catch (cancelled: CancellationException) { throw cancelled @@ -165,6 +194,8 @@ class TerminalViewModel( return } _state.update { it.copy(status = TerminalStatus.RUNNING) } + // The screen may have changed size while the shell was starting. + if (columns != startColumns || rows != startRows) opened.resize(columns, rows) try { withContext(ioDispatcher) { opened.output.collect(::receive) } // Output ends before the exit code is published by a hair; waiting for it here keeps the @@ -367,6 +398,9 @@ class TerminalViewModel( /** How often the servers the shell announced are asked whether they still answer. */ internal const val SERVER_PROBE_INTERVAL_MILLIS = 2_000L + /** How long the screen size must stay put before the shell is told about it. */ + const val RESIZE_SETTLE_MILLIS = 150L + /** How many of the newest screen lines are searched for server addresses after each burst of output. */ private const val SCAN_TAIL_LINES = 200 private const val TAG = "TerminalViewModel" diff --git a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/LocalTerminalLauncher.kt b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/LocalTerminalLauncher.kt index c598ae82c..e5056bc4e 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/LocalTerminalLauncher.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/LocalTerminalLauncher.kt @@ -17,12 +17,16 @@ object LocalTerminalLauncher { const val MIN_ROWS = 5 const val MAX_ROWS = 100 + /** Where a session's resize pipe lives inside the sandbox; the workspace is shared with the app. */ + const val RESIZE_PIPE_DIRECTORY = ".andcode/terminal" + fun command( runtime: LocalRuntimeInstaller.InstalledRuntime, workspaceHostDir: File, startDirectory: String?, columns: Int, rows: Int, + resizePipeName: String? = null, ): List = prootCommandPrefix(runtime.commandSuite, runtime.rootfs, workspaceHostDir) + listOf( @@ -31,7 +35,12 @@ object LocalTerminalLauncher { "/root", "/usr/bin/script", "-qefc", - shellScript(startDirectory, columns, rows), + shellScript( + startDirectory, + columns, + rows, + resizePipeName?.let { "/workspace/$RESIZE_PIPE_DIRECTORY/$it" }, + ), "/dev/null", ) @@ -44,6 +53,7 @@ object LocalTerminalLauncher { startDirectory: String?, columns: Int, rows: Int, + resizePipe: String? = null, ): String { val size = "stty rows ${rows.coerceIn(MIN_ROWS, MAX_ROWS)} cols ${columns.coerceIn(MIN_COLUMNS, MAX_COLUMNS)} 2>/dev/null" // Only an absolute path: anything else could be read by `cd` as an option or resolve against @@ -54,7 +64,25 @@ object LocalTerminalLauncher { ?.let { "cd ${AntigravitySandboxLauncher.shellQuote(it)} 2>/dev/null || cd /root" } ?: "cd /root" val shell = "if command -v bash >/dev/null 2>&1; then exec bash -l; else exec sh -l; fi" - return "$size; $directory; $shell" + val resizer = resizePipe?.let { "${resizeHelper(it)}; " }.orEmpty() + return "$size; $resizer$directory; $shell" + } + + /** + * The pty can only be resized from inside the sandbox, so a helper there reads "rows columns" + * lines from a named pipe the app writes to and applies them with `stty -F`. Changing the size + * makes the kernel send SIGWINCH to the foreground program, which redraws for the new screen. + * The helper polls once a second whether the shell is still running and leaves with it, so it + * never keeps the sandbox alive after the shell exits. + */ + internal fun resizeHelper(pipe: String): String { + val quoted = AntigravitySandboxLauncher.shellQuote(pipe) + val directory = AntigravitySandboxLauncher.shellQuote(pipe.substringBeforeLast('/')) + val loop = + "trap '' HUP; exec 3<>$quoted; while kill -0 \"\$p\" 2>/dev/null; do " + + "if read -t 1 r c <&3; then stty -F \"\$t\" rows \"\$r\" cols \"\$c\" 2>/dev/null; fi; done; rm -f $quoted" + return "if mkdir -p $directory 2>/dev/null && rm -f $quoted && mkfifo $quoted 2>/dev/null; then " + + "t=\$(tty); p=\$\$; ($loop) /dev/null 2>&1 & fi" } fun environment( @@ -86,6 +114,8 @@ class LocalTerminalSessionFactory( val runtime = installedRuntimeProvider() ?: throw TerminalUnavailableException() val prootTmp = File(runtimeDirectory, "proot-tmp").apply { mkdirs() } val workspace = File(runtimeDirectory, "workspace").apply { mkdirs() } + val pipeName = "${java.util.UUID.randomUUID().toString().replace("-", "")}.size" + val pipe = File(workspace, "${LocalTerminalLauncher.RESIZE_PIPE_DIRECTORY}/$pipeName") val process = ProcessBuilder( LocalTerminalLauncher.command( @@ -94,6 +124,7 @@ class LocalTerminalSessionFactory( startDirectory = request.startDirectory, columns = request.columns, rows = request.rows, + resizePipeName = pipeName, ), ) .redirectErrorStream(true) @@ -102,6 +133,6 @@ class LocalTerminalSessionFactory( environment().putAll(LocalTerminalLauncher.environment(runtime, prootTmp)) } .start() - ProcessTerminalSession(process) + ProcessTerminalSession(process, resizePipe = pipe) } } diff --git a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/ProcessTerminalSession.kt b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/ProcessTerminalSession.kt index f94634828..c6d90dc0c 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/ProcessTerminalSession.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/ProcessTerminalSession.kt @@ -1,5 +1,7 @@ package com.yugahashimoto.andcode.runtime.local +import android.system.Os +import android.system.OsConstants import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow @@ -8,6 +10,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn +import java.io.File import java.io.IOException import java.io.InputStreamReader import java.util.concurrent.Executors @@ -24,6 +27,8 @@ import java.util.concurrent.atomic.AtomicBoolean class ProcessTerminalSession( private val process: Process, private val killTree: (Process) -> Unit = ::killProcessTree, + private val resizePipe: File? = null, + private val writeResize: (File, String) -> Unit = ::writeToPipe, ) : TerminalSession { private val mutableExitCode = MutableStateFlow(null) override val exitCode: StateFlow = mutableExitCode.asStateFlow() @@ -97,6 +102,27 @@ class ProcessTerminalSession( } } + override fun resize( + columns: Int, + rows: Int, + ) { + val pipe = resizePipe ?: return + if (closed.get()) return + try { + input.execute { + try { + writeResize(pipe, "$rows $columns\n") + } catch (e: Exception) { + // No helper is listening (it could not start, or the shell has gone); the + // screen keeps working at the size the shell already has. + Log.w(TAG, "Could not resize the terminal", e) + } + } + } catch (_: RejectedExecutionException) { + // Raced with the shell exiting. + } + } + override fun close() { if (!closed.compareAndSet(false, true)) return input.shutdownNow() @@ -112,6 +138,7 @@ class ProcessTerminalSession( } finally { // Whatever the tree walk managed, the root must not outlive the session. process.destroyForcibly() + resizePipe?.delete() } }, "terminal-close", @@ -128,3 +155,20 @@ class ProcessTerminalSession( const val EXIT_UNKNOWN = -1 } } + +/** + * Writes [line] to the named pipe at [pipe] without waiting for a reader: opening a pipe for + * writing would otherwise block until one appears, which it never does once the helper is gone. + */ +private fun writeToPipe( + pipe: File, + line: String, +) { + val fd = Os.open(pipe.path, OsConstants.O_WRONLY or OsConstants.O_NONBLOCK, 0) + try { + val bytes = line.toByteArray(Charsets.UTF_8) + Os.write(fd, bytes, 0, bytes.size) + } finally { + Os.close(fd) + } +} diff --git a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/TerminalSession.kt b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/TerminalSession.kt index f436ae420..347d91d85 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/TerminalSession.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/TerminalSession.kt @@ -24,6 +24,15 @@ interface TerminalSession { /** Sends [text] to the shell as typed input. Never blocks, and is dropped once the session is closed. */ fun write(text: String) + /** + * Tells the shell, and whatever runs in the foreground, that the screen is now [columns] by + * [rows]. Never blocks; a session that cannot be resized ignores it. + */ + fun resize( + columns: Int, + rows: Int, + ) = Unit + /** Ends the session and everything running inside it. Safe to call more than once. */ fun close() } diff --git a/app/src/test/java/com/yugahashimoto/andcode/feature/terminal/AnsiTerminalEmulatorTest.kt b/app/src/test/java/com/yugahashimoto/andcode/feature/terminal/AnsiTerminalEmulatorTest.kt index cf50fb13d..ba878c321 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/feature/terminal/AnsiTerminalEmulatorTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/feature/terminal/AnsiTerminalEmulatorTest.kt @@ -397,4 +397,25 @@ class AnsiTerminalEmulatorTest { // Past the bound a style degrades to the default instead of growing the table. assertTrue(lines.last().spans.isEmpty()) } + + @Test + fun `wraps new output at the width it was resized to`() { + val terminal = AnsiTerminalEmulator(columns = 10, rows = 5) + terminal.feed("0123456789AB\r\n") + + terminal.resize(columns = 4, rows = 5) + terminal.feed("abcdef") + + assertEquals(listOf("0123456789", "AB", "abcd", "ef"), terminal.texts()) + } + + @Test + fun `resizing narrower keeps the cursor on screen`() { + val terminal = AnsiTerminalEmulator(columns = 20, rows = 5) + terminal.feed("0123456789012345") + + terminal.resize(columns = 8, rows = 5) + + assertTrue(terminal.snapshot().cursorColumn <= 7) + } } diff --git a/app/src/test/java/com/yugahashimoto/andcode/feature/workspace/TerminalViewModelTest.kt b/app/src/test/java/com/yugahashimoto/andcode/feature/workspace/TerminalViewModelTest.kt index 2316d0136..721ee6b8b 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/feature/workspace/TerminalViewModelTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/feature/workspace/TerminalViewModelTest.kt @@ -59,6 +59,15 @@ class TerminalViewModelTest { if (!closed) written += text } + val resizes = mutableListOf>() + + override fun resize( + columns: Int, + rows: Int, + ) { + resizes += columns to rows + } + override fun close() { closed = true finish(143) @@ -799,4 +808,23 @@ class TerminalViewModelTest { assertTrue(viewModel.state.value.servers.isEmpty()) viewModel.close() } + + @Test + fun `a new size while the shell runs resizes it once the screen settles`() = + runTest(dispatcher) { + val factory = FakeFactory() + val viewModel = viewModel(factory) + viewModel.open(60, 30) + runCurrent() + + viewModel.open(60, 20) + viewModel.open(60, 14) + runCurrent() + assertTrue("not before the size settles", factory.sessions.single().resizes.isEmpty()) + advanceTimeBy(TerminalViewModel.RESIZE_SETTLE_MILLIS + 1) + runCurrent() + + assertEquals(listOf(60 to 14), factory.sessions.single().resizes) + assertEquals(1, factory.requests.size) + } } diff --git a/app/src/test/java/com/yugahashimoto/andcode/runtime/local/LocalTerminalLauncherTest.kt b/app/src/test/java/com/yugahashimoto/andcode/runtime/local/LocalTerminalLauncherTest.kt index 3fc486009..70056117b 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/runtime/local/LocalTerminalLauncherTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/runtime/local/LocalTerminalLauncherTest.kt @@ -117,4 +117,28 @@ class LocalTerminalLauncherTest { assertEquals("C.UTF-8", environment["LANG"]) assertTrue(environment.containsKey("PROOT_TMP_DIR")) } + + @Test + fun `starts a resize helper on the given pipe before the shell`() { + val script = + LocalTerminalLauncher.shellScript( + startDirectory = null, + columns = 80, + rows = 24, + resizePipe = "/workspace/.andcode/terminal/abc.size", + ) + + val helper = script.indexOf("mkfifo '/workspace/.andcode/terminal/abc.size'") + assertTrue(helper > script.indexOf("stty rows 24 cols 80")) + assertTrue(helper < script.indexOf("exec bash -l")) + assertTrue(script.contains("stty -F")) + assertTrue("the helper leaves with the shell", script.contains("while kill -0")) + } + + @Test + fun `no resize helper without a pipe`() { + val script = LocalTerminalLauncher.shellScript(startDirectory = null, columns = 80, rows = 24) + + assertFalse(script.contains("mkfifo")) + } }