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
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@ class FakeEngine(open: List<String> = emptyList()) : AutoCloseable {
/** Every request [receive] has read from the profile's socket, the skipped ones included. */
val received: List<JSONObject> get() = game().received

/** Every request [receive] has read from the control socket, the skipped ones included. */
val controlReceived: List<JSONObject> get() = control.received

/** The UI's hello on the profile's socket: "instance" and "lastSeq" when it was attached to an engine before. */
val hello: JSONObject get() = game().hello

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,30 @@ class GameSwitcherTest {
compose.onNode(hasText(string(R.string.games_title))).assertDoesNotExist()
}

@Test
fun aGameOpenedBesideStartsWithTheSizeTheGameScreenGaveTheLast() {
showFromTheList(ALPHA.name)
beta.receive("setFront")
waitFor(titleReading(ALPHA.name, R.string.connection_connected, 1, 2))
// Mudlet's font, which the first mainArea tells the game screen, which then gives the main window its size
alpha.mainArea(800, 600, 100, 40, 0, 0, 800, 600)
// The test's clock recomposes only while the test waits on it, not while it reads a socket
compose.waitUntil(WAIT_MS) { EngineClient.session(ALPHA.name)?.windows?.state?.charWidth != null }
compose.waitForIdle()
val given = alpha.receiveLast("setMainWindowSize", readPast = true)

openTheSheet()
compose.onNode(hasText(string(R.string.game_open_another)) and hasClickAction()).performScrollTo()
activate(hasText(string(R.string.game_open_another)))
activate(hasContentDescription(string(R.string.profile_connect_to, GAMMA.name)))
beta.receive("openProfile")
// On the control socket, before it: the new profile's own socket exists only once it has opened
val frames = beta.controlReceived
val before = frames.subList((frames.size - 3).coerceAtLeast(0), frames.size - 1)
assertEquals(listOf("setScreenSize", "setMainWindowSize"), before.map { it.optString("t") })
assertEquals(given.getInt("w") to given.getInt("h"), before[1].getInt("w") to before[1].getInt("h"))
}

@Test
fun openAnotherGameOpensOneBesideThoseOpen_untilAsManyAsCanBeAre() {
showFromTheList(ALPHA.name)
Expand Down
63 changes: 52 additions & 11 deletions app/src/main/kotlin/org/mudlet/android/ui/EngineClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ import org.mudlet.android.engine.EngineSocket
import org.mudlet.android.protocol.EngineLink
import org.mudlet.android.protocol.EngineMessage
import org.mudlet.android.protocol.EngineRestore
import org.mudlet.android.protocol.MudletSize
import org.mudlet.android.protocol.OpenProfile
import org.mudlet.android.protocol.OpenProfileState
import org.mudlet.android.protocol.Profile
import org.mudlet.android.protocol.Requests
import org.mudlet.android.protocol.StartSizes
import org.mudlet.android.protocol.Transport
import org.mudlet.android.ui.game.ScriptWebPages
import java.io.IOException
Expand Down Expand Up @@ -65,6 +67,7 @@ object EngineClient {
private const val RESTART_AFTER_FAILED_ATTEMPTS = 6

private const val PREF_LAST_PROFILE = "lastProfile"
private const val PREF_START_SIZES = "startSizes"

private const val TAG = "EngineClient"

Expand Down Expand Up @@ -187,7 +190,12 @@ object EngineClient {
var screenSize: Pair<Int, Int>? = null
private set

/** The size of the window the app is drawn in, as `WxH` in dp; MainActivity keeps it. */
@Volatile
var window = ""

// Main thread only
private var startSizes: StartSizes? = null
private var startRequestedAt = 0L
private var detachStartedAt = 0L
private var lostAt = 0L
Expand All @@ -203,6 +211,7 @@ object EngineClient {
if (::app.isInitialized) return
app = context.applicationContext
lastProfile = prefs().getString(PREF_LAST_PROFILE, null)
startSizes = StartSizes.decode(prefs().getString(PREF_START_SIZES, null))
}

fun startEngine() {
Expand Down Expand Up @@ -336,6 +345,12 @@ object EngineClient {
sessions.forEach { it.changeSetting(setting, value) }
}

/** The game screen's console size: [setScreenSize], and the one the next profile opened starts with. */
fun setGameConsoleSize(columns: Int, rows: Int) {
keepStartSizes(StartSizes.withScreen(startSizes, startWindow(), columns, rows))
setScreenSize(columns, rows)
}

/** The console's size, which every open profile is given: all of them would show on this screen. */
fun setScreenSize(columns: Int, rows: Int) {
val size = columns to rows
Expand Down Expand Up @@ -365,30 +380,54 @@ object EngineClient {
/** Asks the engine to list its profiles again, as it does not see one added beside it, as an import adds one. */
fun refreshProfiles(onAnswer: (error: String?) -> Unit) = profileRequest(onAnswer) { Requests.listProfiles(it) }

/** The main window's [size] the game screen gives a profile that has no windows yet, which the next profile opened starts with. */
fun setStartMainWindowSize(size: MudletSize) = keepStartSizes(StartSizes.withMainWindow(startSizes, startWindow(), size))

// What decides the sizes besides the window: the app's text size and layout
private fun startWindow() = "$window ${Settings.textSize.value} ${ScriptWindowsClient.layoutMode}"

private fun keepStartSizes(sizes: StartSizes) {
if (sizes == startSizes) return
startSizes = sizes
prefs().edit { putString(PREF_START_SIZES, sizes.encode()) }
}

// Before the profile's own socket exists to give them, so its scripts read them from their first line
private fun sendStartSizes() {
startSizes?.requestsFor(startWindow())?.forEach(::send)
}

/** Opens and connects the profile [name], closing those open; Reconnect then goes to its address, or opens it again once none is. */
fun openProfile(name: String, password: String?, onAnswer: (error: String?) -> Unit) = profileRequest({ error ->
if (error == null) opened(name)
onAnswer(error)
}) { Requests.openProfile(name, password, proxyPassword = proxyPasswordOf(name), connect = true, alongside = false, id = it) }
fun openProfile(name: String, password: String?, onAnswer: (error: String?) -> Unit) {
sendStartSizes()
profileRequest({ error ->
if (error == null) opened(name)
onAnswer(error)
}) { Requests.openProfile(name, password, proxyPassword = proxyPasswordOf(name), connect = true, alongside = false, id = it) }
}

/**
* Opens and connects the profile [name], with [password] for this run, beside those open, and makes it the front;
* one already open stays as it is, and comes to the front.
*/
fun openProfileAlongside(name: String, password: String?, onAnswer: (error: String?) -> Unit) = profileRequest({ error ->
if (error == null) {
opened(name)
setFront(name)
}
onAnswer(error)
}) { Requests.openProfile(name, password, proxyPassword = proxyPasswordOf(name), connect = true, alongside = true, id = it) }
fun openProfileAlongside(name: String, password: String?, onAnswer: (error: String?) -> Unit) {
sendStartSizes()
profileRequest({ error ->
if (error == null) {
opened(name)
setFront(name)
}
onAnswer(error)
}) { Requests.openProfile(name, password, proxyPassword = proxyPasswordOf(name), connect = true, alongside = true, id = it) }
}

/**
* Opens the profile [name] without connecting it, as desktop's Offline, with [password] for a later connection; beside
* those open, as the front, when any are.
*/
fun openProfileOffline(name: String, password: String?, onAnswer: (error: String?) -> Unit) {
val alongside = sessions.isNotEmpty()
sendStartSizes()
profileRequest({ error ->
if (error == null) {
opened(name)
Expand Down Expand Up @@ -559,6 +598,8 @@ object EngineClient {
}
// What it says is in front now stands: it had any setFront sent before
requestedFront = null
// For the profiles a restore opens after this, as for those the player opens
sendStartSizes()
// A profile's socket that went with the engine may be back: no need to wait out the link's retry
sessions.forEach(ProfileSession::wake)
val now = SystemClock.elapsedRealtime()
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/kotlin/org/mudlet/android/ui/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.res.stringResource
import androidx.core.content.IntentCompat
import androidx.core.content.edit
Expand Down Expand Up @@ -97,6 +100,9 @@ class MainActivity : ComponentActivity() {
gameLink = savedInstanceState.getString(STATE_GAME_LINK)?.let(TelnetLink::parse)
}
setContent {
// The window a profile opened from here will be drawn in, which the sizes it starts with are kept for
val window = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.let { "${it.width.toDp().value.toInt()}x${it.height.toDp().value.toInt()}" } }
SideEffect { if (window != "0x0") EngineClient.window = window }
MudletTheme {
val explainEngineStopped = EngineClient.engineStoppedInBackground && !engineStoppedAnswered
AppNavigation(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ private fun ProfileGameScreen(
textSizeSp = textSizeSp,
colors = colors,
onTextSize = Settings.textSize::set,
onScreenSize = EngineClient::setScreenSize,
onScreenSize = EngineClient::setGameConsoleSize,
consoleModifier.tourTarget(TourTarget.CONSOLE),
links = c.links,
onMakeTrigger = onMakeTrigger,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,11 @@ private fun WindowsArea(
// A new engine instance has none of what the last was told
val attaches = EngineClient.front.attaches
LaunchedEffect(layout.mainWindowSize, attaches) { layout.mainWindowSize?.let(client::setMainWindowSize) }
// What a profile with no windows yet is given here, for the next one opened before this screen has measured it
val startSize = remember(windows.charWidth, w, h, fitted, metrics, headerHeight) {
WindowLayout.of(ScriptWindows(charWidth = windows.charWidth), WindowLayout.Area(w, h, fitted, metrics.charWidth, headerHeight, null)).mainWindowSize
}
LaunchedEffect(startSize) { startSize?.let(EngineClient::setStartMainWindowSize) }
LaunchedEffect(layout.placements, attaches) {
for ((name, placement) in layout.placements) client.placeUserWindow(name, placement)
}
Expand Down
4 changes: 2 additions & 2 deletions docs/ai-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ Procedures too long for this file are in `.agents/skills/<name>/SKILL.md` (Claud
- Stored names are the player's data: renaming one alone orphans what players already have. Rename one only with a
migration that runs before the first read, and a test that reads the old name. They are:
- the application id `org.mudlet.mudlet` (`.ptb` for the PTB);
- the SharedPreferences `settings` (the keys in `data/Settings.kt`), `engine` (`qpaPlatform`, `lastProfile`, and
`lastHost:`, `lastPort:` and `lastTls:` before a profile's name) and `ui`;
- the SharedPreferences `settings` (the keys in `data/Settings.kt`), `engine` (`qpaPlatform`, `lastProfile`,
`startSizes`, and `lastHost:`, `lastPort:` and `lastTls:` before a profile's name) and `ui`;
- `PasswordStore`'s file `passwords/profiles.json`, its keys (the lowercased profile name, and `proxy:` before it
for the proxy's password) and KeyStore alias `profile-passwords`;
- the engine's files: `files/mudlet/` (`profiles/<name>/`, `profile-order.json`, and what Mudlet keeps under the
Expand Down
18 changes: 16 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -1190,6 +1190,10 @@ And the style sheet `setCmdLineStyleSheet()` gives a command line (`ScriptWindow
And a profile's SOCKS5 proxy as the desktop's Connection preferences hold it, with its password given for the run
as the game's is (`proxy()`, `setProxy()`, `setProxyPassword()`, `0042-headless-proxy.patch`; see `getProxy` in
[`protocol.md`](protocol.md)).
And the main window's size, or the console's columns and rows, given with the start, so a profile's scripts read it from
their first line (`THeadlessSession::Options::mainWindowSize` and `screenSize`, `0043-headless-main-window-size-at-start.patch`).
And the starter UI's chat welcome printed again at its window's width when the window grows, while it is all the chat
window holds (`BaseUI.fitDock()`, `0044-starter-ui-chat-welcome-refit.patch`).
[`c-device.md`](decisions/hosting-results/c-device.md) has the emulator run of the earlier build, which read Mudlet's console model
and needed a patch.

Expand Down Expand Up @@ -1226,8 +1230,8 @@ keeps the profiles' passwords in the KeyStore.
| `commandLineTextRequested` (`printCmdLine()` and the like) | `commandLine` |
| `scriptWindows()`, read at `profileLoaded`, then at each `scriptWindowsChanged` | `windows`, only the windows that changed and those `removed`; all of them, with `full`, to a UI that attaches. A close sends an empty list |
| `windowLines()`, the last 300 rows, at `profileLoaded` and at each `windowTextChanged` | `windowText`; any rows on request with `getWindowText` |
| `setMainWindowSize()`, then `mainConsoleGrid()`, `mainConsoleTextRect()` and `mainBorderColor()` at `profileLoaded` and at each `mainConsoleAreaChanged` and `mainBorderColorChanged` | `setMainWindowSize`, kept and given again to each profile as it loads; `mainArea` |
| `setScreenSize()` until the profile has the main window's size, then `setGameScreenSize()` (carried), at `profileLoaded`, at the start's end and at each change | `setScreenSize`, kept and given again to each profile as it loads |
| `Options::mainWindowSize` at the start (carried) and `setMainWindowSize()`, then `mainConsoleGrid()`, `mainConsoleTextRect()` and `mainBorderColor()` at `profileLoaded` and at each `mainConsoleAreaChanged` and `mainBorderColorChanged` | `setMainWindowSize`, kept and given to each profile as it starts, before its first script, and again as it loads; on the control socket, only kept, for the profiles opened after it; `mainArea` |
| `Options::screenSize` at the start while it has no main window's size, `setScreenSize()` until the profile has the main window's size, then `setGameScreenSize()` (carried), at `profileLoaded`, at the start's end and at each change | `setScreenSize`, kept and given to each profile as it starts and again as it loads; on the control socket, only kept, for the profiles opened after it |
| `setUserWindowGeometry()`, `closeUserWindow()` | `placeUserWindow`, `closeUserWindow` |
| `submitWindowCommandLine()`; `windowCommandLineTextChanged` | `sendWindowCommandLine`; `windowCommandLine` |
| `labelContent()` of each label, read with `scriptWindows()` | `label` after the `windows`, for each label whose content changed; every label to a UI that attaches |
Expand Down Expand Up @@ -1324,6 +1328,11 @@ Android options (`scripts/build-libmudlet-desktop.sh`) to run it. It checks:
size and the game is told the console's columns and rows (below 40 as 40), not that size's grid, also after a new
main window's size; given both before the profile loads, the same for `getMainWindowSize()` and the game; and with
a main window's size the loading profile refuses, `setScreenSize` sizing the main window and reaching the game;
- the sizes given before a profile opens, on its own socket or on the control socket: its scripts read them from their
first line, so a Geyser `MiniConsole` with `autoWrap` that echoes as the profile loads wraps at the console's
columns; the control socket refusing a size as a profile's socket does, and leaving an open profile its own;
- the starter UI's chat window built in a narrow main window that then widens: its welcome printed again at the new
width, and chat in it keeping its lines through a resize;
- script windows: a Geyser `MiniConsole` as `windows` with its geometry, and its `cecho()` as `windowText` with its
colours; a Geyser `UserWindow` placed by `placeUserWindow`, which raises `sysUserWindowResizeEvent`; the size from
`setMainWindowSize` before the profile loads, `setBorderLeft()` and `setBorderColor()`, as `mainArea`;
Expand Down Expand Up @@ -2316,6 +2325,10 @@ alias of run-lua-code, one of desktop Mudlet's default packages, which a profile
grid). Narrower, the borders become bands above and below the console, and the side windows and docks become
tabs below it; a tab opens its window over the console, its back button or the system's Back closes it.
- A window's text is readable, its newest line in view; scrolled back, it stays put.
- A window that wraps to its width, such as the starter UI's chat window in a game with no GUI of its own, has its
first lines wrapped at its full width, also in the profile opened first after the app starts.
- With the starter UI, turn a tablet or unfold a phone so the game area widens: the chat window's welcome line
fills its new width, while chat the game sent there keeps the lines it arrived on.
- A console a script gave a scroll bar (`lua enableScrollBar("<name>")`) with more rows than fit has a thumb at
its right edge, which moves as the rows scroll and scrolls them when dragged; `disableScrollBar` takes it away.
- With TalkBack on: swiping goes from the console to the input line, then the pinned commands, then
Expand Down Expand Up @@ -2446,6 +2459,7 @@ alias of run-lua-code, one of desktop Mudlet's default packages, which a profile
- Pinch the window with two fingers: its text grows or shrinks as the fingers move, the main console's does not,
and once they lift `win <size>` shows on the main console and `lua echo(getFontSize("win"))` gives that size. New
text in the window wraps to its new width. One finger still scrolls it, and a tap on a link in it still follows.
Text already in the window keeps the rows it had, as on the desktop.
- `lua win:setFontSize(8)` changes nothing that stays: the window goes back to the pinched size. Close and reopen the
profile, or kill the app and start it again: the window comes back at the pinched size.
- Tap the window twice with two fingers: it goes back to 8 (the size its script last gave it), and a later
Expand Down
1 change: 1 addition & 0 deletions docs/multi-profile.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ New on the control socket:
| `closeProfile` | UI→E | `name`, `id`? | Saves and closes that profile, with its `sysExitEvent`; its socket closes. Answered by `openProfiles` or `error`. |
| `setFront` | UI→E | `name` | The profile the player is looking at: raises `sysProfileFocusChangeEvent`, as a desktop tab change does. |
| `markSeen` | UI→E | `name`, `seq` | The player has seen that profile's lines up to `seq`: clears `attention`, and `unread` counts from there. |
| `setScreenSize`, `setMainWindowSize` | UI→E | as on a profile's socket | Kept, and given to each profile opened after them as it starts, so its first script reads them; no profile open now takes them (version 48). |
| `openProfiles` | E→UI | `profiles`: `name`, `slot`, `socket`, `state`, `connection`, `lastSeq`, `unread`, `attention`, `front`; `re`? | Every open profile, in the order opened. `state` is `starting`, `loaded`, `closing` or `restoring`. `attention` is set by `alert()`, the bell or new data while minimized, until seen. Sent on attach and on every change (line counts coalesced to every 500 ms), and as the answer to `openProfile` and `closeProfile`. |

The profile opened last becomes the front; when the front closes, the next one to the right takes over, else the one to
Expand Down
Loading
Loading